// Multi-step Book a Consultation flow — the conversion centrepiece.

function BookingFlow({ go, prefill }) {
  const [step, setStep] = useState(0); // 0 treatment, 1 surgeon, 2 slot, 3 details, 4 success
  const [data, setData] = useState({
    treatment: prefill?.treatment || null,
    surgeon: null,
    day: null,
    time: null,
    name: '',
    phone: '',
    email: '',
    countryCode: '+971',
    note: '',
    consent: false
  });

  const update = (patch) => setData(prev => ({ ...prev, ...patch }));

  const steps = [
    { n: '01', label: 'Treatment area' },
    { n: '02', label: 'Surgeon or doctor' },
    { n: '03', label: 'Preferred time' },
    { n: '04', label: 'Your details' }
  ];

  const treatments = [
    { id: 'plastic-surgery', label: 'Plastic Surgery', sub: 'Face · Breast · Body', icon: Icon.user, surgical: true },
    { id: 'skin', label: 'Skin & Aesthetics', sub: 'Injectables · Lasers · Facials', icon: Icon.sparkle, surgical: false },
    { id: 'body', label: 'Body Contouring', sub: 'CoolSculpting · Surgical', icon: Icon.body, surgical: false },
    { id: 'for-men', label: 'For Men', sub: 'Surgical & aesthetic', icon: Icon.man, surgical: true },
    { id: 'wellness', label: 'Wellness', sub: 'IV · Nutrition · Regenerative', icon: Icon.drop, surgical: false },
    { id: 'unsure', label: 'I\'m not sure yet', sub: 'A consultant will help triage', icon: Icon.alert, surgical: false }
  ];

  // suggest surgeons based on treatment
  const surgeonOptions = useMemo(() => {
    const isSurgicalEnquiry = treatments.find(t => t.id === data.treatment)?.surgical;
    if (data.treatment === 'unsure') return DOCTORS.slice(0, 6);
    if (isSurgicalEnquiry) return DOCTORS.filter(d => d.title.toLowerCase().includes('plastic') || d.title.toLowerCase().includes('specialist'));
    return DOCTORS.filter(d => !d.title.toLowerCase().includes('plastic'));
  }, [data.treatment]);

  // Mock 14-day calendar starting today
  const days = useMemo(() => {
    const out = [];
    const today = new Date();
    for (let i = 1; i <= 14; i++) {
      const d = new Date(today);
      d.setDate(today.getDate() + i);
      out.push({
        date: d,
        dayName: d.toLocaleDateString('en-US', { weekday: 'short' }),
        dayNum: d.getDate(),
        month: d.toLocaleDateString('en-US', { month: 'short' }),
        disabled: d.getDay() === 0 // Sundays "by appointment only"
      });
    }
    return out;
  }, []);

  const times = ['10:30', '11:30', '13:00', '14:30', '16:00', '17:30', '18:30', '19:30'];

  const next = () => setStep(s => Math.min(s + 1, 4));
  const back = () => setStep(s => Math.max(s - 1, 0));

  const canNext = (
    (step === 0 && data.treatment) ||
    (step === 1 && data.surgeon) ||
    (step === 2 && data.day && data.time) ||
    (step === 3 && data.name && data.phone && data.email && data.consent)
  );

  const selectedTreatment = treatments.find(t => t.id === data.treatment);
  const selectedSurgeon = DOCTORS.find(d => d.slug === data.surgeon);

  return (
    <div className="page-anim">
      <section style={{ padding: '32px 0 24px', borderBottom: '1px solid var(--line)' }}>
        <div className="container flex gap-2" style={{ alignItems: 'center', fontSize: 12, color: 'var(--ink-muted)' }}>
          <button onClick={() => go({ page: 'home' })} style={{ cursor: 'pointer', color: 'var(--ink-muted)' }}>Home</button>
          <span>›</span>
          <span style={{ color: 'var(--ink)' }}>Book a Consultation</span>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="booking-shell">
            <aside className="booking-aside">
              <div className="eyebrow" style={{ color: 'var(--bronze)' }}>Consultation</div>
              <h3 style={{ marginTop: 12 }}>
                {step < 4 ? 'A 45-minute conversation with the right consultant.' : 'Request received.'}
              </h3>
              {step < 4 && (
                <p>
                  We collect only what's needed to confirm your appointment. Medical history is taken
                  in person with the consultant, not in a form.
                </p>
              )}

              <div className="booking-stepper">
                {steps.map((s, i) => (
                  <div key={s.n} className={`booking-step ${step === i ? 'active' : step > i ? 'done' : ''}`}>
                    <span className="booking-step-num">
                      {step > i ? <Icon.check /> : s.n}
                    </span>
                    {s.label}
                  </div>
                ))}
              </div>

              {step >= 1 && data.treatment && (
                <div style={{ background: 'rgba(251,250,248,0.06)', padding: 16, borderRadius: 3, marginBottom: 16 }}>
                  <div className="eyebrow mb-1" style={{ color: 'var(--bronze)' }}>Your Selection</div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: 'var(--porcelain)', marginBottom: 6 }}>
                    {selectedTreatment?.label}
                  </div>
                  {selectedSurgeon && (
                    <div style={{ fontSize: 12, color: 'rgba(251,250,248,0.65)' }}>
                      with {selectedSurgeon.name}
                    </div>
                  )}
                  {data.day && data.time && (
                    <div style={{ fontSize: 12, color: 'rgba(251,250,248,0.65)', marginTop: 4 }}>
                      {data.day.dayName} {data.day.dayNum} {data.day.month} · {data.time}
                    </div>
                  )}
                </div>
              )}

              <div className="booking-aside-contact">
                <strong>Prefer to skip the form?</strong>
                <div>WhatsApp +971 4 384 5600</div>
                <div>Call · {CLINIC_INFO.phone}</div>
                <div style={{ marginTop: 8 }}>{CLINIC_INFO.email}</div>
              </div>
            </aside>

            <main className="booking-main">
              {step === 0 && (
                <div>
                  <h2 className="booking-step-title">What would you like to discuss?</h2>
                  <p className="booking-step-sub">Pick a stream of care — we'll match you to the right consultant next.</p>

                  <div className="treat-grid">
                    {treatments.map(t => (
                      <button
                        key={t.id}
                        className={`treat-tile ${data.treatment === t.id ? 'selected' : ''}`}
                        onClick={() => update({ treatment: t.id, surgeon: null })}
                      >
                        <span className="treat-tile-icon"><t.icon /></span>
                        <span className="treat-tile-text">
                          {t.label}
                          <small>{t.sub}</small>
                        </span>
                      </button>
                    ))}
                  </div>

                  {selectedTreatment?.surgical && (
                    <div style={{ background: 'var(--bronze-tint)', borderLeft: '3px solid var(--bronze)', padding: '14px 18px', fontSize: 12.5, color: 'var(--ink-soft)', lineHeight: 1.55, marginBottom: 24, display: 'flex', gap: 12 }}>
                      <Icon.alert className="text-bronze" />
                      <span>Surgical procedures require an in-person paid consultation, candidacy assessment and full risk disclosure before booking. Performed by DHA-licensed surgeons.</span>
                    </div>
                  )}

                  <div className="booking-foot" style={{ justifyContent: 'flex-end' }}>
                    <button className="btn btn-primary btn-lg" disabled={!canNext} onClick={next}
                      style={{ opacity: canNext ? 1 : 0.4, cursor: canNext ? 'pointer' : 'not-allowed' }}>
                      Continue <Icon.arrow className="btn-icon-arrow" />
                    </button>
                  </div>
                </div>
              )}

              {step === 1 && (
                <div>
                  <h2 className="booking-step-title">Choose your consultant</h2>
                  <p className="booking-step-sub">
                    We've narrowed this to the team members who handle <strong style={{ color: 'var(--ink)' }}>{selectedTreatment?.label.toLowerCase()}</strong>. You can also let reception decide.
                  </p>

                  <div className="surg-pick">
                    <button
                      className={`surg-pick-tile ${data.surgeon === 'any' ? 'selected' : ''}`}
                      onClick={() => update({ surgeon: 'any' })}
                    >
                      <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--bronze-tint)', color: 'var(--bronze-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <Icon.sparkle />
                      </div>
                      <div>
                        <div className="surg-pick-tile-name">No Preference</div>
                        <div className="surg-pick-tile-role">Reception will match</div>
                      </div>
                    </button>
                    {surgeonOptions.map(s => (
                      <button
                        key={s.slug}
                        className={`surg-pick-tile ${data.surgeon === s.slug ? 'selected' : ''}`}
                        onClick={() => update({ surgeon: s.slug })}
                      >
                        <img src={s.image} alt={s.name} />
                        <div>
                          <div className="surg-pick-tile-name">{s.name}</div>
                          <div className="surg-pick-tile-role">{s.role}</div>
                        </div>
                      </button>
                    ))}
                  </div>

                  <div className="booking-foot">
                    <button className="btn btn-ghost" onClick={back}>Back</button>
                    <button className="btn btn-primary btn-lg" disabled={!canNext} onClick={next}
                      style={{ opacity: canNext ? 1 : 0.4, cursor: canNext ? 'pointer' : 'not-allowed' }}>
                      Continue <Icon.arrow className="btn-icon-arrow" />
                    </button>
                  </div>
                </div>
              )}

              {step === 2 && (
                <div>
                  <h2 className="booking-step-title">Pick a preferred day & time</h2>
                  <p className="booking-step-sub">We'll confirm the exact slot when reception calls you back. Sunday is by appointment only.</p>

                  <div className="eyebrow mb-2">Next 14 days</div>
                  <div className="slot-cal" style={{ gridTemplateColumns: 'repeat(7, 1fr)' }}>
                    {days.slice(0, 7).map((d, i) => (
                      <button
                        key={i}
                        className={`slot-day ${data.day?.dayNum === d.dayNum ? 'selected' : ''} ${d.disabled ? 'disabled' : ''}`}
                        onClick={() => update({ day: d, time: null })}
                      >
                        <div className="slot-day-name">{d.dayName}</div>
                        <div className="slot-day-num">{d.dayNum}</div>
                      </button>
                    ))}
                  </div>
                  <div className="slot-cal" style={{ gridTemplateColumns: 'repeat(7, 1fr)', marginTop: 4 }}>
                    {days.slice(7, 14).map((d, i) => (
                      <button
                        key={i + 7}
                        className={`slot-day ${data.day?.dayNum === d.dayNum ? 'selected' : ''} ${d.disabled ? 'disabled' : ''}`}
                        onClick={() => update({ day: d, time: null })}
                      >
                        <div className="slot-day-name">{d.dayName}</div>
                        <div className="slot-day-num">{d.dayNum}</div>
                      </button>
                    ))}
                  </div>

                  {data.day && (
                    <div style={{ marginTop: 28 }}>
                      <div className="eyebrow mb-2">
                        Times for {data.day.dayName} {data.day.dayNum} {data.day.month}
                      </div>
                      <div className="slot-times">
                        {times.map(t => (
                          <button
                            key={t}
                            className={`slot-time ${data.time === t ? 'selected' : ''}`}
                            onClick={() => update({ time: t })}
                          >{t}</button>
                        ))}
                      </div>
                      <div className="muted" style={{ fontSize: 11.5, letterSpacing: '0.04em' }}>
                        All times Gulf Standard Time (GST). Indicative — reception confirms availability.
                      </div>
                    </div>
                  )}

                  <div className="booking-foot">
                    <button className="btn btn-ghost" onClick={back}>Back</button>
                    <button className="btn btn-primary btn-lg" disabled={!canNext} onClick={next}
                      style={{ opacity: canNext ? 1 : 0.4, cursor: canNext ? 'pointer' : 'not-allowed' }}>
                      Continue <Icon.arrow className="btn-icon-arrow" />
                    </button>
                  </div>
                </div>
              )}

              {step === 3 && (
                <div>
                  <h2 className="booking-step-title">Just your contact details</h2>
                  <p className="booking-step-sub">No medical history here — that's discussed in person, with the consultant.</p>

                  <div className="booking-summary">
                    <div className="booking-summary-row">
                      <span className="lbl">Treatment</span>
                      <span className="val">{selectedTreatment?.label}</span>
                    </div>
                    <div className="booking-summary-row">
                      <span className="lbl">Consultant</span>
                      <span className="val">{data.surgeon === 'any' ? 'No preference — reception to match' : selectedSurgeon?.name}</span>
                    </div>
                    <div className="booking-summary-row">
                      <span className="lbl">Preferred</span>
                      <span className="val">{data.day?.dayName} {data.day?.dayNum} {data.day?.month} · {data.time} GST</span>
                    </div>
                  </div>

                  <div className="field-grid">
                    <div>
                      <label className="field-label">Full Name</label>
                      <input className="field" placeholder="As you'd like us to address you"
                        value={data.name} onChange={(e) => update({ name: e.target.value })} />
                    </div>
                    <div className="field-grid-2">
                      <div>
                        <label className="field-label">Country</label>
                        <select className="field" value={data.countryCode} onChange={(e) => update({ countryCode: e.target.value })}>
                          <option value="+971">🇦🇪 +971 (UAE)</option>
                          <option value="+966">🇸🇦 +966 (KSA)</option>
                          <option value="+44">🇬🇧 +44 (UK)</option>
                          <option value="+7">🇷🇺 +7 (RU)</option>
                          <option value="+86">🇨🇳 +86 (CN)</option>
                          <option value="+1">🇺🇸 +1 (US)</option>
                        </select>
                      </div>
                      <div>
                        <label className="field-label">Phone</label>
                        <input className="field" placeholder="50 123 4567" value={data.phone}
                          onChange={(e) => update({ phone: e.target.value.replace(/[^\d\s]/g, '') })} />
                      </div>
                    </div>
                    <div>
                      <label className="field-label">Email</label>
                      <input className="field" type="email" placeholder="hello@example.com"
                        value={data.email} onChange={(e) => update({ email: e.target.value })} />
                    </div>
                    <div>
                      <label className="field-label">Anything we should know <span style={{ textTransform: 'none', letterSpacing: 0, opacity: 0.6 }}>— optional</span></label>
                      <textarea className="field field-textarea" placeholder="A sentence or two on what you'd like to discuss"
                        value={data.note} onChange={(e) => update({ note: e.target.value })} />
                    </div>
                  </div>

                  <div className="flex gap-2 mt-4" style={{ alignItems: 'flex-start', maxWidth: 600 }}>
                    <input
                      id="consent"
                      type="checkbox"
                      style={{ width: 16, height: 16, accentColor: 'var(--bronze-deep)', marginTop: 2 }}
                      checked={data.consent}
                      onChange={(e) => update({ consent: e.target.checked })}
                    />
                    <label htmlFor="consent" style={{ fontSize: 12.5, color: 'var(--ink-muted)', lineHeight: 1.55, cursor: 'pointer' }}>
                      I consent to Aesthetics International contacting me on the details above to
                      confirm a consultation appointment. I understand surgical procedures require
                      in-person consultation and that results are individual, not guaranteed.
                    </label>
                  </div>

                  <div className="booking-foot">
                    <button className="btn btn-ghost" onClick={back}>Back</button>
                    <button className="btn btn-bronze btn-lg" disabled={!canNext} onClick={next}
                      style={{ opacity: canNext ? 1 : 0.4, cursor: canNext ? 'pointer' : 'not-allowed' }}>
                      Submit Request <Icon.arrow className="btn-icon-arrow" />
                    </button>
                  </div>
                </div>
              )}

              {step === 4 && (
                <div className="booking-success">
                  <div className="booking-success-tick">
                    <Icon.checkLg />
                  </div>
                  <h3>Thank you, {data.name.split(' ')[0] || 'there'}.</h3>
                  <p>
                    Reception will call you back on <strong style={{ color: 'var(--ink)' }}>{data.countryCode} {data.phone}</strong> within
                    one business day to confirm your appointment for <strong style={{ color: 'var(--ink)' }}>{data.day?.dayName} {data.day?.dayNum} {data.day?.month}</strong> at <strong style={{ color: 'var(--ink)' }}>{data.time} GST</strong>.
                  </p>

                  <div className="booking-summary" style={{ width: '100%', maxWidth: 460, textAlign: 'left', margin: '24px 0' }}>
                    <div className="booking-summary-row">
                      <span className="lbl">Ref</span>
                      <span className="val font-mono" style={{ fontSize: 12 }}>AI-{(Math.random() * 90000 + 10000).toFixed(0)}</span>
                    </div>
                    <div className="booking-summary-row">
                      <span className="lbl">Treatment</span>
                      <span className="val">{selectedTreatment?.label}</span>
                    </div>
                    <div className="booking-summary-row">
                      <span className="lbl">Consultant</span>
                      <span className="val">{data.surgeon === 'any' ? 'Reception to match' : selectedSurgeon?.name}</span>
                    </div>
                  </div>

                  <div className="flex gap-2" style={{ flexWrap: 'wrap', justifyContent: 'center' }}>
                    <a className="btn btn-primary" href={CLINIC_INFO.whatsappHref} target="_blank" rel="noopener">
                      Send via WhatsApp instead
                    </a>
                    <button className="btn btn-ghost" onClick={() => go({ page: 'home' })}>
                      Back to home
                    </button>
                  </div>

                  <div className="mt-6" style={{ fontSize: 11.5, color: 'var(--ink-muted)', letterSpacing: '0.04em', maxWidth: 480, textAlign: 'center', lineHeight: 1.55 }}>
                    By submitting you agreed to our minimal-PHI policy. Medical history is collected
                    in person, not online. We do not advertise guaranteed results.
                  </div>
                </div>
              )}
            </main>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { BookingFlow });
