// Multi-step Consultation booking modal

const INTERESTS = [
  { id: 'engagement', label: 'Engagement Ring' },
  { id: 'bespoke', label: 'Custom Design' },
  { id: 'wedding', label: 'Wedding & Eternity' },
  { id: 'diamond', label: 'A Loose Diamond' },
  { id: 'gift', label: 'A Gift' },
  { id: 'repair', label: 'Service / Repair' },
];

const BOUTIQUE_OPTS = [
  { id: 'deira', label: 'Deira Gold Souq \u00b7 Flagship' },
  { id: 'gdp', label: 'Gold & Diamond Park \u00b7 Factory Outlet' },
  { id: 'eva-gdp', label: 'Eva \u2014 Gold & Diamond Park' },
  { id: 'eva-madinat', label: 'Eva Gems \u2014 Madinat Jumeirah' },
  { id: 'video', label: 'Video Consult (WhatsApp)' },
];

const TIMES = ['10:30', '12:00', '14:00', '16:00', '17:30', '19:00'];

function todayPlus(days) {
  const d = new Date();
  d.setDate(d.getDate() + days);
  return d;
}
function fmtDate(d) {
  return d.toLocaleDateString('en-GB', { weekday: 'short', day: '2-digit', month: 'short' });
}
function fmtISO(d) {
  return d.toISOString().slice(0, 10);
}

const DateChips = ({ value, onChange }) => {
  const days = Array.from({ length: 7 }, (_, i) => todayPlus(i + 1));
  return (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 8 }}>
      {days.map(d => {
        const iso = fmtISO(d);
        const on = value === iso;
        return (
          <button key={iso} onClick={() => onChange(iso)} className={`mm-radio ${on ? 'on' : ''}`}
                  style={{ flex: 'none', minWidth: 0, padding: '10px 14px' }}>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase' }}>{fmtDate(d)}</span>
          </button>
        );
      })}
    </div>
  );
};

const BookingModal = ({ open, onClose, prefill }) => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    interest: prefill?.interest || 'engagement',
    boutique: prefill?.boutique || 'deira',
    date: fmtISO(todayPlus(2)),
    time: '14:00',
    name: '', email: '', phone: '', notes: '',
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    if (open) { setStep(0); setSubmitted(false); setErrors({}); }
  }, [open]);

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));

  const validateContact = () => {
    const e = {};
    if (!data.name.trim()) e.name = 'Please tell us your name.';
    if (!/^.+@.+\..+$/.test(data.email)) e.email = 'A valid email, please.';
    if (data.phone && !/^[\d+\s\-()]{6,}$/.test(data.phone)) e.phone = 'That phone number looks off.';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (step < 2) setStep(step + 1);
    else if (step === 2) {
      if (validateContact()) setSubmitted(true);
    }
  };
  const back = () => { if (step > 0) setStep(step - 1); };

  if (!open) return null;

  const STEP_LABELS = ['Interest', 'When & Where', 'Your Details'];

  return (
    <div className="mm-modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="mm-modal" role="dialog" aria-modal="true">
        <button className="mm-modal-close" onClick={onClose} aria-label="Close"><Icon name="x" size={20} /></button>
        <div className="mm-form-card">
          <div className="mm-form-left">
            <div>
              <Eyebrow>Private Consultation</Eyebrow>
              <h3 style={{ marginTop: 18 }}>An unhurried hour <em className="italic-accent" style={{ color: 'var(--gold-soft)' }}>at the bench.</em></h3>
              <p style={{ marginTop: 16 }}>
                Choose a boutique, a date and a time. One of our advisers \u2014 Abhijeet, Joyce, Sam, Joy, Rohan \u2014 will be expecting you, with coffee and the right cases pulled.
              </p>
            </div>
            <div className="mm-form-left-feats">
              <div className="mm-form-left-feat"><Icon name="check" size={16} /> No pressure. No sales tactics.</div>
              <div className="mm-form-left-feat"><Icon name="check" size={16} /> Bring a picture, a sketch, a stone.</div>
              <div className="mm-form-left-feat"><Icon name="check" size={16} /> Bespoke designs realised in under an hour.</div>
              <div className="mm-form-left-feat"><Icon name="check" size={16} /> Authentication and warranty included.</div>
            </div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.6 }}>
              Prefer WhatsApp? &nbsp;<a href="https://wa.me/971554758003" style={{ color: 'var(--gold-soft)', borderBottom: '1px solid currentColor' }}>+971 55 475 8003</a>
            </div>
          </div>
          <div className="mm-form-right">
            {!submitted ? (
              <React.Fragment>
                <div className="mm-form-stepper">
                  {STEP_LABELS.map((l, i) => (
                    <div key={l} className={`mm-form-step ${i < step ? 'done' : ''} ${i === step ? 'on' : ''}`}>
                      <span className="mm-form-step-label">0{i+1} {l}</span>
                    </div>
                  ))}
                </div>

                {step === 0 && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 32 }}>
                    <Eyebrow>Step 01 of 03</Eyebrow>
                    <h3 style={{ fontSize: 32 }}>What brings you in?</h3>
                    <div className="mm-radio-grid">
                      {INTERESTS.map(o => (
                        <label key={o.id} className={`mm-radio ${data.interest === o.id ? 'on' : ''}`}>
                          <input type="radio" name="interest" value={o.id}
                                 checked={data.interest === o.id}
                                 onChange={() => update('interest', o.id)}
                                 style={{ display: 'none' }} />
                          <span className="mm-radio-dot"></span>
                          {o.label}
                        </label>
                      ))}
                    </div>
                    <div className="mm-form-field">
                      <label>Anything we should know? (optional)</label>
                      <textarea value={data.notes} onChange={e => update('notes', e.target.value)} rows="2"
                                placeholder="Carat range, budget, reference photos, an idea you've been carrying around \u2026" />
                    </div>
                  </div>
                )}

                {step === 1 && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20, marginTop: 32 }}>
                    <Eyebrow>Step 02 of 03</Eyebrow>
                    <h3 style={{ fontSize: 32 }}>When &amp; where</h3>
                    <div className="mm-form-field">
                      <label>Boutique</label>
                      <select value={data.boutique} onChange={e => update('boutique', e.target.value)}>
                        {BOUTIQUE_OPTS.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
                      </select>
                    </div>
                    <div className="mm-form-field">
                      <label>Date</label>
                      <DateChips value={data.date} onChange={v => update('date', v)} />
                    </div>
                    <div className="mm-form-field">
                      <label>Time</label>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                        {TIMES.map(t => (
                          <button key={t} onClick={() => update('time', t)}
                                  className={`mm-radio ${data.time === t ? 'on' : ''}`}
                                  style={{ flex: 'none', padding: '10px 14px', fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.16em' }}>
                            {t}
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>
                )}

                {step === 2 && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 20, marginTop: 32 }}>
                    <Eyebrow>Step 03 of 03</Eyebrow>
                    <h3 style={{ fontSize: 32 }}>Your details</h3>
                    <div className="mm-form-field">
                      <label>Full name</label>
                      <input type="text" value={data.name} onChange={e => update('name', e.target.value)} placeholder="As you'd like to be greeted" />
                      {errors.name && <span className="err">{errors.name}</span>}
                    </div>
                    <div className="mm-form-row">
                      <div className="mm-form-field">
                        <label>Email</label>
                        <input type="email" value={data.email} onChange={e => update('email', e.target.value)} placeholder="you@example.com" />
                        {errors.email && <span className="err">{errors.email}</span>}
                      </div>
                      <div className="mm-form-field">
                        <label>Phone (optional)</label>
                        <input type="tel" value={data.phone} onChange={e => update('phone', e.target.value)} placeholder="+971 \u2026" />
                        {errors.phone && <span className="err">{errors.phone}</span>}
                      </div>
                    </div>
                    <div style={{ background: 'var(--champagne)', padding: 20, marginTop: 12 }}>
                      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--ink-mute)', marginBottom: 10 }}>Summary</div>
                      <div style={{ fontFamily: 'var(--display)', fontSize: 20, lineHeight: 1.3 }}>
                        {INTERESTS.find(i => i.id === data.interest)?.label}
                        {' \u00b7 '}
                        {BOUTIQUE_OPTS.find(b => b.id === data.boutique)?.label.split(' \u00b7 ')[0]}
                      </div>
                      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.18em', color: 'var(--ink-soft)', marginTop: 8 }}>
                        {fmtDate(new Date(data.date))} \u00b7 {data.time}
                      </div>
                    </div>
                  </div>
                )}

                <div className="mm-form-actions">
                  {step > 0
                    ? <Btn variant="ghost" small onClick={back}><Icon name="arrowL" size={12} /> Back</Btn>
                    : <span></span>}
                  <Btn variant="primary" small onClick={next}>
                    {step < 2 ? 'Continue' : 'Confirm Booking'}
                    <Icon name="arrow" size={12} />
                  </Btn>
                </div>
              </React.Fragment>
            ) : (
              <div className="mm-form-confirmation">
                <div className="check"><Icon name="check" size={28} /></div>
                <Eyebrow>Confirmed</Eyebrow>
                <h3 style={{ marginTop: 12 }}>We'll see you, {data.name.split(' ')[0]}.</h3>
                <p style={{ color: 'var(--ink-mute)', marginTop: 12, maxWidth: '38ch', marginInline: 'auto' }}>
                  Your private consultation is booked for <strong>{fmtDate(new Date(data.date))} at {data.time}</strong> at
                  the <strong>{BOUTIQUE_OPTS.find(b => b.id === data.boutique)?.label.split(' \u00b7 ')[0]}</strong> boutique.
                  We've sent confirmation to {data.email}. An adviser will WhatsApp you the day before.
                </p>
                <div style={{ display: 'flex', justifyContent: 'center', gap: 10, marginTop: 32, flexWrap: 'wrap' }}>
                  <Btn variant="primary" small onClick={onClose}>Done</Btn>
                  <Btn variant="ghost" small href="https://wa.me/971554758003"><Icon name="whatsapp" size={12} /> Open WhatsApp</Btn>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { BookingModal });
