/* ============================================================
   MUIY 2.0 — Welcome · Auth · Onboarding
   A warm, one-question-per-screen first-run flow, organised into
   five named phases:  Welcome · Consent · Medical · Reminders · Done.
   The Medical phase is gated behind an explicit data-consent screen
   and becomes the single source of truth for the whole app.
   Exports window.WelcomeFlow — rendered by the shell when the
   user is signed out / hasn't completed setup.
   ============================================================ */

/* small brand leaf used in the logo tile + finish art */
function WfLeaf({ size = 22, color = '#fff' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none">
      <path d="M20 35V16" stroke={color} strokeWidth="3.2" strokeLinecap="round" />
      <path d="M20 27C9 25 5 16 7 8 18 10 24 18 20 27Z" fill={color} opacity=".95" />
      <path d="M20 21C31 19 35 11 33 4 22 6 16 13 20 21Z" fill={color} opacity=".75" />
      <path d="M20 13S13 8 13 3.4a4 4 0 0 1 7-1.4 4 4 0 0 1 7 1.4C27 8 20 13 20 13Z" fill={color} />
    </svg>
  );
}

const WF_THAL = [
  { v: 'β-thalassaemia Major', d: 'Beta thalassaemia major' },
  { v: 'α-thalassaemia Major', d: 'Alpha thalassaemia major' },
  { v: 'β-thalassaemia Intermedia', d: 'Beta thalassaemia intermedia' },
  { v: 'α-thalassaemia Intermedia', d: 'Alpha thalassaemia intermedia' },
  { v: 'Haemoglobin E/β-thalassaemia', d: 'HbE / beta thalassaemia' },
  { v: 'Other', d: 'A different or unconfirmed type' },
];
const WF_BLOOD = ['O+', 'O-', 'A+', 'A-', 'B+', 'B-', 'AB+', 'AB-'];
const WF_INTERVALS = [
  { v: 'Every 2 weeks', w: 2 },
  { v: 'Every 3 weeks', w: 3 },
  { v: 'Every 4 weeks', w: 4 },
  { v: 'Every 5–6 weeks', w: 5 },
  { v: 'I’m not sure', w: null },
];

/* the five onboarding phases — drives the phase rail */
const WF_PHASES = [
  { key: 'welcome', label: 'Welcome' },
  { key: 'consent', label: 'Consent' },
  { key: 'medical', label: 'Medical' },
  { key: 'prefs', label: 'Alerts' },
  { key: 'done', label: 'Done' },
];

/* ---- a single big tappable option ---- */
function WfOpt({ on, title, desc, onClick }) {
  return (
    <button className={'wf-opt' + (on ? ' on' : '')} onClick={onClick}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="wf-opt-t">{title}</div>
        {desc && <div className="wf-opt-d">{desc}</div>}
      </div>
      <span className="wf-opt-tick">{on && <Icon name="check" size={13} color="#fff" sw={3.2} />}</span>
    </button>
  );
}

/* ---- phase rail: five segments, the active one fills as you progress ---- */
function WfPhaseRail({ phaseIndex, fill }) {
  return (
    <div className="wf-prail">
      {WF_PHASES.map((ph, i) => {
        const state = i < phaseIndex ? 'done' : i === phaseIndex ? 'active' : 'todo';
        const w = i < phaseIndex ? 100 : i === phaseIndex ? Math.round(fill * 100) : 0;
        return (
          <div key={ph.key} className={'wf-pseg ' + state}>
            <div className="wf-pseg-bar"><div className="wf-pseg-fill" style={{ width: w + '%' }} /></div>
            <span className="wf-pseg-lbl">{ph.label}</span>
          </div>
        );
      })}
    </div>
  );
}

/* ============================================================
   SPLASH
   ============================================================ */
function WfSplash({ onStart, onHaveAccount, resuming }) {
  return (
    <div className="wf-splash">
      <div className="wf-splash-ring" />
      <div className="wf-splash-ring2" />
      <div className="wf-brand">
        <div className="wf-logo"><Pearl size={172} /></div>
        <span className="wf-wordmark" aria-label="MUIY" style={{ color: 'var(--ink)', opacity: 0.72 }}>MUIY</span>
        <div className="wf-tagline">Your thalassaemia records, always at hand. Anywhere. Anytime.</div>
      </div>
      <div className="wf-splash-foot">
        <button className="wf-btn wf-btn-primary" onClick={onStart}>{resuming ? 'Resume setup' : 'Get started'}</button>
        <div className="wf-switch" style={{ marginTop: 16 }}>Already with us?{' '}
          <button onClick={onHaveAccount}>Log in</button>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   AUTH
   ============================================================ */
function WfAuth({ mode, setMode, onGoogle, onSignup, onLogin }) {
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const isLogin = mode === 'login';
  const isSignup = mode === 'signup';
  const choices = mode === 'choices';

  return (
    <div className="wf">
      <div className="wf-scroll">
        <div className="wf-auth-top">
          <div className="wf-auth-logo"><WfLeaf size={26} /></div>
          <div className="wf-h">{choices ? 'Welcome to MUIY' : isLogin ? 'Welcome back' : 'Create your account'}</div>
          <div className="wf-sub">
            {choices ? 'Sign in to keep your care organised, safely on your own device.'
              : isLogin ? 'Log in to pick up right where you left off.'
              : 'A few quick details and we’ll set things up just for you.'}
          </div>
        </div>

        <div className="wf-pad">
          {choices && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
              <button className="wf-btn wf-btn-google" onClick={onGoogle}><GoogleG size={20} /> Continue with Google</button>
              <button className="wf-btn wf-btn-primary" onClick={() => setMode('signup')}><Icon name="chat" size={18} color="#fff" /> Sign up with email</button>
              <div className="wf-switch">Already have an account?{' '}<button onClick={() => setMode('login')}>Log in</button></div>
            </div>
          )}

          {(isLogin || isSignup) && (
            <div>
              <div className="field"><label className="field-label">Email</label>
                <input className="input" type="email" inputMode="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" autoFocus /></div>
              <div className="field"><label className="field-label">Password</label>
                <input className="input" type="password" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" /></div>
              <button className="wf-btn wf-btn-primary" style={{ marginTop: 4 }} onClick={() => isLogin ? onLogin() : onSignup()}>
                {isLogin ? 'Log in' : 'Continue'}
              </button>
              <div className="wf-or">or</div>
              <button className="wf-btn wf-btn-google" onClick={onGoogle}><GoogleG size={20} /> Continue with Google</button>
              <div className="wf-switch">
                {isLogin ? <>New here?{' '}<button onClick={() => setMode('signup')}>Create an account</button></>
                  : <>Already have an account?{' '}<button onClick={() => setMode('login')}>Log in</button></>}
              </div>
            </div>
          )}

          <div className="wf-legal">Your data stays private — it lives on your device, and you can export your own copy anytime.</div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   CONSENT — plain-language medical-data notice (Step 2)
   ============================================================ */
const WF_CONSENT_POINTS = [
  { icon: 'clipboard', t: 'What we collect', d: 'Your thalassaemia type, blood group, weight, splenectomy status and — if you add them — your transfusion and chelation details.' },
  { icon: 'sparkle', t: 'How we use it', d: 'Only to personalise your reminders, next-transfusion forecast, iron insights and clinical summaries. Just for you.' },
  { icon: 'shield', t: 'Where it’s stored', d: 'On your device only. We never keep it on our servers — export a copy anytime to keep your own backup.' },
  { icon: 'user', t: 'Who can see it', d: 'Only you. We never sell or share your medical information with anyone.' },
  { icon: 'edit', t: 'You stay in control', d: 'Edit or delete any detail anytime under Me → Medical Profile.' },
];

function WfConsent({ checked, onToggle, onOpenDoc }) {
  return (
    <div>
      <div className="wf-consent-list">
        {WF_CONSENT_POINTS.map((p) => (
          <div key={p.t} className="wf-consent-item">
            <div className="wf-consent-ic"><Icon name={p.icon} size={16} color="var(--orange)" /></div>
            <div style={{ minWidth: 0 }}>
              <div className="wf-consent-t">{p.t}</div>
              <div className="wf-consent-d">{p.d}</div>
            </div>
          </div>
        ))}
      </div>
      <div className="wf-doclinks">
        <button onClick={() => onOpenDoc('privacy')}>Privacy Policy</button>
        <span>·</span>
        <button onClick={() => onOpenDoc('terms')}>Terms of Service</button>
      </div>
      <button className={'wf-check' + (checked ? ' on' : '')} onClick={() => onToggle(!checked)}>
        <span className="wf-check-box">{checked && <Icon name="check" size={13} color="#fff" sw={3.4} />}</span>
        <span className="wf-check-lbl">I understand how my medical information will be stored, used and protected, and I consent to the collection and processing of my medical profile information.</span>
      </button>
    </div>
  );
}

/* full Privacy / Terms overlay reached from the consent links */
const WF_DOCS = {
  privacy: {
    title: 'Privacy Policy',
    sub: 'In short: your health data is yours. Here’s the detail.',
    body: [
      ['Your data lives with you', 'MUIY stores everything locally on your device. We operate no central database of patient records and cannot read your information. Export a copy anytime to keep your own portable backup.'],
      ['What we collect', 'Identity details (name, preferred name, date of birth, sex) and the medical profile you choose to provide: thalassaemia type, transfusion pattern, blood group, splenectomy status, weight, transfusion centre, usual interval and chelation therapy.'],
      ['How it is used', 'Solely to power features inside the app for you — next-transfusion forecasting, personalised insights, health-trend analysis, clinical summaries, medication tracking, reminders and recommendations. No advertising, no profiling, no third-party analytics on your health data.'],
      ['Sharing', 'We never sell or share your medical information. You may export or share a summary yourself at any time.'],
      ['Your rights', 'You can view, edit or permanently delete any field from Me → Medical Profile, or clear all data from Me → Data. Deletion is immediate and irreversible.'],
    ],
  },
  terms: {
    title: 'Terms of Service',
    sub: 'A companion app — not a replacement for your care team. The full terms live in Me → About MUIY.',
    body: [
      ['A companion, not a medical device', 'MUIY helps you organise and understand your own thalassaemia care. Its forecasts, dose targets and insights are informational estimates only — never a diagnosis, prescription or medical advice. Always follow your haematologist’s guidance.'],
      ['Not for emergencies', 'MUIY is not for urgent care. For urgent symptoms, contact your treatment centre or local emergency number immediately — don’t wait on the app.'],
      ['Who can use it', 'MUIY is for people with thalassaemia and their caregivers. You should be 18+ to accept these terms; a young person may use it with a parent or guardian who accepts on their behalf.'],
      ['Your responsibility', 'You’re responsible for the accuracy of what you enter and for keeping your own backup, since your data lives on your device. Only add a donor’s details with their agreement.'],
      ['Free, as-is', 'MUIY is provided free and “as is” by the ThalFrndz community. We work to keep it reliable but can’t guarantee uninterrupted service, and to the extent the law allows we’re not liable for harm from relying on the app instead of your care team.'],
      ['Maldivian law', 'These terms are governed by the laws of the Republic of Maldives. We may update them as the app evolves; continuing to use MUIY means you accept the current terms.'],
    ],
  },
};

function WfDoc({ which, onBack }) {
  const doc = WF_DOCS[which] || WF_DOCS.privacy;
  return (
    <div className="wf">
      <div className="wf-prog-row" style={{ paddingBottom: 4 }}>
        <button className="wf-back" onClick={onBack} aria-label="Back"><Icon name="chevL" size={20} /></button>
        <div style={{ fontWeight: 800, fontSize: 16, color: 'var(--ink)' }}>{doc.title}</div>
      </div>
      <div className="wf-scroll">
        <div className="wf-pad" style={{ paddingTop: 10 }}>
          <div className="wf-sub" style={{ textAlign: 'left', marginBottom: 18 }}>{doc.sub}</div>
          {doc.body.map(([h, p]) => (
            <div key={h} style={{ marginBottom: 18 }}>
              <div style={{ fontWeight: 800, fontSize: 15, color: 'var(--ink)', marginBottom: 5 }}>{h}</div>
              <div className="body" style={{ fontSize: 13.5, lineHeight: 1.55 }}>{p}</div>
            </div>
          ))}
          <button className="wf-btn wf-btn-ghost" onClick={onBack} style={{ marginTop: 4 }}>Back to consent</button>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   REMINDERS & PREFERENCES (Step 4)
   ============================================================ */
function WfPrefRow({ icon, title, desc, on, onToggle }) {
  return (
    <div className="wf-pref">
      <div className="wf-pref-ic"><Icon name={icon} size={17} color="var(--orange)" /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="wf-pref-t">{title}</div>
        <div className="wf-pref-d">{desc}</div>
      </div>
      <button className={'switch' + (on ? ' on' : '')} onClick={() => onToggle(!on)}><span className="knob" /></button>
    </div>
  );
}

function WfPrefs({ prefs, set }) {
  return (
    <div className="wf-prefs">
      <WfPrefRow icon="drop" title="Transfusion reminders" desc="A gentle nudge as your next transfusion approaches." on={prefs.transfusion} onToggle={(v) => set('transfusion', v)} />
      <WfPrefRow icon="pill" title="Medication reminders" desc="Daily prompts to take your chelation on time." on={prefs.medication} onToggle={(v) => set('medication', v)} />
      <WfPrefRow icon="calendar" title="Appointment reminders" desc="Heads-up before clinic visits and lab tests." on={prefs.appointment} onToggle={(v) => set('appointment', v)} />
      <WfPrefRow icon="bell" title="Push notifications" desc="Allow MUIY to send these to your device." on={prefs.push} onToggle={(v) => set('push', v)} />
    </div>
  );
}

/* ============================================================
   ONBOARDING — one question per screen, five phases
   ============================================================ */
const WF_OB_KEY = 'mui:onboard:v3';

function WelcomeFlow({ store, patient, onSignIn, onComplete }) {
  // restore any in-progress onboarding (save-progress / finish-later)
  const saved = React.useMemo(() => {
    try { const r = localStorage.getItem(WF_OB_KEY); return r ? JSON.parse(r) : null; } catch (e) { return null; }
  }, []);
  const hasSaved = !!(saved && saved.f && (saved.f.name || saved.step > 0));

  // In cloud mode the visitor already met the root welcome splash and signed
  // in (auth.jsx) before this flow mounts — start directly in profile setup.
  // Local mode (no keys) keeps the original splash-first flow.
  const [screen, setScreen] = React.useState(() =>
    (window.TCsb && window.TCsb.isConfigured()) ? 'onboard' : 'splash'); // splash | auth | onboard | finish
  const [authMode, setAuthMode] = React.useState('choices');
  const [step, setStep] = React.useState(saved && saved.step ? saved.step : 0);
  const [showDoc, setShowDoc] = React.useState(null); // 'privacy' | 'terms' | null
  const [showChel, setShowChel] = React.useState(false);
  const [f, setF] = React.useState(Object.assign({
    name: '', preferredName: '', dob: '', sex: 'female',
    bloodGroup: '', thalType: '', transfusionStatus: 'TDT', splenectomy: false,
    weight: '', treatmentCenter: '', interval: '', consent: false,
    reminders: { transfusion: true, medication: true, appointment: true, push: true },
  }, (saved && saved.f) || {}));
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  const setRem = (k, v) => setF((s) => ({ ...s, reminders: { ...s.reminders, [k]: v } }));

  const startSignup = () => { setScreen('onboard'); };
  // When Supabase is configured the user has already signed in at the auth gate
  // (Google / email) before this flow mounts — so the welcome auth screen is a
  // profile-setup entry, not a second login.
  const cloud = !!(window.TCsb && window.TCsb.isConfigured());
  const handleGoogle = () => {
    if (cloud) { window.TCsb.signInWithGoogle(); return; }
    startSignup();
  };
  const meds = (store && store.patient && store.patient.medications) || [];

  // open the existing chelation wizard as an overlay; seed weight first so it isn't asked twice
  const openChelation = () => {
    const w = parseFloat(f.weight);
    if (w > 0 && store) store.mutate((d) => { d.patient.weightKg = Math.round(w * 10) / 10; });
    setShowChel(true);
  };

  // ---- step definitions (tagged by phase) ----
  const steps = [
    // ---- PHASE 1 · WELCOME ----
    {
      phase: 'welcome', key: 'name', eyebrow: 'About you', title: 'What’s your full name?',
      hint: 'This stays private — it just helps personalise your records.',
      valid: () => f.name.trim().length > 1,
      render: () => <input className="input" style={{ fontSize: 18 }} value={f.name} autoFocus
        onChange={(e) => { const v = e.target.value; setF((s) => ({ ...s, name: v, preferredName: s.preferredName || v.trim().split(/\s+/)[0] || '' })); }}
        placeholder="e.g. Mariyam Ali" />,
    },
    {
      phase: 'welcome', key: 'preferredName', eyebrow: 'About you', title: 'What should we call you?',
      hint: 'We’ll greet you with this name throughout the app.',
      valid: () => f.preferredName.trim().length > 0,
      render: () => <input className="input" style={{ fontSize: 18 }} value={f.preferredName} autoFocus
        onChange={(e) => set('preferredName', e.target.value)} placeholder="e.g. Mariyam" />,
    },
    {
      phase: 'welcome', key: 'dob', eyebrow: 'About you', title: 'When were you born?',
      hint: 'Your age helps us tailor which check-ups apply to you.',
      valid: () => !!f.dob,
      render: () => <input className="input" style={{ fontSize: 18 }} type="date" value={f.dob} max={TC.daysAgoDate(0)}
        onChange={(e) => set('dob', e.target.value)} />,
    },
    {
      phase: 'welcome', key: 'sex', eyebrow: 'About you', title: 'What’s your sex?',
      hint: 'Used to personalise hormone and growth monitoring.',
      valid: () => true,
      render: () => (
        <div className="wf-opts">
          <WfOpt on={f.sex === 'female'} title="Female" onClick={() => set('sex', 'female')} />
          <WfOpt on={f.sex === 'male'} title="Male" onClick={() => set('sex', 'male')} />
        </div>
      ),
    },

    // ---- PHASE 2 · CONSENT (gate) ----
    {
      phase: 'consent', key: 'consent', eyebrow: 'Your privacy', title: 'How we’ll look after your medical information',
      hint: 'Before we collect anything about your health, here’s exactly what happens to it.',
      buttonLabel: 'Agree & Continue',
      valid: () => f.consent === true,
      render: () => <WfConsent checked={f.consent} onToggle={(v) => set('consent', v)} onOpenDoc={setShowDoc} />,
    },

    // ---- PHASE 3 · MEDICAL ----
    {
      phase: 'medical', key: 'thalType', eyebrow: 'Medical profile', title: 'Which type of thalassaemia do you have?',
      hint: 'If you’re unsure, choose Other — you can update this later.',
      valid: () => !!f.thalType,
      render: () => (
        <div className="wf-opts">
          {WF_THAL.map((t) => <WfOpt key={t.v} on={f.thalType === t.v} title={t.v} desc={t.d} onClick={() => set('thalType', t.v)} />)}
        </div>
      ),
    },
    {
      phase: 'medical', key: 'transfusionStatus', eyebrow: 'Medical profile', title: 'How would you describe your transfusions?',
      hint: 'This shapes how often we suggest blood and iron monitoring.',
      valid: () => true,
      render: () => (
        <div className="wf-opts">
          <WfOpt on={f.transfusionStatus === 'TDT'} title="Transfusion-dependent (TDT)" desc="I have regular, scheduled transfusions." onClick={() => set('transfusionStatus', 'TDT')} />
          <WfOpt on={f.transfusionStatus === 'NTDT'} title="Non-transfusion-dependent (NTDT)" desc="I transfuse rarely or only when needed." onClick={() => set('transfusionStatus', 'NTDT')} />
        </div>
      ),
    },
    {
      phase: 'medical', key: 'bloodGroup', eyebrow: 'Medical profile', title: 'What’s your blood group?',
      hint: 'We’ll match compatible donors in your pool for you.',
      valid: () => !!f.bloodGroup,
      render: () => (
        <div className="wf-bloodgrid">
          {WF_BLOOD.map((g) => (
            <button key={g} className={'wf-blood' + (f.bloodGroup === g ? ' on' : '')}
              style={f.bloodGroup === g ? { background: bloodColor(g) } : null}
              onClick={() => set('bloodGroup', g)}>{g}</button>
          ))}
        </div>
      ),
    },
    {
      phase: 'medical', key: 'splenectomy', eyebrow: 'Medical profile', title: 'Have you had your spleen removed?',
      hint: 'A splenectomy adds a couple of extra checks to your schedule.',
      valid: () => true,
      render: () => (
        <div className="wf-opts">
          <WfOpt on={f.splenectomy === false} title="No" desc="My spleen hasn’t been removed." onClick={() => set('splenectomy', false)} />
          <WfOpt on={f.splenectomy === true} title="Yes" desc="I’ve had a splenectomy." onClick={() => set('splenectomy', true)} />
        </div>
      ),
    },
    {
      phase: 'medical', key: 'weight', eyebrow: 'Medical profile', title: 'What’s your current weight?',
      hint: 'Used to calculate your weight-based chelation dose targets.',
      valid: () => { const w = parseFloat(f.weight); return w > 0 && w < 250; },
      render: () => (
        <div className="row" style={{ gap: 10 }}>
          <input className="input" style={{ fontSize: 22, fontWeight: 800, textAlign: 'center', padding: '16px 14px' }}
            type="number" inputMode="decimal" step="0.5" value={f.weight} autoFocus
            onChange={(e) => set('weight', e.target.value)} placeholder="e.g. 58" />
          <span className="input" style={{ width: 64, flex: 'none', textAlign: 'center', fontWeight: 800, color: 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 17 }}>kg</span>
        </div>
      ),
    },
    {
      phase: 'medical', key: 'treatmentCenter', eyebrow: 'Medical profile', title: 'Where do you usually transfuse?', optional: true,
      hint: 'Optional — your transfusion hospital or centre.',
      valid: () => true,
      render: () => <input className="input" style={{ fontSize: 18 }} value={f.treatmentCenter} autoFocus
        onChange={(e) => set('treatmentCenter', e.target.value)} placeholder="e.g. Maldivian Blood Services" />,
    },
    {
      phase: 'medical', key: 'interval', eyebrow: 'Medical profile', title: 'How often do you usually transfuse?', optional: true,
      hint: 'Optional — helps us forecast your next transfusion from day one.',
      valid: () => true,
      render: () => (
        <div className="wf-opts">
          {WF_INTERVALS.map((it) => <WfOpt key={it.v} on={f.interval === it.v} title={it.v} onClick={() => set('interval', it.v)} />)}
        </div>
      ),
    },
    {
      phase: 'medical', key: 'chelation', eyebrow: 'Medical profile', title: 'Are you on chelation therapy?', optional: true,
      hint: 'Optional — add your iron-chelation medication, dose and frequency.',
      valid: () => true,
      render: () => (
        <div>
          {meds.length === 0 ? (
            <button className="wf-add" onClick={openChelation}>
              <span className="wf-add-ic"><Icon name="plus" size={20} color="var(--orange)" sw={2.6} /></span>
              <div style={{ textAlign: 'left' }}>
                <div className="wf-add-t">Add a chelation medication</div>
                <div className="wf-add-d">We’ll calculate weight-based dose targets for you.</div>
              </div>
            </button>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {meds.map((m) => (
                <div key={m.id} className="wf-medcard">
                  <span className="wf-add-ic"><Icon name="pill" size={18} color="var(--orange)" /></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="wf-add-t">{m.brand}</div>
                    <div className="wf-add-d">{m.dose || TC.medDoseLabel(m)}{m.frequency ? ' · ' + TC.medFreqLabel(m.frequency) : ''}</div>
                  </div>
                  <Icon name="check" size={18} color="var(--green)" sw={2.6} />
                </div>
              ))}
              <button className="wf-skip" style={{ alignSelf: 'flex-start', color: 'var(--orange)' }} onClick={openChelation}>+ Add another</button>
            </div>
          )}
        </div>
      ),
    },

    // ---- PHASE 4 · REMINDERS ----
    {
      phase: 'prefs', key: 'prefs', eyebrow: 'Reminders', title: 'How should we keep you on track?',
      hint: 'Pick the gentle nudges you’d like. You can change these anytime.',
      valid: () => true,
      render: () => <WfPrefs prefs={f.reminders} set={setRem} />,
    },
  ];

  const cur = steps[step];
  const total = steps.length;

  // phase-rail maths
  const phaseIndex = WF_PHASES.findIndex((p) => p.key === cur.phase);
  const phaseSteps = steps.filter((s) => s.phase === cur.phase);
  const localIndex = phaseSteps.findIndex((s) => s.key === cur.key);
  const fill = (localIndex + 1) / phaseSteps.length;

  // persist progress for resume (save automatically / finish later)
  React.useEffect(() => {
    if (screen === 'onboard') {
      try { localStorage.setItem(WF_OB_KEY, JSON.stringify({ step, f })); } catch (e) {}
    }
  }, [screen, step, f]);
  const clearProgress = () => { try { localStorage.removeItem(WF_OB_KEY); } catch (e) {} };

  const next = () => {
    if (!cur.valid()) return;
    if (step < total - 1) setStep(step + 1);
    else setScreen('finish');
  };
  const back = () => { if (step > 0) setStep(step - 1); else setScreen('auth'); };

  const finish = () => { clearProgress(); onComplete(f); };

  // ---------- render ----------
  if (screen === 'splash') {
    return <WfSplash resuming={hasSaved}
      onStart={() => { if (hasSaved || cloud) { setScreen('onboard'); } else { setAuthMode('choices'); setScreen('auth'); } }}
      onHaveAccount={() => { if (cloud) { setScreen('onboard'); } else { setAuthMode('login'); setScreen('auth'); } }} />;
  }

  if (screen === 'auth') {
    return <WfAuth mode={authMode} setMode={setAuthMode}
      onGoogle={handleGoogle} onLogin={onSignIn} onSignup={startSignup} />;
  }

  if (screen === 'finish') {
    return (
      <div className="wf">
        <div className="wf-finish">
          <div className="wf-finish-art stagger"><Pearl size={104} /></div>
          <div className="wf-h" style={{ marginTop: 6 }}>You’re all set, {f.preferredName || 'friend'}.</div>
          <div className="wf-sub" style={{ maxWidth: 300 }}>We’ll personalise your experience as you add more information over time. Everything you shared lives safely in your Medical Profile.</div>
          <button className="wf-btn wf-btn-primary" style={{ marginTop: 26, width: '100%', maxWidth: 320 }} onClick={finish}>
            Enter MUIY
          </button>
        </div>
      </div>
    );
  }

  // doc overlay sits above the onboard screen
  if (showDoc) {
    return <WfDoc which={showDoc} onBack={() => setShowDoc(null)} />;
  }

  // onboard
  return (
    <div className="wf">
      <div className="wf-prog-row">
        <button className="wf-back" onClick={back} aria-label="Back"><Icon name="chevL" size={20} /></button>
        <WfPhaseRail phaseIndex={phaseIndex} fill={fill} />
      </div>

      <div className="wf-scroll">
        <div className="wf-q" key={'q' + step}>
          <div className="wf-eyebrow">{cur.eyebrow}</div>
          <div className="wf-qtitle">{cur.title}</div>
          {cur.hint && <div className="wf-qhint">{cur.hint}</div>}
        </div>
        <div className="wf-control" key={'c' + step}>{cur.render()}</div>
      </div>

      <div className="wf-foot">
        <button className="wf-btn wf-btn-primary" style={{ opacity: cur.valid() ? 1 : 0.45 }}
          disabled={!cur.valid()} onClick={next}>
          {cur.buttonLabel || (step === total - 1 ? 'Finish' : 'Continue')}
        </button>
        {cur.optional && <button className="wf-skip" onClick={() => { if (step < total - 1) setStep(step + 1); else setScreen('finish'); }}>Skip for now</button>}
      </div>

      {showChel && store && <ChelationSetupWizard store={store} close={() => setShowChel(false)} />}
    </div>
  );
}

Object.assign(window, { WelcomeFlow, WfSplash });
