// Healify — Account / Settings deep stack, Billing, Help, Legal.
// All screens push onto the router and use the standard HTopBar back affordance.

const { useState: useStateA, useEffect: useEffectA } = React;

// ══════════════════════════════════════════════════════════════════════════
// SETTINGS SUB-STACK
// account · privacy · integrations · units · appearance · sign-out
// ══════════════════════════════════════════════════════════════════════════

function AccountScreen({ onNavigate, onBack }) {
  const [name, setName] = useStateA('Kathryn Murphy');
  const [email, setEmail] = useStateA('kathryn@example.com');
  const [phone, setPhone] = useStateA('+1 (415) 555-0142');
  const [dob, setDob] = useStateA('1992-04-18');
  const [edit, setEdit] = useStateA(null); // 'name' | 'email' | 'phone' | 'dob'
  const [confirm, setConfirm] = useStateA(null); // 'signout' | 'delete'
  const [toast, setToast] = useStateA(null);
  const dobLabel = (() => { try { return new Date(dob).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); } catch { return dob; } })();
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Account" />

      <HCard style={{ padding: 18, borderRadius: 22, display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
        <div style={{ width: 64, height: 64, borderRadius: 999, background: H.gradOrange, display: 'grid', placeItems: 'center', color: '#fff', fontFamily: H.display, fontWeight: 600, fontSize: 22 }}>{(name[0] || 'K').toUpperCase()}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 17 }}>{name}</div>
          <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 2 }}>{email}</div>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Profile</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Full name" detail={name} onClick={() => setEdit('name')} />
        <HSettingsRow title="Email" detail={email} onClick={() => setEdit('email')} />
        <HSettingsRow title="Phone" detail={phone} onClick={() => setEdit('phone')} />
        <HSettingsRow title="Date of birth" detail={dobLabel} onClick={() => setEdit('dob')} isLast />
      </HSettingsGroup>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Security</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Change password" onClick={() => onNavigate('auth-reset')} />
        <HSettingsRow title="Two-factor auth" detail="On · Authenticator" onClick={() => onNavigate('auth-mfa')} />
        <HSettingsRow title="Active sessions" detail="2 devices" onClick={() => {}} isLast />
      </HSettingsGroup>

      <div style={{ marginTop: 24 }}>
        <HPrimaryButton type="outline" onClick={() => setConfirm('signout')}>Sign out</HPrimaryButton>
      </div>
      <div style={{ marginTop: 10 }}>
        <button onClick={() => setConfirm('delete')} style={{ width: '100%', padding: '14px 20px', borderRadius: 999, background: 'transparent', border: 0, color: H.danger, fontFamily: H.body, fontWeight: 500, fontSize: 14, cursor: 'pointer' }}>Delete account</button>
      </div>

      {edit === 'name'  && <HEditFieldSheet title="Edit name"  label="Full name"     value={name}  placeholder="Your full name" onSave={(v) => { setName(v.trim() || name); setEdit(null); setToast({ msg: 'Name updated' }); }} onClose={() => setEdit(null)} />}
      {edit === 'email' && <HEditFieldSheet title="Edit email" label="Email address" value={email} type="email" placeholder="you@example.com" hint="We'll send a verification link to confirm the change." onSave={(v) => { setEmail(v.trim() || email); setEdit(null); setToast({ msg: 'Verification email sent' }); }} onClose={() => setEdit(null)} />}
      {edit === 'phone' && <HEditFieldSheet title="Edit phone" label="Phone number"  value={phone} type="tel"   placeholder="+1 (415) 555-0100" onSave={(v) => { setPhone(v.trim() || phone); setEdit(null); setToast({ msg: 'Phone updated' }); }} onClose={() => setEdit(null)} />}
      {edit === 'dob'   && <HDateSheet      title="Date of birth" value={dob} onSave={(v) => { setDob(v || dob); setEdit(null); setToast({ msg: 'Date of birth updated' }); }} onClose={() => setEdit(null)} />}

      {confirm === 'signout' && (
        <HConfirmSheet
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5"/><path d="M21 12H9"/></svg>}
          title="Sign out?"
          body="You'll need to sign in again to see your data. Your account stays intact."
          primary="Sign out"
          onConfirm={() => { setConfirm(null); onNavigate('auth-splash'); }}
          onClose={() => setConfirm(null)}
        />
      )}
      {confirm === 'delete' && (
        <HConfirmSheet
          destructive
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.danger} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>}
          title="Delete account?"
          body="This permanently erases your chats, health data, and subscription. We can't recover anything after 30 days."
          primary="Delete forever"
          onConfirm={() => { setConfirm(null); onNavigate('auth-splash'); }}
          onClose={() => setConfirm(null)}
        />
      )}
      {toast && <HToast msg={toast.msg} onDone={() => setToast(null)} />}
    </div>
  );
}

function PrivacyScreen({ onNavigate, onBack }) {
  const [analytics, setAnalytics] = useStateA(true);
  const [shareAnon, setShareAnon] = useStateA(false);
  const [crash, setCrash] = useStateA(true);
  const [confirm, setConfirm] = useStateA(null); // 'export' | 'wipe-chats' | 'clear-cache'
  const [cacheSize, setCacheSize] = useStateA('124 MB');
  const [toast, setToast] = useStateA(null);
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Privacy" />

      <HCard style={{ padding: 16, borderRadius: 18, marginBottom: 18 }}>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, lineHeight: 1.5 }}>
          Your health data is end-to-end encrypted and stays on-device by default. Anna only sees what you share in chat.
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Data sharing</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Product analytics" toggle toggleOn={analytics} onClick={() => setAnalytics(v => !v)} />
        <HSettingsRow title="Anonymized research" toggle toggleOn={shareAnon} onClick={() => setShareAnon(v => !v)} />
        <HSettingsRow title="Crash reports" toggle toggleOn={crash} onClick={() => setCrash(v => !v)} isLast />
      </HSettingsGroup>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Your data</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Download my data" onClick={() => setConfirm('export')} />
        <HSettingsRow title="Delete chat history" destructive onClick={() => setConfirm('wipe-chats')} />
        <HSettingsRow title="Clear cached files" detail={cacheSize} onClick={() => setConfirm('clear-cache')} isLast />
      </HSettingsGroup>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Policy</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Privacy policy" onClick={() => onNavigate('legal-privacy')} />
        <HSettingsRow title="Terms of service" onClick={() => onNavigate('legal-terms')} isLast />
      </HSettingsGroup>

      {confirm === 'export' && (
        <HConfirmSheet
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5"/><path d="M12 15V3"/></svg>}
          title="Export your data?"
          body="We'll bundle your chats, vitals, blood reports, and surveys into an encrypted .zip and email it to kathryn@example.com."
          primary="Send export"
          onConfirm={() => { setConfirm(null); setToast({ msg: 'Export queued · ready in ~10 min' }); }}
          onClose={() => setConfirm(null)}
        />
      )}
      {confirm === 'wipe-chats' && (
        <HConfirmSheet
          destructive
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.danger} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>}
          title="Delete chat history?"
          body="Every conversation with Anna will be permanently removed. She'll start with a clean slate."
          primary="Delete chats"
          onConfirm={() => { setConfirm(null); setToast({ msg: 'Chat history cleared' }); }}
          onClose={() => setConfirm(null)}
        />
      )}
      {confirm === 'clear-cache' && (
        <HConfirmSheet
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a9 9 0 1 1-9-9"/><path d="M21 3v6h-6"/></svg>}
          title={'Clear ' + cacheSize + ' of cached files?'}
          body="Anna will need to re-download avatars and audio next time you open them."
          primary="Clear cache"
          onConfirm={() => { setConfirm(null); setCacheSize('0 MB'); setToast({ msg: 'Cache cleared' }); }}
          onClose={() => setConfirm(null)}
        />
      )}
      {toast && <HToast msg={toast.msg} onDone={() => setToast(null)} />}
    </div>
  );
}

function IntegrationsScreen({ onNavigate, onBack }) {
  const [items, setItems] = useStateA([
    { k: 'apple',  name: 'Apple Health',     sub: 'Synced 4m ago',  on: true,  icon: '\u2728', bg: '#0A0911', fg: '#fff', perms: ['Steps, distance, active energy', 'Heart rate & HRV', 'Sleep stages from your watch', 'Blood pressure, glucose & SpO₂'] },
    { k: 'oura',   name: 'Oura ring',         sub: 'Synced 14m ago', on: true,  icon: '\u25EF', bg: '#1F1B18', fg: '#fff', perms: ['Sleep score & stages', 'Readiness score', 'Resting heart rate & HRV', 'Body temperature'] },
    { k: 'whoop',  name: 'Whoop',             sub: 'Not connected',   on: false, icon: 'W', bg: '#000', fg: '#fff', perms: ['Recovery & strain', 'Sleep performance', 'Heart rate', 'Workouts'] },
    { k: 'garmin', name: 'Garmin Connect',    sub: 'Not connected',   on: false, icon: 'G', bg: '#007CC3', fg: '#fff', perms: ['GPS workouts', 'Heart rate', 'VO₂ max', 'Body battery'] },
    { k: 'fitbit', name: 'Fitbit',            sub: 'Not connected',   on: false, icon: 'F', bg: '#00B0B9', fg: '#fff', perms: ['Steps & activity', 'Heart rate', 'Sleep', 'Weight & body composition'] },
    { k: 'google', name: 'Google Fit',        sub: 'Not connected',   on: false, icon: 'G', bg: '#4285F4', fg: '#fff', perms: ['Daily steps', 'Active minutes', 'Heart points', 'Weight'] },
    { k: 'cal',    name: 'Calendar',          sub: 'Connected',       on: true,  icon: '\u25A4', bg: 'var(--quartz-cream-bg)', fg: H.fg1, perms: ['Read upcoming events for context', 'Block focus / workout slots'] },
  ]);
  const [askConnect, setAskConnect] = useStateA(null); // provider key being connected
  const [confirmDisc, setConfirmDisc] = useStateA(null); // provider key being disconnected
  const [toast, setToast] = useStateA(null);

  const tapToggle = (k) => {
    const it = items.find(x => x.k === k);
    if (!it) return;
    if (it.on) setConfirmDisc(k);
    else setAskConnect(k);
  };
  const allow = (k) => {
    setItems(arr => arr.map(x => x.k === k ? { ...x, on: true, sub: 'Just now' } : x));
    setAskConnect(null);
    const name = items.find(x => x.k === k)?.name || '';
    setToast({ msg: name + ' connected' });
  };
  const disconnect = (k) => {
    setItems(arr => arr.map(x => x.k === k ? { ...x, on: false, sub: 'Disconnected' } : x));
    setConfirmDisc(null);
    const name = items.find(x => x.k === k)?.name || '';
    setToast({ msg: name + ' disconnected' });
  };
  const askProvider = askConnect && items.find(x => x.k === askConnect);
  const discProvider = confirmDisc && items.find(x => x.k === confirmDisc);

  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Integrations" />
      <HSectionLabel style={{ margin: '0 4px 10px' }}>Connected services</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map(it => (
          <HCard key={it.k} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, borderRadius: 18 }}>
            <div style={{ width: 40, height: 40, borderRadius: 12, background: it.bg, color: it.fg, display: 'grid', placeItems: 'center', fontFamily: H.body, fontWeight: 600, fontSize: 16 }}>{it.icon}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{it.name}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{it.sub}</div>
            </div>
            <div onClick={() => tapToggle(it.k)} style={{
              width: 44, height: 26, borderRadius: 999, padding: 2,
              background: it.on ? H.success : '#E5E7EB',
              transition: 'background 160ms', cursor: 'pointer',
            }}>
              <div style={{ width: 22, height: 22, borderRadius: 999, background: '#fff', boxShadow: '0 1px 2px rgba(0,0,0,0.2)', transform: it.on ? 'translateX(18px)' : 'translateX(0)', transition: 'transform 160ms' }}/>
            </div>
          </HCard>
        ))}
      </div>
      <div style={{ marginTop: 20 }}>
        <HPrimaryButton type="outline" onClick={() => onNavigate('permissions-health')}>Manage Apple Health permissions</HPrimaryButton>
      </div>

      {askProvider && (
        <HPermissionSheet
          provider={askProvider}
          perms={askProvider.perms}
          onAllow={() => allow(askProvider.k)}
          onClose={() => setAskConnect(null)}
        />
      )}
      {discProvider && (
        <HConfirmSheet
          destructive
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.danger} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M18.84 12.25a4 4 0 0 0-5.66-5.66l-1.41 1.42"/><path d="M5.16 11.75a4 4 0 0 0 5.66 5.66l1.41-1.42"/><path d="M2 2l20 20"/></svg>}
          title={'Disconnect ' + discProvider.name + '?'}
          body="Anna will stop seeing new data from this device. Your past data stays in Healify."
          primary="Disconnect"
          onConfirm={() => disconnect(discProvider.k)}
          onClose={() => setConfirmDisc(null)}
        />
      )}
      {toast && <HToast msg={toast.msg} onDone={() => setToast(null)} />}
    </div>
  );
}

function UnitsScreen({ onNavigate, onBack }) {
  const [system, setSystem] = useStateA('imperial');
  const [temp, setTemp] = useStateA('f');
  const [glucose, setGlucose] = useStateA('mgdl');
  const [first, setFirst] = useStateA('mon');
  const Pick = ({ value, set, options }) => (
    <div style={{ display: 'flex', gap: 6 }}>
      {options.map(o => (
        <div key={o.k} onClick={() => set(o.k)} style={{
          padding: '8px 14px', borderRadius: 999, cursor: 'pointer',
          background: value === o.k ? H.black : '#fff', color: value === o.k ? '#fff' : H.fg1,
          fontFamily: H.body, fontWeight: 500, fontSize: 13,
          boxShadow: value === o.k ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
        }}>{o.label}</div>
      ))}
    </div>
  );
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Units & locale" />

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Measurements</HSectionLabel>
      <HCard style={{ padding: 16, marginBottom: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>Distance & weight</div>
          <Pick value={system} set={setSystem} options={[{ k: 'imperial', label: 'lb / mi' }, { k: 'metric', label: 'kg / km' }]} />
        </div>
      </HCard>
      <HCard style={{ padding: 16, marginBottom: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>Temperature</div>
          <Pick value={temp} set={setTemp} options={[{ k: 'f', label: '\u00B0F' }, { k: 'c', label: '\u00B0C' }]} />
        </div>
      </HCard>
      <HCard style={{ padding: 16, marginBottom: 22 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>Blood glucose</div>
          <Pick value={glucose} set={setGlucose} options={[{ k: 'mgdl', label: 'mg/dL' }, { k: 'mmol', label: 'mmol/L' }]} />
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Calendar</HSectionLabel>
      <HCard style={{ padding: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>First day of week</div>
          <Pick value={first} set={setFirst} options={[{ k: 'sun', label: 'Sun' }, { k: 'mon', label: 'Mon' }]} />
        </div>
      </HCard>
    </div>
  );
}

function AppearanceScreen({ onNavigate, onBack }) {
  const [mode, setMode] = useStateA(() => localStorage.getItem('healify.theme') || 'system');
  const [text, setText] = useStateA(() => +localStorage.getItem('healify.textsize') || 1);
  const [reduceMotion, setReduceMotion] = useStateA(() => localStorage.getItem('healify.reducemotion') === '1');

  // Apply theme live -- toggles a class on <html> the global CSS picks up.
  useEffectA(() => {
    const html = document.documentElement;
    html.classList.remove('theme-light', 'theme-dark', 'theme-system');
    html.classList.add('theme-' + mode);
    localStorage.setItem('healify.theme', mode);
  }, [mode]);
  useEffectA(() => {
    document.documentElement.style.setProperty('--app-text-scale', String(1 + text * 0.06));
    localStorage.setItem('healify.textsize', String(text));
  }, [text]);
  useEffectA(() => {
    document.documentElement.classList.toggle('reduce-motion', reduceMotion);
    localStorage.setItem('healify.reducemotion', reduceMotion ? '1' : '0');
  }, [reduceMotion]);

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

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Theme</HSectionLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 22 }}>
        {[
          { k: 'light',  label: 'Light',  bg: '#F0F3F5', ink: H.fg1 },
          { k: 'dark',   label: 'Dark',   bg: '#0A0911', ink: '#fff' },
          { k: 'system', label: 'System', bg: 'linear-gradient(120deg, #F0F3F5 50%, #0A0911 50%)', ink: H.fg1 },
        ].map(m => (
          <div key={m.k} onClick={() => setMode(m.k)} style={{
            borderRadius: 18, padding: 12, cursor: 'pointer',
            background: '#fff',
            border: '2px solid ' + (mode === m.k ? H.orange : 'transparent'),
            boxShadow: '0 1px 2px rgba(3,4,13,0.04)',
          }}>
            <div style={{ height: 60, borderRadius: 12, background: m.bg, display: 'grid', placeItems: 'center', marginBottom: 8 }}>
              <div style={{ width: 30, height: 4, borderRadius: 4, background: m.k === 'dark' ? '#fff' : H.fg1, opacity: 0.7 }}/>
            </div>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 13, textAlign: 'center' }}>{m.label}</div>
          </div>
        ))}
      </div>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Text size</HSectionLabel>
      <HCard style={{ padding: 16, marginBottom: 22 }}>
        <div style={{ fontFamily: H.body, fontSize: 11 + (text * 3), letterSpacing: -0.2, marginBottom: 12 }}>The quick brown fox</div>
        <input type="range" min="0" max="3" step="1" value={text} onChange={e => setText(+e.target.value)} style={{ width: '100%', accentColor: H.orange }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: H.body, fontSize: 11, color: H.fg3, marginTop: 4 }}>
          <span>A</span><span>A</span><span>A</span><span>A</span>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Motion</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Reduce motion" toggle toggleOn={reduceMotion} onClick={() => setReduceMotion(v => !v)} isLast />
      </HSettingsGroup>
    </div>
  );
}

function NotificationPrefsScreen({ onNavigate, onBack }) {
  const [prefs, setPrefs] = useStateA({
    nudges: true, summary: true, anomaly: true, sleep: true,
    workout: true, meditate: false, marketing: false,
  });
  const flip = (k) => setPrefs(p => ({ ...p, [k]: !p[k] }));
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Notifications" />
      <HSectionLabel style={{ margin: '0 4px 10px' }}>Anna</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Daily nudges" toggle toggleOn={prefs.nudges} onClick={() => flip('nudges')} />
        <HSettingsRow title="Weekly summary" toggle toggleOn={prefs.summary} onClick={() => flip('summary')} />
        <HSettingsRow title="Anomalies in your data" toggle toggleOn={prefs.anomaly} onClick={() => flip('anomaly')} isLast />
      </HSettingsGroup>
      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Reminders</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Sleep wind-down" detail="10:30 pm" toggle toggleOn={prefs.sleep} onClick={() => flip('sleep')} />
        <HSettingsRow title="Workout" detail="Mon · Wed · Fri 6 pm" toggle toggleOn={prefs.workout} onClick={() => flip('workout')} />
        <HSettingsRow title="Meditation" detail="Disabled" toggle toggleOn={prefs.meditate} onClick={() => flip('meditate')} isLast />
      </HSettingsGroup>
      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Other</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Product updates" toggle toggleOn={prefs.marketing} onClick={() => flip('marketing')} isLast />
      </HSettingsGroup>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// BILLING / SUBSCRIPTION
// plans · payment · manage · receipts
// ══════════════════════════════════════════════════════════════════════════

function PlansScreen({ onNavigate, onBack }) {
  const [picked, setPicked] = useStateA('annual');
  const plans = [
    { k: 'annual', name: 'Annual',    price: '$89.99', sub: '$7.50/mo billed yearly', save: 'Save 37%' },
    { k: 'monthly', name: 'Monthly',  price: '$11.99', sub: 'billed monthly',          save: '' },
    { k: 'lifetime', name: 'Lifetime', price: '$249',  sub: 'one-time payment',         save: 'Best value' },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Choose a plan" />

      <HCard style={{ padding: 18, borderRadius: 22, background: H.gradOrange, color: '#fff', marginBottom: 18, textAlign: 'center' }}>
        <div style={{ width: 48, height: 48, borderRadius: 999, margin: '0 auto', background: 'rgba(255,255,255,0.18)', display: 'grid', placeItems: 'center' }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2 4 7v6c0 5 4 9 8 9s8-4 8-9V7l-8-5z"/></svg>
        </div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, marginTop: 12 }}>Healify Plus</div>
        <div style={{ fontFamily: H.body, fontSize: 13, marginTop: 4, opacity: 0.92 }}>Unlimited Anna chat · all AI tools · personalized coaching</div>
      </HCard>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 22 }}>
        {plans.map(p => (
          <div key={p.k} onClick={() => setPicked(p.k)} style={{
            background: '#fff', borderRadius: 18, padding: 16,
            border: '2px solid ' + (picked === p.k ? H.orange : 'transparent'),
            boxShadow: '0 1px 2px rgba(3,4,13,0.04)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{ width: 22, height: 22, borderRadius: 999, border: '2px solid ' + (picked === p.k ? H.orange : H.border), display: 'grid', placeItems: 'center' }}>
              {picked === p.k && <div style={{ width: 10, height: 10, borderRadius: 999, background: H.orange }}/>}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{p.name}</div>
                {p.save && <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 11, padding: '2px 8px', borderRadius: 999, background: 'var(--success-50)', color: H.success }}>{p.save}</div>}
              </div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{p.sub}</div>
            </div>
            <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 18 }}>{p.price}</div>
          </div>
        ))}
      </div>

      <HPrimaryButton onClick={() => onNavigate('payment', { plan: picked })}>Continue</HPrimaryButton>
      <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, textAlign: 'center', marginTop: 12, lineHeight: 1.5 }}>
        Cancel anytime. By continuing you agree to the{' '}
        <span onClick={() => onNavigate('legal-terms')} style={{ textDecoration: 'underline', cursor: 'pointer' }}>Terms</span> &{' '}
        <span onClick={() => onNavigate('legal-privacy')} style={{ textDecoration: 'underline', cursor: 'pointer' }}>Privacy</span>.
      </div>
    </div>
  );
}

function PaymentScreen({ onNavigate, onBack, plan = 'annual' }) {
  const [method, setMethod] = useStateA('card');
  const [stage, setStage] = useStateA('form'); // form | processing | done
  useEffectA(() => {
    if (stage === 'processing') {
      const t = setTimeout(() => setStage('done'), 1700);
      return () => clearTimeout(t);
    }
  }, [stage]);

  if (stage === 'processing') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => setStage('form')} title="Payment" />
        <HToolLoading title="Processing payment\u2026" sub={plan} hint="Connecting securely" />
      </div>
    );
  }

  if (stage === 'done') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => onNavigate('tab:home')} title="Welcome to Plus" />
        <HCard style={{ padding: 28, textAlign: 'center', borderRadius: 22 }}>
          <div style={{ width: 88, height: 88, borderRadius: 999, margin: '0 auto', background: H.success, display: 'grid', placeItems: 'center' }}>
            <svg width="40" height="40" 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 style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, marginTop: 16 }}>You're in.</div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6, lineHeight: 1.5 }}>Anna just unlocked unlimited chat and every AI tool.</div>
        </HCard>
        <div style={{ marginTop: 20 }}>
          <HPrimaryButton onClick={() => onNavigate('tab:home')}>Get started</HPrimaryButton>
        </div>
      </div>
    );
  }

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

      <HCard style={{ padding: 16, borderRadius: 18, marginBottom: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>Healify Plus · {plan}</div>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 18 }}>{plan === 'annual' ? '$89.99' : plan === 'lifetime' ? '$249' : '$11.99'}</div>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Payment method</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 22 }}>
        {[
          { k: 'card', label: 'Credit / debit card' },
          { k: 'apple', label: 'Apple Pay' },
          { k: 'paypal', label: 'PayPal' },
        ].map(m => (
          <HCard key={m.k} onClick={() => setMethod(m.k)} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, borderRadius: 16, border: '2px solid ' + (method === m.k ? H.orange : 'transparent') }}>
            <div style={{ width: 22, height: 22, borderRadius: 999, border: '2px solid ' + (method === m.k ? H.orange : H.border), display: 'grid', placeItems: 'center' }}>
              {method === m.k && <div style={{ width: 10, height: 10, borderRadius: 999, background: H.orange }}/>}
            </div>
            <div style={{ flex: 1, fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{m.label}</div>
          </HCard>
        ))}
      </div>

      {method === 'card' && (
        <>
          <HSectionLabel style={{ margin: '0 4px 10px' }}>Card details</HSectionLabel>
          <HCard style={{ padding: 0, borderRadius: 16, marginBottom: 22 }}>
            {[
              { label: 'Card number', placeholder: '1234 5678 9012 3456' },
              { label: 'Cardholder name', placeholder: 'Kathryn Murphy' },
            ].map((f, i, arr) => (
              <div key={i} style={{ padding: '14px 16px', borderBottom: i === arr.length - 1 ? 'none' : '0.5px solid ' + H.border }}>
                <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>{f.label}</div>
                <input placeholder={f.placeholder} style={{ width: '100%', border: 0, outline: 'none', fontFamily: H.body, fontSize: 15, marginTop: 4, background: 'transparent' }}/>
              </div>
            ))}
            <div style={{ display: 'flex' }}>
              <div style={{ flex: 1, padding: '14px 16px', borderRight: '0.5px solid ' + H.border }}>
                <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>Expires</div>
                <input placeholder="MM / YY" style={{ width: '100%', border: 0, outline: 'none', fontFamily: H.body, fontSize: 15, marginTop: 4, background: 'transparent' }}/>
              </div>
              <div style={{ flex: 1, padding: '14px 16px' }}>
                <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>CVV</div>
                <input placeholder="123" style={{ width: '100%', border: 0, outline: 'none', fontFamily: H.body, fontSize: 15, marginTop: 4, background: 'transparent' }}/>
              </div>
            </div>
          </HCard>
        </>
      )}

      <HPrimaryButton onClick={() => setStage('processing')}>Pay & subscribe</HPrimaryButton>
      <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, textAlign: 'center', marginTop: 12 }}>
        Secured by Stripe \u00B7 256-bit encryption
      </div>
    </div>
  );
}

function ManageSubscriptionScreen({ onNavigate, onBack }) {
  const [status, setStatus] = useStateA('active'); // active | paused | canceled
  const [confirm, setConfirm] = useStateA(null);   // 'pause' | 'cancel' | 'resume'
  const [toast, setToast] = useStateA(null);

  const heroByStatus = {
    active: {
      bg: H.gradOrange, color: '#fff', tag: 'Active',
      title: 'Healify Plus · Annual',
      sub: 'Renews Mar 12, 2027 · $89.99',
    },
    paused: {
      bg: 'var(--quartz-cream-bg)', color: H.fg1, tag: 'Paused',
      title: 'Healify Plus · Annual',
      sub: 'Resumes Jun 12, 2026',
    },
    canceled: {
      bg: 'var(--quartz-cream-bg)', color: H.fg1, tag: 'Canceled',
      title: 'Healify Plus · Annual',
      sub: 'Access ends Mar 12, 2027',
    },
  };
  const hero = heroByStatus[status];

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

      <HCard style={{ padding: 18, borderRadius: 22, background: hero.bg, color: hero.color, marginBottom: 18 }}>
        <div style={{ fontFamily: H.body, fontSize: 12, letterSpacing: 1, textTransform: 'uppercase', opacity: status === 'active' ? 0.85 : 0.65 }}>{hero.tag}</div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, marginTop: 4 }}>{hero.title}</div>
        <div style={{ fontFamily: H.body, fontSize: 13, marginTop: 6, opacity: status === 'active' ? 0.95 : 0.75 }}>{hero.sub}</div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Plan</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Change plan" onClick={() => onNavigate('plans')} />
        <HSettingsRow title="Receipts" onClick={() => onNavigate('receipts')} isLast />
      </HSettingsGroup>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Payment</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Card on file" detail="Visa \u2022 4242" onClick={() => onNavigate('payment')} />
        <HSettingsRow title="Billing address" detail="San Francisco, CA" onClick={() => {}} isLast />
      </HSettingsGroup>

      {status === 'active' && (
        <>
          <div style={{ marginTop: 24 }}>
            <HPrimaryButton type="outline" onClick={() => setConfirm('pause')}>Pause subscription</HPrimaryButton>
          </div>
          <div style={{ marginTop: 10 }}>
            <button onClick={() => setConfirm('cancel')} style={{ width: '100%', padding: '14px 20px', borderRadius: 999, background: 'transparent', border: 0, color: H.danger, fontFamily: H.body, fontWeight: 500, fontSize: 14, cursor: 'pointer' }}>Cancel subscription</button>
          </div>
        </>
      )}
      {status === 'paused' && (
        <div style={{ marginTop: 24 }}>
          <HPrimaryButton onClick={() => setConfirm('resume')}>Resume subscription</HPrimaryButton>
        </div>
      )}
      {status === 'canceled' && (
        <div style={{ marginTop: 24 }}>
          <HPrimaryButton onClick={() => { setStatus('active'); setToast({ msg: 'Subscription reactivated' }); }}>Reactivate</HPrimaryButton>
        </div>
      )}

      {confirm === 'pause' && (
        <HConfirmSheet
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg>}
          title="Pause for 3 months?"
          body="Billing pauses. You keep full access until Jun 12, then we'll quietly resume."
          primary="Pause"
          onConfirm={() => { setStatus('paused'); setConfirm(null); setToast({ msg: 'Paused until Jun 12' }); }}
          onClose={() => setConfirm(null)}
        />
      )}
      {confirm === 'cancel' && (
        <HConfirmSheet
          destructive
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.danger} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6"/><path d="M9 9l6 6"/></svg>}
          title="Cancel subscription?"
          body="You'll keep Plus until Mar 12, 2027. After that Anna locks unlimited chat and the AI tools."
          primary="Cancel anyway"
          cancel="Keep Plus"
          onConfirm={() => { setStatus('canceled'); setConfirm(null); setToast({ msg: 'Subscription canceled' }); }}
          onClose={() => setConfirm(null)}
        />
      )}
      {confirm === 'resume' && (
        <HConfirmSheet
          icon={<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polygon points="6 4 20 12 6 20 6 4"/></svg>}
          title="Resume now?"
          body="Billing restarts today. We'll prorate the unused pause time as credit."
          primary="Resume"
          onConfirm={() => { setStatus('active'); setConfirm(null); setToast({ msg: 'Welcome back' }); }}
          onClose={() => setConfirm(null)}
        />
      )}
      {toast && <HToast msg={toast.msg} onDone={() => setToast(null)} />}
    </div>
  );
}

function ReceiptsScreen({ onNavigate, onBack }) {
  const items = [
    { d: 'Mar 12, 2026', desc: 'Healify Plus \u00B7 Annual',  amt: '$89.99', s: 'Paid', invoice: 'HLF-2026-031284', period: 'Mar 12, 2026 \u2014 Mar 12, 2027', method: 'Visa \u2022 4242', subtotal: '$89.99', tax: '$0.00', total: '$89.99' },
    { d: 'Mar 12, 2025', desc: 'Healify Plus \u00B7 Annual',  amt: '$89.99', s: 'Paid', invoice: 'HLF-2025-031255', period: 'Mar 12, 2025 \u2014 Mar 12, 2026', method: 'Visa \u2022 4242', subtotal: '$89.99', tax: '$0.00', total: '$89.99' },
    { d: 'Apr 04, 2024', desc: 'Healify Plus \u00B7 Monthly', amt: '$11.99', s: 'Paid', invoice: 'HLF-2024-040402', period: 'Apr 04, 2024 \u2014 May 04, 2024', method: 'Visa \u2022 4242', subtotal: '$11.99', tax: '$0.00', total: '$11.99' },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Receipts" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map((r, i) => (
          <HCard key={i} onClick={() => onNavigate('receipt-detail', { receipt: r })} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 12, background: 'var(--quartz-cream-bg)', display: 'grid', placeItems: 'center' }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z"/><path d="M14 3v6h6"/></svg>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{r.desc}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{r.d} \u00B7 {r.s}</div>
            </div>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{r.amt}</div>
            <HChevron />
          </HCard>
        ))}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// HELP / SUPPORT
// faq · contact · report · status
// ══════════════════════════════════════════════════════════════════════════

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

      <HCard onClick={() => onNavigate('chat', { topic: 'support' })} style={{ padding: 18, borderRadius: 22, background: 'linear-gradient(135deg, var(--brand-ink) 0%, #1A1018 100%)', color: '#fff', marginBottom: 18, display: 'flex', alignItems: 'center', gap: 14 }}>
        <HAnnaAvatar size={48} />
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 16 }}>Ask Anna</div>
          <div style={{ fontFamily: H.body, fontSize: 13, opacity: 0.75, marginTop: 2 }}>Most questions, answered in chat</div>
        </div>
        <HChevron color="rgba(255,255,255,0.6)" />
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Resources</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Frequently asked questions" onClick={() => onNavigate('faq')} />
        <HSettingsRow title="System status" detail="All systems normal" onClick={() => onNavigate('status')} />
        <HSettingsRow title="Contact support" onClick={() => onNavigate('contact')} />
        <HSettingsRow title="Report a problem" onClick={() => onNavigate('report')} isLast />
      </HSettingsGroup>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>About</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="About Healify" onClick={() => onNavigate('legal-about')} />
        <HSettingsRow title="Terms of service" onClick={() => onNavigate('legal-terms')} />
        <HSettingsRow title="Privacy policy" onClick={() => onNavigate('legal-privacy')} isLast />
      </HSettingsGroup>
    </div>
  );
}

function FAQScreen({ onNavigate, onBack }) {
  const [open, setOpen] = useStateA(0);
  const items = [
    { q: 'Is my health data private?', a: 'Yes. Everything is encrypted on-device by default. We never sell your data and you can export or delete it anytime in Privacy.' },
    { q: 'How accurate is Anna?', a: 'Anna is a coach, not a doctor. She combines clinical guidelines with your wearable & survey data to give plain-language guidance. Always consult your physician for medical decisions.' },
    { q: 'What devices does Healify support?', a: 'Apple Health, Oura, Whoop, Garmin, Fitbit, and Google Fit. Connect any of them in Settings \u2192 Integrations.' },
    { q: 'Can I cancel my subscription?', a: 'Anytime, from Settings \u2192 Subscription \u2192 Cancel. Access continues through the end of your billing period.' },
    { q: 'How is the Health Score calculated?', a: 'A weighted blend of sleep, vitals, fitness, and mind metrics, normalized against age- and gender-matched cohorts. Tap your score to see contributing factors.' },
    { q: 'Does Anna replace therapy?', a: "No. Anna can help you track mental wellbeing and surface patterns, but she's not a licensed therapist. We refer out when patterns suggest you'd benefit from one." },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="FAQ" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map((it, i) => (
          <HCard key={i} onClick={() => setOpen(open === i ? -1 : i)} style={{ padding: 16, borderRadius: 18, cursor: 'pointer' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
              <div style={{ flex: 1, fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{it.q}</div>
              <div style={{ fontFamily: H.body, fontSize: 18, color: H.fg2, transform: open === i ? 'rotate(45deg)' : 'none', transition: 'transform 160ms' }}>+</div>
            </div>
            {open === i && (
              <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 8, lineHeight: 1.55 }}>{it.a}</div>
            )}
          </HCard>
        ))}
      </div>
    </div>
  );
}

function ContactScreen({ onNavigate, onBack }) {
  const [topic, setTopic] = useStateA('general');
  const [text, setText] = useStateA('');
  const [sent, setSent] = useStateA(false);
  if (sent) {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={onBack} title="Contact" />
        <HCard style={{ padding: 28, textAlign: 'center', borderRadius: 22 }}>
          <div style={{ width: 88, height: 88, borderRadius: 999, margin: '0 auto', background: H.success, display: 'grid', placeItems: 'center' }}>
            <svg width="40" height="40" 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 style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, marginTop: 16 }}>Message sent</div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6, lineHeight: 1.5 }}>We'll reply within 24h to kathryn@example.com.</div>
        </HCard>
        <div style={{ marginTop: 20 }}>
          <HPrimaryButton onClick={() => onBack()}>Done</HPrimaryButton>
        </div>
      </div>
    );
  }
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Contact support" />

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Topic</HSectionLabel>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
        {[
          { k: 'general',  label: 'General' },
          { k: 'billing',  label: 'Billing' },
          { k: 'data',     label: 'My data' },
          { k: 'feature',  label: 'Feature request' },
        ].map(o => (
          <div key={o.k} onClick={() => setTopic(o.k)} style={{
            padding: '10px 14px', borderRadius: 999, cursor: 'pointer',
            background: topic === o.k ? H.black : '#fff', color: topic === o.k ? '#fff' : H.fg1,
            fontFamily: H.body, fontWeight: 500, fontSize: 13,
            boxShadow: topic === o.k ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
          }}>{o.label}</div>
        ))}
      </div>

      <HCard style={{ padding: 16, marginBottom: 22 }}>
        <textarea value={text} onChange={e => setText(e.target.value)} rows="6" placeholder="Tell us what's going on..."
          style={{ width: '100%', border: 0, outline: 'none', resize: 'none', fontFamily: H.body, fontSize: 14, lineHeight: 1.5, background: 'transparent' }}/>
      </HCard>

      <HPrimaryButton onClick={() => setSent(true)}>Send message</HPrimaryButton>
    </div>
  );
}

function ReportProblemScreen({ onNavigate, onBack }) {
  const [text, setText] = useStateA('');
  const [include, setInclude] = useStateA({ logs: true, screen: true });
  const [sent, setSent] = useStateA(false);
  if (sent) {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={onBack} title="Report a problem" />
        <HCard style={{ padding: 28, textAlign: 'center', borderRadius: 22 }}>
          <div style={{ width: 88, height: 88, borderRadius: 999, margin: '0 auto', background: H.success, display: 'grid', placeItems: 'center' }}>
            <svg width="40" height="40" 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 style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, marginTop: 16 }}>Report sent</div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6, lineHeight: 1.5 }}>Thanks. The team has the diagnostic bundle.</div>
        </HCard>
        <div style={{ marginTop: 20 }}>
          <HPrimaryButton onClick={() => onBack()}>Done</HPrimaryButton>
        </div>
      </div>
    );
  }
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Report a problem" />

      <HCard style={{ padding: 16, marginBottom: 18 }}>
        <textarea value={text} onChange={e => setText(e.target.value)} rows="6" placeholder="What were you doing when it broke?"
          style={{ width: '100%', border: 0, outline: 'none', resize: 'none', fontFamily: H.body, fontSize: 14, lineHeight: 1.5, background: 'transparent' }}/>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Include with report</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Diagnostic logs (last 30 min)" toggle toggleOn={include.logs} onClick={() => setInclude(i => ({ ...i, logs: !i.logs }))} />
        <HSettingsRow title="Screenshot of current screen" toggle toggleOn={include.screen} onClick={() => setInclude(i => ({ ...i, screen: !i.screen }))} isLast />
      </HSettingsGroup>

      <div style={{ marginTop: 22 }}>
        <HPrimaryButton onClick={() => setSent(true)}>Send report</HPrimaryButton>
      </div>
    </div>
  );
}

function StatusScreen({ onNavigate, onBack }) {
  const services = [
    { name: 'Anna chat',         status: 'normal' },
    { name: 'Wearable sync',     status: 'normal' },
    { name: 'Apple Health',      status: 'normal' },
    { name: 'AI tools',          status: 'normal' },
    { name: 'Push notifications', status: 'degraded' },
    { name: 'Account & billing', status: 'normal' },
  ];
  const colorFor = (s) => s === 'normal' ? H.success : s === 'degraded' ? H.warn : H.danger;
  const labelFor = (s) => s === 'normal' ? 'Operational' : s === 'degraded' ? 'Degraded' : 'Outage';
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="System status" />

      <HCard style={{ padding: 18, borderRadius: 22, marginBottom: 18, display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 14, height: 14, borderRadius: 999, background: H.success, boxShadow: '0 0 0 4px rgba(68,197,92,0.18)' }}/>
        <div>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>All systems normal</div>
          <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>Updated just now</div>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Services</HSectionLabel>
      <HCard style={{ padding: 0 }}>
        {services.map((s, i, arr) => (
          <div key={s.name} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: i === arr.length - 1 ? 'none' : '0.5px solid ' + H.border }}>
            <div style={{ width: 8, height: 8, borderRadius: 999, background: colorFor(s.status) }}/>
            <div style={{ flex: 1, fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{s.name}</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: colorFor(s.status) }}>{labelFor(s.status)}</div>
          </div>
        ))}
      </HCard>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// LEGAL — Terms · Privacy · About
// ══════════════════════════════════════════════════════════════════════════

function LegalScreen({ onNavigate, onBack, kind = 'terms' }) {
  const docs = {
    terms: {
      title: 'Terms of service',
      updated: 'Updated Mar 1, 2026',
      sections: [
        { h: '1. Using Healify', p: "By creating an account you agree to use Healify lawfully and only for personal, non-commercial purposes. We may update these terms; if changes are material we'll notify you in-app at least 30 days before they take effect." },
        { h: '2. Anna is a coach, not a doctor', p: "Anna provides general health information and lifestyle guidance based on the data you share. Nothing in Healify is medical advice, diagnosis, or treatment. For medical questions, consult a licensed clinician. Call your local emergency number if you may be in danger." },
        { h: '3. Your account', p: 'You are responsible for keeping your password confidential and for activity on your account. Notify us immediately of any unauthorized use.' },
        { h: '4. Subscriptions', p: 'Plus subscriptions auto-renew until canceled. Cancel anytime in Settings; access continues through the end of the paid period. Refunds are handled per the App Store / Play Store policies in effect at purchase.' },
        { h: '5. Limitation of liability', p: "To the fullest extent permitted by law, Healify is provided as-is. We aren't liable for indirect or consequential damages arising from use of the app, decisions you make based on its outputs, or interruptions in service." },
        { h: '6. Termination', p: "You can delete your account anytime in Privacy \u2192 Delete account. We may suspend accounts that violate these terms or applicable law." },
      ],
    },
    privacy: {
      title: 'Privacy policy',
      updated: 'Updated Mar 1, 2026',
      sections: [
        { h: 'What we collect', p: 'Account info you give us (name, email), health data you sync (wearables, blood reports, surveys), and product usage analytics so we can fix bugs and improve features.' },
        { h: 'How we use it', p: 'To run the service: power Anna\u2019s coaching, sync your wearables, send reminders you opt into, and process payments. We do not sell your data.' },
        { h: 'On-device by default', p: 'Sensitive health data is stored encrypted on your device. Cloud backups are end-to-end encrypted with a key only you control.' },
        { h: 'Sharing', p: 'We share data only with vetted infrastructure providers (hosting, payments, crash reporting). They process data on our behalf under strict contracts and may not use it for their own purposes.' },
        { h: 'Your rights', p: 'You can export your data, delete your chat history, or delete your entire account at any time from Privacy. We respond to deletion requests within 30 days.' },
        { h: 'Contact', p: 'Questions about privacy: privacy@healify.ai' },
      ],
    },
    about: {
      title: 'About Healify',
      updated: 'Version 2.4.1 (build 208)',
      sections: [
        { h: 'Our mission', p: "Healify exists to make health legible. Most people drown in disconnected data points: rings, scales, blood reports, mental-health check-ins. Anna stitches them into a single warm, plain-language thread \u2014 the way a great coach would." },
        { h: 'Built by', p: "Lifecycle Innovations Limited. Designed and engineered by a small remote team across San Francisco, London, Lisbon, and Bangalore. Anna is built on top of state-of-the-art health LLMs with clinical guardrails, audited quarterly by independent reviewers." },
        { h: 'Acknowledgments', p: 'Thanks to the thousands of beta members who helped us tune voice, pacing, and the "validate \u2192 explain \u2192 nudge" pattern.' },
        { h: 'Reach us', p: 'hello@healify.ai \u00B7 healify.ai' },
      ],
    },
  };
  const d = docs[kind] || docs.terms;
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 80px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title={d.title} />
      <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 14 }}>{d.updated}</div>

      <HCard style={{ padding: 20, borderRadius: 22 }}>
        {d.sections.map((s, i, arr) => (
          <div key={i} style={{ paddingBottom: i === arr.length - 1 ? 0 : 16, marginBottom: i === arr.length - 1 ? 0 : 16, borderBottom: i === arr.length - 1 ? 'none' : '0.5px solid ' + H.border }}>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, marginBottom: 6 }}>{s.h}</div>
            <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, lineHeight: 1.6 }}>{s.p}</div>
          </div>
        ))}
      </HCard>

      {kind === 'about' && (
        <div style={{ marginTop: 22, textAlign: 'center', fontFamily: H.body, fontSize: 12, color: H.fg3 }}>
          \u00A9 2026 Lifecycle Innovations Limited
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  AccountScreen, PrivacyScreen, IntegrationsScreen, UnitsScreen, AppearanceScreen, NotificationPrefsScreen,
  PlansScreen, PaymentScreen, ManageSubscriptionScreen, ReceiptsScreen,
  HelpScreen, FAQScreen, ContactScreen, ReportProblemScreen, StatusScreen,
  LegalScreen,
});
