// Healify — Auth, onboarding, mental-health survey, permissions, error & empty states.
// Requires components.jsx + screens-primary.jsx loaded first.
//
// Architecture note: every screen here is reachable through a string route
// from the App router. Onboarding is a self-contained flow with internal
// step state — it doesn't push every step onto the global history stack
// (you don't want Back inside onboarding to feel like browser-back). One
// onboarding "screen" wraps all 8 steps; onboarding completes by
// resetting the stack to 'home'.

const { useState: useStateO, useEffect: useEffectO, useRef: useRefO } = React;

// ══════════════════════════════════════════════════════════════════════════
// Auth — splash + sign in + register + password reset + email verify + MFA
// ══════════════════════════════════════════════════════════════════════════
//
// The auth surface is split into many small screens rather than one giant
// stack so every state is screenshot-able for App Store / docs / QA. Each
// pushes onto the router and uses the standard HTopBar back affordance.

function AuthSplashScreen({ onNavigate }) {
  return (
    <div className="screen-enter" style={{
      padding: '60px 24px 40px', background: H.bg, minHeight: '100%',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18, textAlign: 'center' }}>
        <HealifyMark size={88} />
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 34, letterSpacing: -0.6, marginTop: 12, lineHeight: 1.05 }}>
          Your AI<br/>health coach
        </div>
        <div style={{ fontFamily: H.body, fontSize: 15, color: H.fg2, lineHeight: 1.5, maxWidth: 300 }}>
          Daily check-ins. Your data, understood. Personal plans that adapt.
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <HPrimaryButton onClick={() => onNavigate('auth-register')}>Get started</HPrimaryButton>
        <HPrimaryButton type="ghost" onClick={() => onNavigate('auth-signin')}>
          I already have an account
        </HPrimaryButton>
      </div>

      <div style={{ marginTop: 18, fontFamily: H.body, fontSize: 11, color: H.fg3, textAlign: 'center', lineHeight: 1.5 }}>
        By continuing you agree to the <b style={{ color: H.fg2 }}>Terms</b> & <b style={{ color: H.fg2 }}>Privacy Policy</b>.
      </div>
    </div>
  );
}

// ── Tiny reusable input field ─────────────────────────────────────────────
function AuthInput({ label, type = 'text', value, onChange, error, autoFocus, trailing }) {
  const [focused, setFocused] = useStateO(false);
  return (
    <label style={{ display: 'block' }}>
      <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginBottom: 6, letterSpacing: 0.2 }}>{label}</div>
      <div style={{
        position: 'relative',
        background: '#fff',
        border: '1px solid ' + (error ? H.danger : focused ? H.fg2 : H.border),
        borderRadius: 14,
        padding: '0 14px',
        height: 50,
        display: 'flex', alignItems: 'center',
        transition: 'border-color 120ms',
      }}>
        <input
          autoFocus={autoFocus}
          type={type}
          value={value}
          onChange={e => onChange && onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          style={{
            flex: 1, border: 'none', outline: 'none', background: 'transparent',
            fontFamily: H.body, fontSize: 16, color: H.fg1,
          }}
        />
        {trailing}
      </div>
      {error && <div style={{ fontFamily: H.body, fontSize: 12, color: H.danger, marginTop: 6, marginLeft: 4 }}>{error}</div>}
    </label>
  );
}

function AuthSignInScreen({ onNavigate, onBack }) {
  const [email, setEmail] = useStateO('kathryn@example.com');
  const [pw, setPw] = useStateO('');
  const [showPw, setShowPw] = useStateO(false);
  const [err, setErr] = useStateO(null);
  const [social, setSocial] = useStateO(null); // 'apple' | 'google'

  const submit = () => {
    if (!email.includes('@')) { setErr('Enter a valid email'); return; }
    if (pw.length < 6)       { setErr('Password must be at least 6 characters'); return; }
    setErr(null);
    onNavigate('home', {});
  };

  useEffectO(() => {
    if (!social) return;
    const t = setTimeout(() => { setSocial(null); onNavigate('home'); }, 1400);
    return () => clearTimeout(t);
  }, [social]);

  return (
    <div className="screen-enter" style={{ padding: '14px 20px 40px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="" />

      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, letterSpacing: -0.4, marginTop: 8 }}>Welcome back</div>
      <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 4, marginBottom: 24 }}>Sign in to continue.</div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <AuthInput label="Email" type="email" value={email} onChange={setEmail} error={err && !email.includes('@') ? err : null} autoFocus />
        <AuthInput
          label="Password"
          type={showPw ? 'text' : 'password'}
          value={pw}
          onChange={setPw}
          error={err && pw.length < 6 ? err : null}
          trailing={
            <button onClick={() => setShowPw(v => !v)} style={{
              border: 0, background: 'transparent', padding: '4px 6px', cursor: 'pointer',
              fontFamily: H.body, fontSize: 12, color: H.fg2,
            }}>{showPw ? 'Hide' : 'Show'}</button>
          }
        />

        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button onClick={() => onNavigate('auth-reset')} style={{ border: 0, background: 'transparent', cursor: 'pointer', fontFamily: H.body, fontSize: 13, color: H.fg2 }}>
            Forgot password?
          </button>
        </div>

        <HPrimaryButton onClick={submit}>Sign in</HPrimaryButton>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '24px 0' }}>
        <div style={{ flex: 1, height: 1, background: H.border }}/>
        <span style={{ fontFamily: H.body, fontSize: 12, color: H.fg3 }}>or</span>
        <div style={{ flex: 1, height: 1, background: H.border }}/>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <SocialButton provider="apple"  onClick={() => setSocial('apple')}/>
        <SocialButton provider="google" onClick={() => setSocial('google')}/>
      </div>

      <div style={{ textAlign: 'center', marginTop: 28, fontFamily: H.body, fontSize: 14, color: H.fg2 }}>
        New to Healify?{' '}
        <button onClick={() => onNavigate('auth-register')} style={{ border: 0, background: 'transparent', cursor: 'pointer', fontFamily: H.body, fontSize: 14, color: H.orange, fontWeight: 500 }}>
          Create account
        </button>
      </div>

      {social && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 220,
          background: 'rgba(3,4,13,0.42)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{
            background: '#fff', borderRadius: 22, padding: '24px 22px',
            width: 260, textAlign: 'center', boxShadow: '0 18px 40px rgba(3,4,13,0.18)',
          }}>
            <HSpinner size={36} color={H.orange} />
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, marginTop: 12 }}>
              Signing in with {social === 'apple' ? 'Apple' : 'Google'}…
            </div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 4 }}>Verifying your account</div>
          </div>
        </div>
      )}
    </div>
  );
}

function SocialButton({ provider, onClick }) {
  const meta = {
    apple:  { label: 'Continue with Apple',  bg: H.fg1,    fg: '#fff',
              icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="#fff"><path d="M16.4 1.4c0 1.2-.5 2.3-1.3 3.1-.9 1-2.4 1.7-3.6 1.6-.2-1.2.4-2.4 1.2-3.2.9-1 2.4-1.6 3.7-1.5zm4.3 16.5c-.7 1.6-1 2.3-1.9 3.7-1.3 1.9-3.1 4.3-5.4 4.3-2 0-2.5-1.3-5.2-1.3-2.7 0-3.3 1.4-5.3 1.3-2.3 0-4-2.2-5.3-4.1C-1 17.4-1.4 11.6 1.7 8.6c2.2-2.1 5.6-2.1 7-2.1 1.5 0 4.3.9 6.5.9 1 0 4-1 6.6-.8 1.1.1 4.2.5 6.2 3.4-.1.1-3.7 2.2-3.3 6.6.1 5.2 4.7 7 4.7 7s-3.3 9.7-7.7 9.5z" transform="translate(0,-2) scale(0.7)"/></svg> },
    google: { label: 'Continue with Google', bg: '#fff',    fg: H.fg1, border: '1px solid ' + H.border,
              icon: <svg width="18" height="18" viewBox="0 0 24 24"><path fill="#4285F4" d="M23.5 12.27c0-.79-.07-1.54-.2-2.27H12v4.51h6.47a5.55 5.55 0 0 1-2.4 3.65v3.04h3.88c2.27-2.09 3.55-5.17 3.55-8.93Z"/><path fill="#34A853" d="M12 24c3.24 0 5.95-1.08 7.95-2.91l-3.88-3.04c-1.08.72-2.45 1.16-4.07 1.16-3.13 0-5.78-2.11-6.73-4.96H1.27v3.13A12 12 0 0 0 12 24Z"/><path fill="#FBBC05" d="M5.27 14.25a7.21 7.21 0 0 1 0-4.5V6.62H1.27a12 12 0 0 0 0 10.76l4-3.13Z"/><path fill="#EA4335" d="M12 4.74c1.77 0 3.35.61 4.6 1.8l3.43-3.43C17.95 1.18 15.24 0 12 0A12 12 0 0 0 1.27 6.62l4 3.13C6.22 6.85 8.87 4.74 12 4.74Z"/></svg> },
  }[provider];
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      width: '100%', height: 50, borderRadius: 999,
      background: meta.bg, color: meta.fg, border: meta.border || 0,
      fontFamily: H.body, fontWeight: 500, fontSize: 15,
      cursor: 'pointer',
    }}>
      {meta.icon}
      {meta.label}
    </button>
  );
}

function AuthRegisterScreen({ onNavigate, onBack }) {
  const [name, setName] = useStateO('');
  const [email, setEmail] = useStateO('');
  const [pw, setPw] = useStateO('');
  const submit = () => onNavigate('auth-verify', { email });
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 40px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="" />
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, letterSpacing: -0.4, marginTop: 8 }}>Create account</div>
      <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 4, marginBottom: 24 }}>Three quick fields. We'll personalise next.</div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <AuthInput label="Name"     value={name}  onChange={setName}  autoFocus />
        <AuthInput label="Email"    value={email} onChange={setEmail} type="email" />
        <AuthInput label="Password" value={pw}    onChange={setPw}    type="password" />

        {/* Password strength meter — minimal hint */}
        <div style={{ display: 'flex', gap: 4 }}>
          {[0,1,2,3].map(i => (
            <div key={i} style={{
              flex: 1, height: 3, borderRadius: 2,
              background: pw.length > i*2 ? (pw.length > 8 ? H.success : H.warning) : 'rgba(3,4,13,0.06)',
              transition: 'background 200ms',
            }}/>
          ))}
        </div>
        <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, marginTop: -8, marginLeft: 4 }}>
          Use 8+ characters · mix of letters, numbers, symbols
        </div>

        <HPrimaryButton onClick={submit} disabled={!name || !email.includes('@') || pw.length < 6}>
          Continue
        </HPrimaryButton>
      </div>

      <div style={{ marginTop: 18, fontFamily: H.body, fontSize: 11, color: H.fg3, textAlign: 'center', lineHeight: 1.5 }}>
        We'll send a verification code to your email.
      </div>
    </div>
  );
}

function AuthResetScreen({ onNavigate, onBack }) {
  const [email, setEmail] = useStateO('');
  const [sent, setSent] = useStateO(false);
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 40px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="" />
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, letterSpacing: -0.4, marginTop: 8 }}>Reset password</div>
      <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 4, marginBottom: 24 }}>
        {sent ? `Sent. Check ${email} for a reset link.` : "We'll email you a reset link."}
      </div>

      {!sent && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <AuthInput label="Email" value={email} onChange={setEmail} type="email" autoFocus />
          <HPrimaryButton onClick={() => setSent(true)} disabled={!email.includes('@')}>Send reset link</HPrimaryButton>
        </div>
      )}

      {sent && (
        <>
          <HCard style={{ padding: 18, borderRadius: 18, display: 'flex', alignItems: 'center', gap: 12 }}>
            <HIconTile color={H.success} alpha={0.15} size={36}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={H.success} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
            </HIconTile>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>Email sent</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>Link expires in 30 min</div>
            </div>
          </HCard>
          <div style={{ marginTop: 16 }}>
            <HPrimaryButton type="outline" onClick={onBack}>Back to sign in</HPrimaryButton>
          </div>
        </>
      )}
    </div>
  );
}

function AuthVerifyScreen({ onNavigate, onBack, email = 'you@example.com' }) {
  const [code, setCode] = useStateO(['','','','','','']);
  const refs = useRefO([]);
  const [toast, setToast] = useStateO(null);

  const set = (i, v) => {
    if (v && !/^\d$/.test(v)) return;
    setCode(c => { const n = [...c]; n[i] = v; return n; });
    if (v && i < 5) refs.current[i+1]?.focus();
  };
  const onKey = (i, e) => {
    if (e.key === 'Backspace' && !code[i] && i > 0) refs.current[i-1]?.focus();
  };

  const allFilled = code.every(c => c !== '');
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 40px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="" />
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, letterSpacing: -0.4, marginTop: 8 }}>Verify email</div>
      <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 4, marginBottom: 24 }}>
        Enter the 6-digit code we sent to <b style={{ color: H.fg1 }}>{email}</b>.
      </div>

      <div style={{ display: 'flex', gap: 8, justifyContent: 'space-between' }}>
        {code.map((c, i) => (
          <input
            key={i}
            ref={el => (refs.current[i] = el)}
            value={c}
            onChange={e => set(i, e.target.value.slice(-1))}
            onKeyDown={e => onKey(i, e)}
            inputMode="numeric"
            maxLength={1}
            style={{
              flex: 1, height: 56, textAlign: 'center',
              fontFamily: H.body, fontWeight: 500, fontSize: 24,
              border: '1px solid ' + (c ? H.fg2 : H.border),
              borderRadius: 14, background: '#fff',
              outline: 'none',
            }}
          />
        ))}
      </div>

      <div style={{ marginTop: 24 }}>
        <HPrimaryButton onClick={() => onNavigate('onboarding')} disabled={!allFilled}>Verify</HPrimaryButton>
      </div>

      <div style={{ textAlign: 'center', marginTop: 18, fontFamily: H.body, fontSize: 13, color: H.fg2 }}>
        Didn't get it?{' '}
        <button onClick={() => setToast('New code sent to ' + email)} style={{ border: 0, background: 'transparent', cursor: 'pointer', fontFamily: H.body, fontSize: 13, color: H.orange, fontWeight: 500 }}>
          Resend
        </button>
      </div>
      {toast && <HToast msg={toast} onDone={() => setToast(null)} />}
    </div>
  );
}

function AuthMFAScreen({ onNavigate, onBack }) {
  const [method, setMethod] = useStateO('totp');
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 40px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Two-factor auth" />
      <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 4, marginBottom: 18, lineHeight: 1.5 }}>
        Add a second layer of security to your account. Choose how you want to receive codes.
      </div>

      <HSettingsGroup>
        {[
          { k: 'totp', title: 'Authenticator app', detail: 'Recommended' },
          { k: 'sms',  title: 'Text message',      detail: '+1 ··· 4521' },
          { k: 'email', title: 'Email',            detail: 'kathryn@…' },
        ].map((o, i, a) => (
          <div key={o.k} onClick={() => setMethod(o.k)} style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
            borderBottom: i === a.length - 1 ? 'none' : '0.5px solid ' + H.border,
            cursor: 'pointer',
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: 999,
              border: '2px solid ' + (method === o.k ? H.orange : H.border),
              background: method === o.k ? H.orange : 'transparent',
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              {method === o.k && <div style={{ width: 8, height: 8, borderRadius: 999, background: '#fff' }}/>}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{o.title}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{o.detail}</div>
            </div>
          </div>
        ))}
      </HSettingsGroup>

      <div style={{ marginTop: 20 }}>
        <HPrimaryButton onClick={() => onNavigate('home')}>Set up</HPrimaryButton>
        <div style={{ height: 8 }}/>
        <HPrimaryButton type="ghost" onClick={() => onNavigate('home')}>Skip for now</HPrimaryButton>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Onboarding — single screen, internal step state
// ══════════════════════════════════════════════════════════════════════════
//
// 8 steps. Internal state, not router state — Back inside onboarding pops a
// step; Back from step 0 exits onboarding (returns to auth splash, since
// onboarding always launches from there).

const ONBOARDING_STEPS = [
  'welcome',     // 3-card carousel
  'goals',       // multi-select goals
  'metrics',     // body metrics
  'food',        // food preferences
  'allergies',   // allergies
  'activity',    // activity level
  'sleep',       // sleep schedule
  'notifications', // notif opt-in
];

function OnboardingScreen({ onNavigate, onBack }) {
  const [step, setStep] = useStateO(0);
  // Collected answers — kept locally; in production would POST on each step.
  const [data, setData] = useStateO({
    goals: [], height: '', weight: '', age: '', sex: 'female',
    diet: 'balanced', allergies: [], activity: 'moderate',
    sleepStart: '23:00', sleepEnd: '07:00', notifications: true,
  });
  const set = (patch) => setData(d => ({ ...d, ...patch }));

  const next = () => {
    if (step === ONBOARDING_STEPS.length - 1) {
      // Hand off to mental-health survey, which then completes to home.
      onNavigate('survey-intro');
    } else {
      setStep(s => s + 1);
    }
  };
  const back = () => step === 0 ? onBack() : setStep(s => s - 1);

  const Step = ({ children }) => (
    <div style={{ paddingTop: 8, display: 'flex', flexDirection: 'column', minHeight: 'calc(100% - 56px)' }}>
      {children}
    </div>
  );

  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header: back + segmented progress */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
        <HBackButton onClick={back} variant={step === 0 ? 'close' : 'back'} label="" />
        <div style={{ flex: 1, display: 'flex', gap: 3 }}>
          {ONBOARDING_STEPS.map((_, i) => (
            <div key={i} style={{
              flex: 1, height: 4, borderRadius: 2,
              background: i < step ? H.fg1 : i === step ? H.orange : 'rgba(3,4,13,0.06)',
              transition: 'background 220ms',
              position: 'relative', overflow: 'hidden',
            }}>
              {i === step && (
                <div style={{
                  position: 'absolute', inset: 0, borderRadius: 2,
                  background: 'linear-gradient(90deg, transparent 0%, rgba(255,236,224,0.85) 50%, transparent 100%)',
                  backgroundSize: '200% 100%', backgroundRepeat: 'no-repeat',
                  animation: 'pg-shimmer 1.8s linear infinite', pointerEvents: 'none',
                }}/>
              )}
            </div>
          ))}
        </div>
        <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, fontVariantNumeric: 'tabular-nums', minWidth: 36, textAlign: 'right' }}>
          {step + 1}/{ONBOARDING_STEPS.length}
        </div>
      </div>

      <style>{`@keyframes pg-shimmer { from { background-position: 100% 0; } to { background-position: -100% 0; } }`}</style>

      {ONBOARDING_STEPS[step] === 'welcome' && (
        <Step>
          <div style={{ flex: 1 }}>
            <HealifyMark size={64} />
            <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 32, letterSpacing: -0.5, marginTop: 16, lineHeight: 1.05 }}>
              Welcome to<br/>Healify
            </div>
            <div style={{ fontFamily: H.body, fontSize: 15, color: H.fg2, marginTop: 12, lineHeight: 1.5 }}>
              We'll ask a few questions to set up your plan. Most people finish in 3 minutes.
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 28 }}>
              {[
                { i: HIcons.vitals, t: 'Track what matters', s: 'Sleep, vitals, mood — connected.' },
                { i: HIcons.mind,   t: 'Talk to Anna',       s: 'Your AI coach, 24/7.' },
                { i: HIcons.fitness,t: 'Move with intent',   s: 'Plans that adapt to your week.' },
              ].map((b, i) => (
                <HCard key={i} style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
                  <HIconTile color="var(--brand-orange-vibey)" alpha={0.14} size={40}>{b.i('var(--brand-orange-vibey)')}</HIconTile>
                  <div>
                    <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{b.t}</div>
                    <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{b.s}</div>
                  </div>
                </HCard>
              ))}
            </div>
          </div>
          <HPrimaryButton onClick={next}>Let's start</HPrimaryButton>
        </Step>
      )}

      {ONBOARDING_STEPS[step] === 'goals' && (
        <Step>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, lineHeight: 1.1 }}>
            What do you want from Healify?
          </div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6 }}>Pick all that apply.</div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 20, flex: 1 }}>
            {[
              { k: 'longevity',  t: 'Live longer, healthier',  i: HIcons.vitals,  c: 'var(--focus-heart-100)' },
              { k: 'energy',     t: 'More daily energy',        i: HIcons.fitness, c: 'var(--focus-fitness-100)' },
              { k: 'weight',     t: 'Manage weight',            i: HIcons.nutrition, c: 'var(--focus-nutrition-100)' },
              { k: 'sleep',      t: 'Better sleep',             i: HIcons.sleep,   c: 'var(--focus-sleep-100)' },
              { k: 'stress',     t: 'Lower stress',             i: HIcons.mind,    c: 'var(--focus-mental-100)' },
              { k: 'fitness',    t: 'Get stronger / fitter',    i: HIcons.fitness, c: 'var(--focus-fitness-100)' },
            ].map(g => {
              const selected = data.goals.includes(g.k);
              return (
                <HCard key={g.k} onClick={() => set({ goals: selected ? data.goals.filter(x => x !== g.k) : [...data.goals, g.k] })}
                       style={{
                         padding: 14, display: 'flex', alignItems: 'center', gap: 12,
                         border: '1px solid ' + (selected ? H.orange : 'transparent'),
                         background: selected ? 'rgba(255,105,66,0.04)' : '#fff',
                       }}>
                  <HIconTile color={g.c} alpha={0.18} size={36}>{g.i(g.c)}</HIconTile>
                  <div style={{ flex: 1, fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{g.t}</div>
                  <div style={{
                    width: 22, height: 22, borderRadius: 999,
                    border: '2px solid ' + (selected ? H.orange : H.border),
                    background: selected ? H.orange : 'transparent',
                    display: 'grid', placeItems: 'center', flexShrink: 0,
                  }}>
                    {selected && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>}
                  </div>
                </HCard>
              );
            })}
          </div>

          <HPrimaryButton onClick={next} disabled={data.goals.length === 0}>Continue</HPrimaryButton>
        </Step>
      )}

      {ONBOARDING_STEPS[step] === 'metrics' && (
        <Step>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, lineHeight: 1.1 }}>
            Tell us about you
          </div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6 }}>Used to compute your Health Score.</div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 20, flex: 1 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <AuthInput label="Age" type="number" value={data.age} onChange={v => set({ age: v })} />
              <div>
                <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginBottom: 6, letterSpacing: 0.2 }}>Sex</div>
                <div style={{ display: 'flex', background: 'rgba(3,4,13,0.04)', borderRadius: 14, padding: 3 }}>
                  {['female','male','other'].map(s => (
                    <div key={s} onClick={() => set({ sex: s })} style={{
                      flex: 1, padding: '10px 4px', textAlign: 'center',
                      fontFamily: H.body, fontSize: 13, fontWeight: 500,
                      borderRadius: 11, cursor: 'pointer',
                      background: data.sex === s ? '#fff' : 'transparent',
                      color: data.sex === s ? H.fg1 : H.fg2,
                      boxShadow: data.sex === s ? '0 1px 3px rgba(3,4,13,0.06)' : 'none',
                      transition: 'all 120ms',
                      textTransform: 'capitalize',
                    }}>{s}</div>
                  ))}
                </div>
              </div>
            </div>
            <AuthInput label="Height (cm)" type="number" value={data.height} onChange={v => set({ height: v })} />
            <AuthInput label="Weight (kg)" type="number" value={data.weight} onChange={v => set({ weight: v })} />
          </div>

          <HPrimaryButton onClick={next} disabled={!data.age || !data.height || !data.weight}>Continue</HPrimaryButton>
        </Step>
      )}

      {ONBOARDING_STEPS[step] === 'food' && (
        <Step>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, lineHeight: 1.1 }}>
            How do you eat?
          </div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6 }}>So Anna can suggest meal plans you'll actually want.</div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 20, flex: 1 }}>
            {[
              { k: 'balanced',    t: 'Balanced',    sub: 'No restrictions', emoji: '🍽️' },
              { k: 'mediterranean', t: 'Mediterranean', sub: 'Fish, veg, olive oil', emoji: '🐟' },
              { k: 'vegetarian',  t: 'Vegetarian',  sub: 'No meat / fish', emoji: '🥦' },
              { k: 'vegan',       t: 'Vegan',       sub: 'Plant-based', emoji: '🌱' },
              { k: 'keto',        t: 'Keto',        sub: 'Low carb, high fat', emoji: '🥑' },
              { k: 'paleo',       t: 'Paleo',       sub: 'Whole foods', emoji: '🍖' },
            ].map(d => {
              const selected = data.diet === d.k;
              return (
                <HCard key={d.k} onClick={() => set({ diet: d.k })}
                       style={{
                         padding: 14, display: 'flex', flexDirection: 'column', gap: 6,
                         border: '1px solid ' + (selected ? H.orange : 'transparent'),
                         background: selected ? 'rgba(255,105,66,0.04)' : '#fff',
                         alignSelf: 'start',
                       }}>
                  <div style={{ fontSize: 24 }}>{d.emoji}</div>
                  <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{d.t}</div>
                  <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg2, lineHeight: 1.3 }}>{d.sub}</div>
                </HCard>
              );
            })}
          </div>

          <HPrimaryButton onClick={next}>Continue</HPrimaryButton>
        </Step>
      )}

      {ONBOARDING_STEPS[step] === 'allergies' && (
        <Step>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, lineHeight: 1.1 }}>
            Any allergies or intolerances?
          </div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6 }}>We'll always check before suggesting recipes.</div>

          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 20, flex: 1, alignContent: 'flex-start' }}>
            {['Peanuts','Tree nuts','Dairy','Gluten','Eggs','Soy','Shellfish','Fish','Sesame','Citrus','Nightshades','None of these'].map(a => {
              const selected = data.allergies.includes(a);
              return (
                <div key={a} onClick={() => set({ allergies: selected ? data.allergies.filter(x => x !== a) : (a === 'None of these' ? ['None of these'] : [...data.allergies.filter(x => x !== 'None of these'), a]) })}
                     style={{
                       padding: '10px 16px', borderRadius: 999,
                       background: selected ? H.fg1 : '#fff',
                       color: selected ? '#fff' : H.fg1,
                       fontFamily: H.body, fontSize: 14, fontWeight: 500,
                       border: '1px solid ' + (selected ? H.fg1 : H.border),
                       cursor: 'pointer', transition: 'all 120ms',
                     }}>
                  {a}
                </div>
              );
            })}
          </div>

          <HPrimaryButton onClick={next}>Continue</HPrimaryButton>
        </Step>
      )}

      {ONBOARDING_STEPS[step] === 'activity' && (
        <Step>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, lineHeight: 1.1 }}>
            How active are you?
          </div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6 }}>Honest answer is fine. We'll meet you where you are.</div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 20, flex: 1 }}>
            {[
              { k: 'sedentary', t: 'Sedentary',  sub: 'Mostly desk-bound, < 1 workout / week' },
              { k: 'light',     t: 'Lightly active', sub: '1–2 workouts / week, 5k+ steps' },
              { k: 'moderate',  t: 'Moderately active', sub: '3–4 workouts / week, 8k+ steps' },
              { k: 'high',      t: 'Very active', sub: '5+ workouts / week or athlete' },
            ].map(o => {
              const selected = data.activity === o.k;
              return (
                <HCard key={o.k} onClick={() => set({ activity: o.k })}
                       style={{
                         padding: 14, display: 'flex', alignItems: 'center', gap: 12,
                         border: '1px solid ' + (selected ? H.orange : 'transparent'),
                         background: selected ? 'rgba(255,105,66,0.04)' : '#fff',
                       }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{o.t}</div>
                    <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{o.sub}</div>
                  </div>
                  <div style={{
                    width: 22, height: 22, borderRadius: 999,
                    border: '2px solid ' + (selected ? H.orange : H.border),
                    background: selected ? H.orange : 'transparent',
                    display: 'grid', placeItems: 'center', flexShrink: 0,
                  }}>
                    {selected && <div style={{ width: 8, height: 8, borderRadius: 999, background: '#fff' }}/>}
                  </div>
                </HCard>
              );
            })}
          </div>

          <HPrimaryButton onClick={next}>Continue</HPrimaryButton>
        </Step>
      )}

      {ONBOARDING_STEPS[step] === 'sleep' && (
        <Step>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, lineHeight: 1.1 }}>
            When do you usually sleep?
          </div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6 }}>Roughly is fine — used to plan your wind-down.</div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 24, flex: 1 }}>
            {[
              { k: 'sleepStart', label: 'Bedtime', icon: '🌙' },
              { k: 'sleepEnd',   label: 'Wake up', icon: '☀️' },
            ].map(t => (
              <HCard key={t.k} style={{ padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{ fontSize: 24 }}>{t.icon}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2 }}>{t.label}</div>
                  <input
                    type="time"
                    value={data[t.k]}
                    onChange={e => set({ [t.k]: e.target.value })}
                    style={{
                      fontFamily: H.body, fontWeight: 500, fontSize: 22,
                      border: 'none', outline: 'none', background: 'transparent',
                      color: H.fg1, padding: 0, marginTop: 2,
                    }}
                  />
                </div>
              </HCard>
            ))}

            {(() => {
              // Compute total hours, very roughly
              const [sh, sm] = data.sleepStart.split(':').map(Number);
              const [eh, em] = data.sleepEnd.split(':').map(Number);
              let total = (eh*60+em) - (sh*60+sm);
              if (total <= 0) total += 24*60;
              const hrs = Math.floor(total/60), mins = total%60;
              return (
                <div style={{
                  background: 'rgba(3,4,13,0.04)', borderRadius: 14, padding: '12px 16px',
                  fontFamily: H.body, fontSize: 13, color: H.fg2,
                  display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <span style={{ fontWeight: 500, color: H.fg1 }}>{hrs}h {mins}m</span>
                  in bed · target is 7–9h for adults
                </div>
              );
            })()}
          </div>

          <HPrimaryButton onClick={next}>Continue</HPrimaryButton>
        </Step>
      )}

      {ONBOARDING_STEPS[step] === 'notifications' && (
        <Step>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', gap: 18 }}>
            <div style={{
              width: 96, height: 96, borderRadius: 28,
              background: 'var(--quartz-100)',
              display: 'grid', placeItems: 'center',
            }}>
              <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke={H.orange} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>
            </div>
            <div>
              <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, lineHeight: 1.15 }}>
                Daily check-ins<br/>that don't nag
              </div>
              <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 8, lineHeight: 1.5, maxWidth: 280, marginLeft: 'auto', marginRight: 'auto' }}>
                Anna sends one short prompt a day. Reply when you have a moment — she'll batch the rest.
              </div>
            </div>
          </div>
          <HPrimaryButton onClick={() => { set({ notifications: true }); next(); }}>Allow notifications</HPrimaryButton>
          <div style={{ height: 8 }}/>
          <HPrimaryButton type="ghost" onClick={() => { set({ notifications: false }); next(); }}>Maybe later</HPrimaryButton>
        </Step>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Mental health survey — PHQ-9 / GAD-7 style
// ══════════════════════════════════════════════════════════════════════════

const SURVEY_QUESTIONS = [
  { id: 'phq1',  group: 'phq', text: 'Little interest or pleasure in doing things?' },
  { id: 'phq2',  group: 'phq', text: 'Feeling down, depressed, or hopeless?' },
  { id: 'phq3',  group: 'phq', text: 'Trouble falling or staying asleep, or sleeping too much?' },
  { id: 'phq4',  group: 'phq', text: 'Feeling tired or having little energy?' },
  { id: 'phq5',  group: 'phq', text: 'Poor appetite or overeating?' },
  { id: 'phq6',  group: 'phq', text: 'Feeling bad about yourself — or that you\'ve let yourself down?' },
  { id: 'phq7',  group: 'phq', text: 'Trouble concentrating on things, like reading or watching TV?' },
  { id: 'phq8',  group: 'phq', text: 'Moving or speaking so slowly other people noticed?' },
  { id: 'phq9',  group: 'phq', text: 'Thoughts that you would be better off dead or hurting yourself?' },
  { id: 'gad1',  group: 'gad', text: 'Feeling nervous, anxious, or on edge?' },
  { id: 'gad2',  group: 'gad', text: 'Not being able to stop or control worrying?' },
  { id: 'gad3',  group: 'gad', text: 'Worrying too much about different things?' },
  { id: 'gad4',  group: 'gad', text: 'Trouble relaxing?' },
  { id: 'gad5',  group: 'gad', text: 'Being so restless that it\'s hard to sit still?' },
  { id: 'gad6',  group: 'gad', text: 'Becoming easily annoyed or irritable?' },
  { id: 'gad7',  group: 'gad', text: 'Feeling afraid as if something awful might happen?' },
];

const SURVEY_OPTIONS = [
  { v: 0, label: 'Not at all',          sub: '' },
  { v: 1, label: 'Several days',        sub: '1–6 days' },
  { v: 2, label: 'More than half',      sub: '7–11 days' },
  { v: 3, label: 'Nearly every day',    sub: '12+ days' },
];

function SurveyIntroScreen({ onNavigate, onBack }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <HTopBar onBack={onBack} title="" />
      <div style={{ flex: 1, paddingTop: 12 }}>
        <HIconTile color="var(--focus-mental-100)" alpha={0.16} size={56} rounded="round">{HIcons.mind('var(--focus-mental-100)')}</HIconTile>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, letterSpacing: -0.4, marginTop: 16, lineHeight: 1.15 }}>
          One last thing — your mental health
        </div>
        <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 10, lineHeight: 1.55 }}>
          16 short questions. Used to set a baseline so Anna can spot meaningful changes over time. Standard validated screen (PHQ-9 + GAD-7).
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 24 }}>
          {[
            { i: '🔒', t: 'Private', s: 'Stays on your account. Never sold.' },
            { i: '⏱', t: '~3 minutes', s: 'Tap-through, no typing.' },
            { i: '🩺', t: 'Not a diagnosis', s: 'Educational baseline. Speak to a clinician if concerning.' },
          ].map((b, i) => (
            <HCard key={i} style={{ padding: 14, display: 'flex', alignItems: 'flex-start', gap: 12 }}>
              <div style={{ fontSize: 22, lineHeight: 1, marginTop: 2 }}>{b.i}</div>
              <div>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{b.t}</div>
                <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 2, lineHeight: 1.45 }}>{b.s}</div>
              </div>
            </HCard>
          ))}
        </div>
      </div>

      <HPrimaryButton onClick={() => onNavigate('survey')}>Begin</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="ghost" onClick={() => onNavigate('home')}>Skip — I'll do it later</HPrimaryButton>
    </div>
  );
}

function SurveyScreen({ onNavigate, onBack }) {
  const [idx, setIdx] = useStateO(0);
  const [answers, setAnswers] = useStateO({});
  const q = SURVEY_QUESTIONS[idx];
  const total = SURVEY_QUESTIONS.length;

  const choose = (v) => {
    setAnswers(a => ({ ...a, [q.id]: v }));
    if (idx === total - 1) {
      // finalize and go to results
      const final = { ...answers, [q.id]: v };
      const phq = Object.entries(final).filter(([k]) => k.startsWith('phq')).reduce((s,[,v]) => s+v, 0);
      const gad = Object.entries(final).filter(([k]) => k.startsWith('gad')).reduce((s,[,v]) => s+v, 0);
      onNavigate('survey-results', { phq, gad, phq9: final.phq9 });
    } else {
      setTimeout(() => setIdx(i => i + 1), 220);
    }
  };

  const back = () => idx === 0 ? onBack() : setIdx(i => i - 1);

  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 22 }}>
        <HBackButton onClick={back} variant={idx === 0 ? 'close' : 'back'} label="" />
        <div style={{ flex: 1, height: 4, borderRadius: 2, background: 'rgba(3,4,13,0.06)', overflow: 'hidden', position: 'relative' }}>
          <div style={{
            position: 'absolute', left: 0, top: 0, bottom: 0,
            width: `${((idx + 1) / total) * 100}%`,
            background: H.orange, borderRadius: 2,
            transition: 'width 280ms cubic-bezier(.16,1,.3,1)',
          }}/>
        </div>
        <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, fontVariantNumeric: 'tabular-nums', minWidth: 44, textAlign: 'right' }}>
          {idx + 1}/{total}
        </div>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1.2, color: H.fg3, textTransform: 'uppercase', marginBottom: 12 }}>
          Over the past 2 weeks, how often have you been bothered by…
        </div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24, letterSpacing: -0.3, lineHeight: 1.25, marginBottom: 32 }}>
          {q.text}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
          {SURVEY_OPTIONS.map(o => {
            const selected = answers[q.id] === o.v;
            return (
              <HCard key={o.v} onClick={() => choose(o.v)}
                     style={{
                       padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 14,
                       border: '1px solid ' + (selected ? H.orange : 'transparent'),
                       background: selected ? 'rgba(255,105,66,0.04)' : '#fff',
                     }}>
                <div style={{
                  width: 24, height: 24, borderRadius: 999,
                  border: '2px solid ' + (selected ? H.orange : H.border),
                  background: selected ? H.orange : 'transparent',
                  display: 'grid', placeItems: 'center', flexShrink: 0,
                }}>
                  {selected && <div style={{ width: 8, height: 8, borderRadius: 999, background: '#fff' }}/>}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{o.label}</div>
                  {o.sub && <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 2 }}>{o.sub}</div>}
                </div>
              </HCard>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function SurveyResultsScreen({ onNavigate, onBack, phq = 8, gad = 6, phq9 = 0 }) {
  // PHQ-9 banding
  const phqBand =
    phq <= 4  ? { t: 'Minimal',  c: H.success, body: 'Below typical screening thresholds.' } :
    phq <= 9  ? { t: 'Mild',     c: H.success, body: 'Within a normal range — keep an eye on patterns.' } :
    phq <= 14 ? { t: 'Moderate', c: H.warning, body: 'Worth monitoring. Consider speaking with a clinician.' } :
    phq <= 19 ? { t: 'Mod-severe', c: H.warning, body: 'Speaking with a clinician is recommended.' } :
                { t: 'Severe',   c: H.danger,  body: 'Speaking with a clinician is strongly recommended.' };
  // GAD-7 banding
  const gadBand =
    gad <= 4  ? { t: 'Minimal',  c: H.success, body: 'Below typical screening thresholds.' } :
    gad <= 9  ? { t: 'Mild',     c: H.success, body: 'Within a normal range.' } :
    gad <= 14 ? { t: 'Moderate', c: H.warning, body: 'Worth monitoring.' } :
                { t: 'Severe',   c: H.danger,  body: 'Speaking with a clinician is recommended.' };

  // PHQ-9 question 9 — self-harm flag
  const selfHarm = (phq9 || 0) > 0;

  return (
    <div className="screen-enter" style={{ padding: '14px 20px 40px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Results" />

      {selfHarm && (
        <HCard style={{ padding: 16, borderRadius: 18, background: 'var(--error-50)', border: '1px solid ' + H.danger, marginBottom: 18 }}>
          <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 14, color: H.danger, marginBottom: 6 }}>
            We're glad you answered honestly
          </div>
          <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg1, lineHeight: 1.55 }}>
            If you're having thoughts of self-harm, please reach out. In the US, call or text <b>988</b>. In the UK, call <b>Samaritans on 116 123</b>. Anna will check in with you again tomorrow.
          </div>
          <div style={{ marginTop: 12 }}>
            <HPrimaryButton type="outline-brand" onClick={() => {}}>Get help now</HPrimaryButton>
          </div>
        </HCard>
      )}

      <HCard style={{ padding: 22, textAlign: 'center', borderRadius: 22, marginBottom: 14 }}>
        <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1.2, color: H.fg3, textTransform: 'uppercase' }}>Depression · PHQ-9</div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 56, letterSpacing: -1, color: phqBand.c, marginTop: 6 }}>{phq}</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg3 }}>of 27</div>
        <div style={{ display: 'inline-block', marginTop: 10, padding: '4px 12px', borderRadius: 999, background: phqBand.c + '22', color: phqBand.c, fontFamily: H.body, fontSize: 13, fontWeight: 500 }}>
          {phqBand.t}
        </div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 12, lineHeight: 1.5 }}>{phqBand.body}</div>
      </HCard>

      <HCard style={{ padding: 22, textAlign: 'center', borderRadius: 22, marginBottom: 18 }}>
        <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1.2, color: H.fg3, textTransform: 'uppercase' }}>Anxiety · GAD-7</div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 56, letterSpacing: -1, color: gadBand.c, marginTop: 6 }}>{gad}</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg3 }}>of 21</div>
        <div style={{ display: 'inline-block', marginTop: 10, padding: '4px 12px', borderRadius: 999, background: gadBand.c + '22', color: gadBand.c, fontFamily: H.body, fontSize: 13, fontWeight: 500 }}>
          {gadBand.t}
        </div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 12, lineHeight: 1.5 }}>{gadBand.body}</div>
      </HCard>

      <HCard style={{ padding: 18, borderRadius: 18, marginBottom: 18, background: 'var(--quartz-50)' }}>
        <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1, color: H.fg3, textTransform: 'uppercase' }}>What's next</div>
        <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg1, marginTop: 8, lineHeight: 1.55 }}>
          Anna will check in weekly with shorter versions of these questions. Trends over time matter much more than any single score.
        </div>
      </HCard>

      <HPrimaryButton onClick={() => onNavigate('permissions-health')}>Connect health data</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="ghost" onClick={() => onNavigate('home')}>Skip to dashboard</HPrimaryButton>

      <div style={{ marginTop: 18, fontFamily: H.body, fontSize: 11, color: H.fg3, textAlign: 'center', lineHeight: 1.5 }}>
        PHQ-9 & GAD-7 are validated screens, not diagnostic tools.
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Permissions
// ══════════════════════════════════════════════════════════════════════════

function PermissionsHealthScreen({ onNavigate, onBack }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <HTopBar onBack={onBack} title="" />
      <div style={{ flex: 1, paddingTop: 12 }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
          <div style={{
            width: 56, height: 56, borderRadius: 16,
            background: '#fff', display: 'grid', placeItems: 'center',
            boxShadow: '0 1px 3px rgba(3,4,13,0.08)',
          }}>
            <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke={H.danger} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
          </div>
          <div>
            <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1.2, color: H.fg3, textTransform: 'uppercase' }}>Step 1 of 2</div>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 16, marginTop: 2 }}>Apple Health</div>
          </div>
        </div>

        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, marginTop: 24, lineHeight: 1.15 }}>
          Sync your health data
        </div>
        <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 8, lineHeight: 1.55 }}>
          Healify reads (never writes) the metrics below. You can change this anytime in Settings.
        </div>

        <div style={{ marginTop: 22 }}>
          <HSettingsGroup>
            {[
              { i: '❤️', t: 'Heart rate & HRV',     d: 'Resting and active' },
              { i: '🛌', t: 'Sleep',                d: 'Stages, time in bed' },
              { i: '🏃', t: 'Activity',             d: 'Steps, workouts, distance' },
              { i: '⚖️', t: 'Body measurements',     d: 'Weight, body fat %' },
              { i: '🩸', t: 'Lab results',          d: 'When you upload PDFs' },
            ].map((p, i, a) => (
              <div key={p.t} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                borderBottom: i === a.length - 1 ? 'none' : '0.5px solid ' + H.border,
              }}>
                <div style={{ fontSize: 22 }}>{p.i}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{p.t}</div>
                  <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 1 }}>{p.d}</div>
                </div>
                <div style={{
                  width: 22, height: 22, borderRadius: 999,
                  background: H.success, display: 'grid', placeItems: 'center',
                }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>
                </div>
              </div>
            ))}
          </HSettingsGroup>
        </div>
      </div>

      <HPrimaryButton onClick={() => onNavigate('permissions-notifications')}>Allow Apple Health</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="ghost" onClick={() => onNavigate('permissions-notifications')}>Skip — connect later</HPrimaryButton>
    </div>
  );
}

function PermissionsNotificationsScreen({ onNavigate, onBack }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <HTopBar onBack={onBack} title="" />
      <div style={{ flex: 1, paddingTop: 12, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', gap: 18 }}>
        <div style={{
          width: 96, height: 96, borderRadius: 28,
          background: 'var(--quartz-100)',
          display: 'grid', placeItems: 'center',
        }}>
          <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke={H.orange} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>
        </div>
        <div>
          <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1.2, color: H.fg3, textTransform: 'uppercase' }}>Step 2 of 2</div>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, marginTop: 8, lineHeight: 1.15 }}>
            Get gentle reminders
          </div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 8, lineHeight: 1.5, maxWidth: 280, marginLeft: 'auto', marginRight: 'auto' }}>
            One short check-in a day. We don't do streak guilt or marketing pings.
          </div>
        </div>
      </div>
      <HPrimaryButton onClick={() => onNavigate('home')}>Allow notifications</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="ghost" onClick={() => onNavigate('home')}>Not now</HPrimaryButton>
    </div>
  );
}

function PermissionsCalendarScreen({ onNavigate, onBack }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <HTopBar onBack={onBack} title="" />
      <div style={{ flex: 1, paddingTop: 12 }}>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, letterSpacing: -0.4, lineHeight: 1.15 }}>
          Sync your calendar
        </div>
        <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 8, lineHeight: 1.55 }}>
          So Anna can suggest workouts and meditations that fit your day instead of fighting it.
        </div>
        <HCard style={{ marginTop: 24, padding: 16, borderRadius: 18 }}>
          <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1, color: H.fg3, textTransform: 'uppercase', marginBottom: 8 }}>Tomorrow · preview</div>
          {[
            { t: '07:00', n: 'Wake-up window' },
            { t: '09:30', n: 'Anna: 5-min breath reset (open block)' },
            { t: '12:00', n: 'Standup', dim: true },
            { t: '17:00', n: 'Workout slot · zone-2 walk', accent: true },
            { t: '21:30', n: 'Wind-down · meditation' },
          ].map((r, i) => (
            <div key={i} style={{ display: 'flex', gap: 12, padding: '8px 0', borderBottom: i === 4 ? 'none' : '0.5px solid ' + H.border, opacity: r.dim ? 0.5 : 1 }}>
              <div style={{ width: 50, fontFamily: H.body, fontSize: 12, color: H.fg3, fontVariantNumeric: 'tabular-nums' }}>{r.t}</div>
              <div style={{ flex: 1, fontFamily: H.body, fontSize: 13, color: r.accent ? H.orange : H.fg1, fontWeight: r.accent ? 500 : 400 }}>{r.n}</div>
            </div>
          ))}
        </HCard>
      </div>
      <HPrimaryButton onClick={() => onNavigate('home')}>Connect calendar</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="ghost" onClick={() => onNavigate('home')}>Skip</HPrimaryButton>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Error states
// ══════════════════════════════════════════════════════════════════════════

function ErrorOfflineScreen({ onNavigate, onBack }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <HTopBar onBack={onBack} title="" />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', gap: 16 }}>
        <div style={{
          width: 96, height: 96, borderRadius: 999,
          background: 'rgba(3,4,13,0.04)',
          display: 'grid', placeItems: 'center',
        }}>
          <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke={H.fg2} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <line x1="1" y1="1" x2="23" y2="23"/><path d="M16.72 11.06A10.94 10.94 0 0 1 19 12.55"/><path d="M5 12.55a10.94 10.94 0 0 1 5.17-2.39"/><path d="M10.71 5.05A16 16 0 0 1 22.58 9"/><path d="M1.42 9a15.91 15.91 0 0 1 4.7-2.88"/><path d="M8.53 16.11a6 6 0 0 1 6.95 0"/><line x1="12" y1="20" x2="12.01" y2="20"/>
          </svg>
        </div>
        <div>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, letterSpacing: -0.3 }}>You're offline</div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 8, lineHeight: 1.5, maxWidth: 280 }}>
            Your data is saved locally. We'll sync as soon as you're back on a network.
          </div>
        </div>
        <HPrimaryButton type="outline" style={{ width: 'auto', padding: '10px 22px' }} onClick={onBack}>Try again</HPrimaryButton>
      </div>
    </div>
  );
}

function ErrorSyncConflictScreen({ onNavigate, onBack }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <HTopBar onBack={onBack} title="Sync conflict" />
      <div style={{ flex: 1 }}>
        <HCard style={{ padding: 16, borderRadius: 18, background: 'var(--warning-50)', border: '1px solid ' + H.warning, marginBottom: 18 }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={H.warning} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
            <div>
              <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 14, color: H.fg1 }}>Two versions of "Sleep" exist</div>
              <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 4, lineHeight: 1.5 }}>
                You edited this on another device while offline. Pick which one to keep.
              </div>
            </div>
          </div>
        </HCard>

        {[
          { who: 'This device', when: '2 min ago', body: '7h 15m, deep sleep marked above target. Note: "felt rested".' },
          { who: 'iPhone (offline)', when: '6h ago', body: '6h 50m, deep sleep on target. Note: "okay night".' },
        ].map((v, i) => (
          <HCard key={i} style={{ padding: 16, borderRadius: 18, marginBottom: 10 }} onClick={() => onBack()}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{v.who}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3 }}>{v.when}</div>
            </div>
            <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 6, lineHeight: 1.5 }}>{v.body}</div>
            <div style={{ marginTop: 12 }}>
              <HPrimaryButton type="outline" style={{ height: 36, padding: '0 16px', fontSize: 13 }} onClick={() => onBack()}>Keep this version</HPrimaryButton>
            </div>
          </HCard>
        ))}

        <div style={{ marginTop: 14 }}>
          <HPrimaryButton type="ghost" onClick={() => onBack()}>Merge both (manual)</HPrimaryButton>
        </div>
      </div>
    </div>
  );
}

function ErrorPaymentDeclinedScreen({ onNavigate, onBack }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 28px', background: H.bg, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <HTopBar onBack={onBack} title="Payment" />
      <div style={{ flex: 1 }}>
        <HCard style={{ padding: 22, textAlign: 'center', borderRadius: 22, marginBottom: 18 }}>
          <div style={{
            width: 72, height: 72, borderRadius: 999, margin: '0 auto',
            background: 'var(--error-50)', display: 'grid', placeItems: 'center',
          }}>
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke={H.danger} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
          </div>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, letterSpacing: -0.3, marginTop: 14 }}>
            Card declined
          </div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 8, lineHeight: 1.5 }}>
            Your bank declined the charge. No money was taken.
          </div>
        </HCard>

        <HCard style={{ padding: 16, borderRadius: 18, marginBottom: 18 }}>
          <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1, color: H.fg3, textTransform: 'uppercase', marginBottom: 8 }}>Common fixes</div>
          {[
            'Check that the card number, expiry, and CVV are correct',
            'Make sure your card supports international charges',
            'Try a different payment method (Apple Pay below)',
            'Contact your bank if the issue persists',
          ].map((t, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, padding: '8px 0', borderBottom: i === 3 ? 'none' : '0.5px solid ' + H.border }}>
              <div style={{ width: 18, height: 18, borderRadius: 999, background: 'rgba(3,4,13,0.04)', color: H.fg2, display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 600, flexShrink: 0 }}>{i+1}</div>
              <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, lineHeight: 1.5 }}>{t}</div>
            </div>
          ))}
        </HCard>
      </div>
      <HPrimaryButton onClick={onBack}>Try a different card</HPrimaryButton>
      <div style={{ height: 8 }}/>
      <HPrimaryButton type="outline" onClick={onBack}> Apple Pay</HPrimaryButton>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Empty / first-time states
// ══════════════════════════════════════════════════════════════════════════

function EmptyHomeScreen({ onNavigate }) {
  // First-time Home: no score yet, prompt to do basics
  return (
    <div className="screen-enter" style={{ padding: '0 20px 140px', display: 'flex', flexDirection: 'column', gap: 16, background: H.bg, minHeight: '100%' }}>
      <div style={{ paddingTop: 20 }}>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, letterSpacing: 0.4 }}>Good morning</div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 32, letterSpacing: -0.6, lineHeight: 1.1, marginTop: 4 }}>Let's set you up</div>
      </div>

      <HCard style={{ padding: 18, display: 'flex', alignItems: 'center', gap: 14, borderRadius: 20 }}>
        <HAnnaAvatar size={44} />
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>Hi, I'm Anna</div>
          <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 2, lineHeight: 1.45 }}>
            We'll build your Health Score as your data comes in. Start with one of these.
          </div>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '4px 4px 4px' }}>Get started</HSectionLabel>

      {[
        { i: HIcons.vitals, t: 'Connect Apple Health', s: 'Pulls in sleep, vitals, activity', cta: 'Connect', color: 'var(--focus-heart-100)', dest: 'permissions-health' },
        { i: HIcons.nutrition, t: 'Upload bloodwork', s: 'Anna will scan and explain', cta: 'Upload', color: 'var(--focus-nutrition-100)', dest: 'blood' },
        { i: HIcons.mind, t: 'Quick check-in', s: '4 short questions to start', cta: 'Begin', color: 'var(--focus-mental-100)', dest: 'survey-intro' },
      ].map((c, i) => (
        <HCard key={i} onClick={() => onNavigate(c.dest)} style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
          <HIconTile color={c.color} alpha={0.16} size={44}>{c.i(c.color)}</HIconTile>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{c.t}</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{c.s}</div>
          </div>
          <div style={{
            padding: '6px 12px', borderRadius: 999, background: H.fg1, color: '#fff',
            fontFamily: H.body, fontSize: 12, fontWeight: 500,
          }}>{c.cta}</div>
        </HCard>
      ))}

      <HCard style={{ padding: 16, borderRadius: 18, marginTop: 4, background: 'var(--quartz-50)' }}>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, lineHeight: 1.5 }}>
          <b style={{ color: H.fg1 }}>Don't worry about doing everything today.</b> Connect one source and Anna will start tracking. Add more whenever you want.
        </div>
      </HCard>
    </div>
  );
}

function EmptyHealthScreen({ onNavigate }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1.2, color: H.fg3, textTransform: 'uppercase', marginBottom: 6 }}>This week</div>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, marginBottom: 16, letterSpacing: -0.4 }}>Your Health</div>

      <HCard style={{ padding: 24, textAlign: 'center', borderRadius: 22 }}>
        <div style={{ width: 140, height: 140, borderRadius: 999, margin: '0 auto', background: 'rgba(3,4,13,0.04)', display: 'grid', placeItems: 'center', position: 'relative' }}>
          <div style={{ width: 116, height: 116, borderRadius: 999, background: '#fff', border: '2px dashed ' + H.border, display: 'grid', placeItems: 'center' }}>
            <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg3, padding: '0 16px', textAlign: 'center', lineHeight: 1.4 }}>
              Score appears after 3 days of data
            </div>
          </div>
        </div>
        <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 16, marginTop: 18 }}>Building your baseline</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 6, lineHeight: 1.5 }}>
          Connect a data source and your Health Score will start computing.
        </div>
        <div style={{ marginTop: 16 }}>
          <HPrimaryButton onClick={() => onNavigate('permissions-health')}>Connect Apple Health</HPrimaryButton>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>What we'll track</HSectionLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {[
          'Resting HR', 'Sleep duration', 'Steps', 'Workouts',
          'Heart rate variability', 'Body weight', 'Mood', 'Bloodwork',
        ].map(d => (
          <HCard key={d} style={{ padding: 14, opacity: 0.7 }}>
            <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>{d}</div>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, marginTop: 4, color: H.fg3 }}>—</div>
          </HCard>
        ))}
      </div>
    </div>
  );
}

function EmptyNutritionScreen({ onNavigate }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, letterSpacing: -0.4, marginBottom: 18 }}>Nutrition</div>

      <HCard style={{ padding: 22, textAlign: 'center', borderRadius: 22 }}>
        <div style={{ width: 84, height: 84, borderRadius: 999, margin: '0 auto', background: 'var(--focus-nutrition-50)', display: 'grid', placeItems: 'center' }}>
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--focus-nutrition-100)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M11 21H7a4 4 0 0 1-4-4V8a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4v3"/><path d="M16 21l3-3 3 3"/><path d="M19 18v6"/><circle cx="12" cy="12" r="3"/></svg>
        </div>
        <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, marginTop: 14 }}>Plan your first meals</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 6, lineHeight: 1.55, padding: '0 8px' }}>
          Anna will use your dietary preferences and goals to build a 7-day plan tuned to your week.
        </div>
        <div style={{ marginTop: 16 }}>
          <HPrimaryButton onClick={() => onNavigate('mealplan')}>Generate meal plan</HPrimaryButton>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>Quick log</HSectionLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
        {[
          { e: '🍎', t: 'Breakfast' },
          { e: '🥗', t: 'Lunch' },
          { e: '🍲', t: 'Dinner' },
        ].map(c => (
          <HCard key={c.t} onClick={() => onNavigate('chat', { topic: 'nutrition' })} style={{ padding: 12, textAlign: 'center' }}>
            <div style={{ fontSize: 26, marginBottom: 4 }}>{c.e}</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2 }}>{c.t}</div>
          </HCard>
        ))}
      </div>
    </div>
  );
}

function EmptyFitnessScreen({ onNavigate }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, letterSpacing: -0.4, marginBottom: 18 }}>Fitness</div>

      <HCard style={{ padding: 22, textAlign: 'center', borderRadius: 22 }}>
        <div style={{ width: 84, height: 84, borderRadius: 999, margin: '0 auto', background: 'var(--focus-fitness-50)', display: 'grid', placeItems: 'center' }}>
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--focus-fitness-100)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M6.5 6.5h11v11h-11z"/><path d="M3 9.5h3.5v5H3z"/><path d="M17.5 9.5H21v5h-3.5z"/></svg>
        </div>
        <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, marginTop: 14 }}>Build your first workout</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 6, lineHeight: 1.55, padding: '0 8px' }}>
          Tell Anna what equipment you have and how much time you've got. She'll design something that fits.
        </div>
        <div style={{ marginTop: 16 }}>
          <HPrimaryButton onClick={() => onNavigate('workout')}>Generate workout</HPrimaryButton>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>Try a starter</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { t: '20-min mobility flow', s: 'No equipment · beginner', e: '🧘' },
          { t: 'Zone-2 walk',          s: '30 min · easy pace',     e: '🚶' },
          { t: '15-min strength',      s: 'Bodyweight · full body', e: '💪' },
        ].map(w => (
          <HCard key={w.t} onClick={() => onNavigate('workout')} style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--focus-fitness-50)', display: 'grid', placeItems: 'center', fontSize: 22 }}>{w.e}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{w.t}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{w.s}</div>
            </div>
            <HChevron />
          </HCard>
        ))}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Export to window
// ══════════════════════════════════════════════════════════════════════════

Object.assign(window, {
  AuthSplashScreen, AuthSignInScreen, AuthRegisterScreen, AuthResetScreen,
  AuthVerifyScreen, AuthMFAScreen,
  OnboardingScreen,
  SurveyIntroScreen, SurveyScreen, SurveyResultsScreen,
  PermissionsHealthScreen, PermissionsNotificationsScreen, PermissionsCalendarScreen,
  ErrorOfflineScreen, ErrorSyncConflictScreen, ErrorPaymentDeclinedScreen,
  EmptyHomeScreen, EmptyHealthScreen, EmptyNutritionScreen, EmptyFitnessScreen,
});
