/* ============================================================
   DNA Health & Wellness — Multi-step booking flow + App shell
   ============================================================ */

const { useState: useStateApp, useEffect: useEffectApp } = React;

/* -------------------- BookSheet (multi-step) -------------------- */
function BookSheet({ open, onClose, presetPillar, presetLocation }) {
  const STEPS = ['Pillar', 'Program', 'Location', 'When', 'Contact', 'Confirm'];
  const [step, setStep] = useStateApp(0);
  const [pillar, setPillar] = useStateApp('');
  const [program, setProgram] = useStateApp('');
  const [location, setLocation] = useStateApp('');
  const [when, setWhen] = useStateApp('');
  const [time, setTime] = useStateApp('');
  const [contact, setContact] = useStateApp({ name: '', email: '', phone: '', message: '', preferred: 'WhatsApp' });
  const [done, setDone] = useStateApp(false);

  useEffectApp(() => {
    if (open) {
      setStep(0);
      setPillar(presetPillar || '');
      setLocation(presetLocation || '');
      setProgram('');
      setWhen('');
      setTime('');
      setContact({ name: '', email: '', phone: '', message: '', preferred: 'WhatsApp' });
      setDone(false);
    }
  }, [open, presetPillar, presetLocation]);

  // jump past preset
  useEffectApp(() => {
    if (open && pillar && step === 0) setStep(1);
  }, [open, pillar]);

  if (!open) return null;

  const activePillar = PILLARS.find(p => p.name === pillar);
  const canNext = (() => {
    if (step === 0) return !!pillar;
    if (step === 1) return !!program;
    if (step === 2) return !!location;
    if (step === 3) return !!when && !!time;
    if (step === 4) return contact.name && contact.email && contact.phone;
    return true;
  })();

  const submit = () => {
    setDone(true);
  };

  const progress = ((step + 1) / STEPS.length) * 100;

  return (
    <div className={`scrim ${open ? 'open' : ''}`} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="sheet" role="dialog" aria-modal="true">
        <aside className="sheet-aside">
          <div className="logo"><img src="media/dna-logo.svg" alt="" style={{ filter: 'brightness(0) invert(1)', height: 32 }}/></div>
          <div>
            <div className="eyebrow" style={{ color: 'rgba(250,251,248,0.55)' }}>
              <span className="dot"></span>Book a consultation
            </div>
            <h3 style={{ marginTop: 14 }}>A real doctor, not an intake script.</h3>
            <p style={{ marginTop: 14 }}>
              Tell us where you are in your health journey. We'll match you with the right practitioner, at the right clinic, with a 24/7 line if you need to reach us in between.
            </p>
          </div>
          <div className="steps">
            {STEPS.map((s, i) => (
              <div className={`step ${i < step ? 'done' : ''} ${i === step ? 'current' : ''}`} key={s}>
                <span className="dot"></span>
                <span>{String(i + 1).padStart(2, '0')} · {s}</span>
              </div>
            ))}
          </div>
        </aside>

        <main className="sheet-main">
          <button className="close" onClick={onClose} aria-label="Close"><Icon.close/></button>

          {!done ? (
            <>
              <div className="sheet-progress">
                <span>Step {String(step + 1).padStart(2, '0')} of {STEPS.length}</span>
                <div className="bar"><div className="fill" style={{ width: `${progress}%` }}/></div>
                <span>{STEPS[step]}</span>
              </div>

              {step === 0 && (
                <>
                  <h3 className="sheet-q">Where shall we start?</h3>
                  <div className="sheet-h">Pick the pillar closest to what you're after. You can move between them later.</div>
                  <div className="opt-grid">
                    {PILLARS.map(p => (
                      <div key={p.id} className={`opt ${pillar === p.name ? 'selected' : ''}`} onClick={() => setPillar(p.name)}>
                        <div className="dot"/>
                        <div>
                          <div className="opt-name">{p.num} · {p.name}</div>
                          <div className="opt-sub">{p.tagline}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </>
              )}

              {step === 1 && activePillar && (
                <>
                  <h3 className="sheet-q">Which {activePillar.name.toLowerCase()} program?</h3>
                  <div className="sheet-h">Approximate — we'll refine in the consultation. Prices are typed from the current rate card; final figures confirmed by your doctor.</div>
                  <div className="opt-grid">
                    {activePillar.programs.map(pr => (
                      <div key={pr.name} className={`opt ${program === pr.name ? 'selected' : ''}`} onClick={() => setProgram(pr.name)}>
                        <div className="dot"/>
                        <div>
                          <div className="opt-name">{pr.name}</div>
                          <div className="opt-sub">{pr.price}</div>
                        </div>
                      </div>
                    ))}
                    <div className={`opt ${program === 'Not sure yet' ? 'selected' : ''}`} onClick={() => setProgram('Not sure yet')}>
                      <div className="dot"/>
                      <div>
                        <div className="opt-name">Not sure yet</div>
                        <div className="opt-sub">A doctor will guide you in a 30-min discovery call.</div>
                      </div>
                    </div>
                  </div>
                </>
              )}

              {step === 2 && (
                <>
                  <h3 className="sheet-q">Which clinic suits you?</h3>
                  <div className="sheet-h">All branches share one medical record. Home-service is available for screenings and IV therapy in select postcodes.</div>
                  <div className="opt-grid">
                    {LOCATIONS.map(l => (
                      <div key={l.id} className={`opt ${location === l.name ? 'selected' : ''}`} onClick={() => setLocation(l.name)}>
                        <div className="dot"/>
                        <div>
                          <div className="opt-name">{l.name}</div>
                          <div className="opt-sub">{l.address.split(',').slice(0, 2).join(',')}</div>
                        </div>
                      </div>
                    ))}
                    <div className={`opt ${location === 'Home service' ? 'selected' : ''}`} onClick={() => setLocation('Home service')}>
                      <div className="dot"/>
                      <div>
                        <div className="opt-name">Home service</div>
                        <div className="opt-sub">Concierge IV / screening at your address.</div>
                      </div>
                    </div>
                  </div>
                </>
              )}

              {step === 3 && (
                <>
                  <h3 className="sheet-q">When works for you?</h3>
                  <div className="sheet-h">Indicative slots only — your doctor's PA will confirm by WhatsApp within two hours.</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                    <div>
                      <label className="eyebrow" style={{ marginBottom: 10, display: 'block' }}>Day</label>
                      <div className="opt-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
                        {['Today', 'Tomorrow', 'This week', 'Next week'].map(d => (
                          <div key={d} className={`opt ${when === d ? 'selected' : ''}`} onClick={() => setWhen(d)}>
                            <div className="dot"/>
                            <div className="opt-name" style={{ fontSize: 13 }}>{d}</div>
                          </div>
                        ))}
                      </div>
                    </div>
                    <div>
                      <label className="eyebrow" style={{ marginBottom: 10, display: 'block' }}>Time of day</label>
                      <div className="opt-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
                        {['Morning (08-12)', 'Afternoon (12-17)', 'Evening (17-21)'].map(t => (
                          <div key={t} className={`opt ${time === t ? 'selected' : ''}`} onClick={() => setTime(t)}>
                            <div className="dot"/>
                            <div className="opt-name" style={{ fontSize: 13 }}>{t}</div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </>
              )}

              {step === 4 && (
                <>
                  <h3 className="sheet-q">How shall we reach you?</h3>
                  <div className="sheet-h">Minimal personal info — we don't ask for medical history here. That conversation belongs in clinic.</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                    <div className="field">
                      <label>Full name</label>
                      <input value={contact.name} onChange={e => setContact({ ...contact, name: e.target.value })} placeholder="As it appears on Emirates ID"/>
                    </div>
                    <div className="fields-grid">
                      <div className="field">
                        <label>Email</label>
                        <input type="email" value={contact.email} onChange={e => setContact({ ...contact, email: e.target.value })} placeholder="you@example.com"/>
                      </div>
                      <div className="field">
                        <label>Phone (UAE preferred)</label>
                        <input type="tel" value={contact.phone} onChange={e => setContact({ ...contact, phone: e.target.value })} placeholder="+971 5_ ___ ____"/>
                      </div>
                    </div>
                    <div className="field">
                      <label>Anything we should know (optional)</label>
                      <textarea value={contact.message} onChange={e => setContact({ ...contact, message: e.target.value })} placeholder="Programme of interest, accessibility needs, language preference…"/>
                    </div>
                    <div className="field">
                      <label>Preferred contact channel</label>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                        {['WhatsApp', 'Phone call', 'Email'].map(ch => (
                          <button key={ch} className={`chip ${contact.preferred === ch ? 'chip-leaf' : ''}`}
                            onClick={() => setContact({ ...contact, preferred: ch })}
                            style={{ cursor: 'pointer' }}>{ch}</button>
                        ))}
                      </div>
                    </div>
                    <div className="consent-line">
                      By submitting, you consent to be contacted by DNA Health Medical Center LLC about this enquiry. No medical history is collected here; PHI is gathered only in-clinic, under DHA-compliant consent.
                    </div>
                  </div>
                </>
              )}

              {step === 5 && (
                <>
                  <h3 className="sheet-q">Confirm and send</h3>
                  <div className="sheet-h">Review your enquiry. The next conversation is with a doctor — usually within two hours.</div>
                  <div style={{ background: 'var(--mist)', borderRadius: 'var(--r)', padding: '22px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
                    {[
                      ['Pillar', pillar],
                      ['Program', program],
                      ['Clinic', location],
                      ['When', `${when} · ${time}`],
                      ['Name', contact.name],
                      ['Contact', `${contact.email} · ${contact.phone}`],
                      ['Preferred channel', contact.preferred],
                    ].map(([k, v]) => (
                      <div key={k} style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 16, paddingBottom: 10, borderBottom: '1px solid var(--line)' }}>
                        <div className="eyebrow" style={{ marginBottom: 0 }}>{k}</div>
                        <div style={{ fontSize: 14, color: 'var(--ink)' }}>{v || '—'}</div>
                      </div>
                    ))}
                    {contact.message && (
                      <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 16 }}>
                        <div className="eyebrow" style={{ marginBottom: 0 }}>Note</div>
                        <div style={{ fontSize: 14, color: 'var(--ink)' }}>{contact.message}</div>
                      </div>
                    )}
                  </div>
                </>
              )}

              <div className="sheet-actions">
                {step > 0 ? (
                  <button className="tiny-link" onClick={() => setStep(step - 1)}>← Back</button>
                ) : <div/>}
                {step < STEPS.length - 1 ? (
                  <button className="btn btn-primary" disabled={!canNext} onClick={() => setStep(step + 1)} style={{ opacity: canNext ? 1 : 0.4, pointerEvents: canNext ? 'all' : 'none' }}>
                    Continue <Icon.arrow/>
                  </button>
                ) : (
                  <button className="btn btn-leaf" onClick={submit}>Send enquiry <Icon.check/></button>
                )}
              </div>
            </>
          ) : (
            <div className="success-state">
              <div className="check"><Icon.check/></div>
              <h3>Enquiry sent.</h3>
              <p>A member of the medical team will be in touch via {contact.preferred.toLowerCase()} within two hours. For anything urgent, the client line is open 24/7.</p>
              <div style={{ display: 'flex', justifyContent: 'center', gap: 8, flexWrap: 'wrap' }}>
                <a className="btn btn-primary" href="tel:+97145736500"><Icon.phone/> Call +971 4 573 6500</a>
                <a className="btn btn-ghost" href="https://wa.me/971585974663" target="_blank" rel="noreferrer"><Icon.whatsapp/> Open WhatsApp</a>
                <button className="btn btn-ghost" onClick={onClose}>Close</button>
              </div>
              <div style={{ marginTop: 32, padding: '16px 18px', background: 'var(--mist)', borderRadius: 'var(--r)', fontSize: 12, color: 'var(--muted)', textAlign: 'left' }}>
                Reference · DNA-{Math.floor(Math.random() * 90000 + 10000)} · logged at {new Date().toLocaleString('en-AE', { hour: '2-digit', minute: '2-digit', day: '2-digit', month: 'short' })}
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}

/* -------------------- App shell -------------------- */
function App() {
  const [openMenu, setOpenMenu] = useStateApp(null);
  const [bookOpen, setBookOpen] = useStateApp(false);
  const [bookPillar, setBookPillar] = useStateApp('');
  const [bookLocation, setBookLocation] = useStateApp('');
  const [activeDoctor, setActiveDoctor] = useStateApp(null);

  useEffectApp(() => {
    document.body.style.overflow = bookOpen || activeDoctor ? 'hidden' : '';
  }, [bookOpen, activeDoctor]);

  return (
    <>
      <Nav openBook={() => setBookOpen(true)} openMenu={openMenu} setOpenMenu={setOpenMenu}/>
      <Hero openBook={() => setBookOpen(true)}/>
      <PressStrip/>
      <Pillars
        openBook={() => setBookOpen(true)}
        setBookPillar={setBookPillar}/>
      <Philosophy/>
      <Approach/>
      <Team openDoctor={setActiveDoctor}/>
      <Locations
        openBook={() => setBookOpen(true)}
        setBookLocation={setBookLocation}/>
      <Reviews/>
      <CTABand openBook={() => setBookOpen(true)}/>
      <Footer/>
      <MobileBar openBook={() => setBookOpen(true)}/>

      <BookSheet
        open={bookOpen}
        onClose={() => { setBookOpen(false); setBookPillar(''); setBookLocation(''); }}
        presetPillar={bookPillar}
        presetLocation={bookLocation}/>

      {activeDoctor && <DoctorDrawer doctor={activeDoctor} onClose={() => setActiveDoctor(null)}/>}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
