// Healify V2 — Missing screens to round out the prototype.
// Survey, Auth completion, Settings deep stack, Empty/Error/Permission states, Tool sub-flows.

// ============================================================================
// SURVEY (PHQ-9 / GAD-7)
// ============================================================================
function SurveyIntroScreen({ onNavigate, onBack }) {
  return (
    <HScreen label="Survey intro">
      <HTopBar title="" onBack={onBack}/>
      <div style={{ padding: '0 4px 24px' }}>
        <div className="h-label">Mental-health check-in</div>
        <div className="h-display" style={{ fontSize: 30, marginTop: 6 }}>How have you been?</div>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 12, lineHeight: 1.5 }}>
          A 5-minute, validated screening (PHQ-9 + GAD-7). Helps Anna understand the last two weeks. Your answers stay private.
        </div>
      </div>
      <HCard pad="16px" radius={20} style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', gap: 12 }}>
          <div style={{ width: 38, height: 38, borderRadius: 12, background: 'var(--t-cream)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Glyph name="clock" size={18}/>
          </div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>About 5 minutes</div>
            <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>16 questions · skip any</div>
          </div>
        </div>
      </HCard>
      <HCard pad="16px" radius={20} style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', gap: 12 }}>
          <div style={{ width: 38, height: 38, borderRadius: 12, background: 'var(--t-cream)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Glyph name="lock" size={18}/>
          </div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>Private to you</div>
            <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>Encrypted · never shared</div>
          </div>
        </div>
      </HCard>
      <div style={{ position: 'fixed', bottom: 24, left: 16, right: 16 }}>
        <HPrimaryButton variant="gradient" full size="lg" onClick={() => onNavigate('survey')}>Start check-in</HPrimaryButton>
      </div>
    </HScreen>
  );
}

function SurveyScreen({ onNavigate, onBack }) {
  const questions = [
    'Little interest or pleasure in doing things',
    'Feeling down, depressed, or hopeless',
    'Trouble falling or staying asleep, or sleeping too much',
    'Feeling tired or having little energy',
    'Poor appetite or overeating',
    'Feeling bad about yourself',
    'Trouble concentrating',
    'Moving or speaking slowly, or being fidgety/restless',
    'Thoughts of being better off dead or hurting yourself',
    'Feeling nervous, anxious, or on edge',
    'Not being able to stop or control worrying',
    'Worrying too much about different things',
    'Trouble relaxing',
    'Being so restless it is hard to sit still',
    'Becoming easily annoyed or irritable',
    'Feeling afraid as if something awful might happen',
  ];
  const answers = [
    { v: 0, t: 'Not at all' },
    { v: 1, t: 'Several days' },
    { v: 2, t: 'More than half the days' },
    { v: 3, t: 'Nearly every day' },
  ];
  const [i, setI] = React.useState(0);
  const [picks, setPicks] = React.useState({});
  const q = questions[i];
  const done = Object.keys(picks).length;

  const next = () => {
    if (i === questions.length - 1) {
      // compute scores
      const phq = Array.from({ length: 9 }).reduce((s, _, k) => s + (picks[k] ?? 0), 0);
      const gad = Array.from({ length: 7 }).reduce((s, _, k) => s + (picks[9 + k] ?? 0), 0);
      onNavigate('survey-results', { phq, gad });
    } else setI(i + 1);
  };

  return (
    <HScreen label="Survey">
      <HTopBar title={`${i + 1} / ${questions.length}`} onBack={i > 0 ? () => setI(i - 1) : onBack}/>

      <div style={{ display: 'flex', gap: 3, padding: '0 16px', marginBottom: 24 }}>
        {questions.map((_, k) => (
          <div key={k} style={{ flex: 1, height: 3, borderRadius: 999, background: k <= i ? 'var(--brand-orange-vibey)' : 'var(--t-ink-08)' }}/>
        ))}
      </div>

      <div style={{ padding: '0 4px 24px' }}>
        <div className="h-label">Over the last 2 weeks…</div>
        <div className="h-display" style={{ fontSize: 26, marginTop: 8, lineHeight: 1.25 }}>{q}?</div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {answers.map(a => {
          const active = picks[i] === a.v;
          return (
            <button key={a.v} onClick={() => { setPicks(p => ({ ...p, [i]: a.v })); setTimeout(next, 220); }} style={{
              padding: '18px 18px', borderRadius: 16, textAlign: 'left',
              background: active ? 'var(--t-cream)' : 'var(--t-surface)',
              border: active ? '2px solid var(--brand-orange-vibey)' : '2px solid transparent',
              boxShadow: 'var(--shadow-md)', color: 'var(--t-fg-1)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <span style={{ fontSize: 15, fontWeight: 500 }}>{a.t}</span>
              {active && <div style={{ width: 22, height: 22, borderRadius: 999, background: 'var(--brand-orange-vibey)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Glyph name="check" size={12} stroke={3}/></div>}
            </button>
          );
        })}
      </div>

      <div style={{ marginTop: 18, textAlign: 'center' }}>
        <button onClick={next} style={{ fontSize: 13, color: 'var(--t-fg-3)' }}>Skip this one</button>
      </div>
    </HScreen>
  );
}

function SurveyResultsScreen({ onNavigate, onBack, phq = 0, gad = 0 }) {
  const phqBand = phq <= 4 ? 'Minimal' : phq <= 9 ? 'Mild' : phq <= 14 ? 'Moderate' : 'Severe';
  const gadBand = gad <= 4 ? 'Minimal' : gad <= 9 ? 'Mild' : gad <= 14 ? 'Moderate' : 'Severe';
  const phqColor = phq <= 4 ? 'var(--success)' : phq <= 9 ? 'var(--warning)' : 'var(--error)';
  const gadColor = gad <= 4 ? 'var(--success)' : gad <= 9 ? 'var(--warning)' : 'var(--error)';
  return (
    <HScreen label="Survey results">
      <HTopBar title="" onBack={onBack}/>
      <div style={{ padding: '0 4px 16px' }}>
        <div className="h-label">Check-in results</div>
        <div className="h-display" style={{ fontSize: 28, marginTop: 8 }}>Here's what I see</div>
      </div>

      <HCard pad="18px" radius={22} style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div>
            <div className="h-label">PHQ-9 · Depression</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 600, marginTop: 4 }}>{phq}<span style={{ color: 'var(--t-fg-3)', fontSize: 18 }}> / 27</span></div>
          </div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 999, background: `color-mix(in oklab, ${phqColor} 14%, transparent)`, color: phqColor, fontSize: 12, fontWeight: 600 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: phqColor }}/> {phqBand}
          </div>
        </div>
      </HCard>

      <HCard pad="18px" radius={22} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div>
            <div className="h-label">GAD-7 · Anxiety</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 600, marginTop: 4 }}>{gad}<span style={{ color: 'var(--t-fg-3)', fontSize: 18 }}> / 21</span></div>
          </div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 999, background: `color-mix(in oklab, ${gadColor} 14%, transparent)`, color: gadColor, fontSize: 12, fontWeight: 600 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: gadColor }}/> {gadBand}
          </div>
        </div>
      </HCard>

      <HCard pad="16px" radius={20} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 10 }}>
          <HAnnaAvatar size={32}/>
          <div style={{ flex: 1, fontSize: 14, lineHeight: 1.5 }}>
            Thanks for sharing. These numbers are <strong style={{ fontWeight: 600 }}>part of the picture</strong>, not the whole story. Want to talk about what's been weighing on you?
          </div>
        </div>
      </HCard>

      <div style={{ display: 'flex', gap: 10 }}>
        <HPrimaryButton variant="ghost" full size="md" onClick={() => onNavigate('home')}>Skip</HPrimaryButton>
        <HPrimaryButton variant="gradient" full size="md" icon="voice" onClick={() => onNavigate('chat')}>Talk to Anna</HPrimaryButton>
      </div>
    </HScreen>
  );
}

// ============================================================================
// AUTH — register, reset, verify, mfa
// ============================================================================
function AuthRegisterScreen({ onNavigate, onBack }) {
  return (
    <HScreen label="Register">
      <HTopBar title="" onBack={onBack}/>
      <div style={{ padding: '0 4px 24px' }}>
        <div className="h-display" style={{ fontSize: 32 }}>Create account</div>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 6 }}>2 minutes to set up.</div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 16 }}>
        <SoftInput placeholder="Full name"/>
        <SoftInput placeholder="Email"/>
        <SoftInput placeholder="Password" type="password"/>
      </div>
      <HPrimaryButton variant="gradient" full size="lg" onClick={() => onNavigate('auth-verify', { email: 'you@example.com' })}>Create account</HPrimaryButton>
      <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--t-fg-3)', marginTop: 14 }}>By creating an account you agree to our Terms.</div>
    </HScreen>
  );
}

function AuthResetScreen({ onNavigate, onBack }) {
  return (
    <HScreen label="Reset">
      <HTopBar title="" onBack={onBack}/>
      <div style={{ padding: '0 4px 24px' }}>
        <div className="h-display" style={{ fontSize: 30 }}>Reset password</div>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 6 }}>Enter your email and we'll send a reset link.</div>
      </div>
      <SoftInput placeholder="Email"/>
      <div style={{ height: 14 }}/>
      <HPrimaryButton variant="gradient" full size="lg" onClick={() => onNavigate('auth-signin')}>Send link</HPrimaryButton>
    </HScreen>
  );
}

function AuthVerifyScreen({ onNavigate, onBack, email = 'you@healify.ai' }) {
  return (
    <HScreen label="Verify">
      <HTopBar title="" onBack={onBack}/>
      <div style={{ padding: '0 4px 24px' }}>
        <div className="h-display" style={{ fontSize: 30 }}>Check your email</div>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 6, lineHeight: 1.5 }}>We sent a 6-digit code to <strong style={{ color: 'var(--t-fg-1)', fontWeight: 600 }}>{email}</strong>.</div>
      </div>
      <CodeInput length={6}/>
      <div style={{ height: 16 }}/>
      <HPrimaryButton variant="gradient" full size="lg" onClick={() => onNavigate('onboarding')}>Verify</HPrimaryButton>
      <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--t-fg-3)', marginTop: 16 }}>
        Didn't receive it? <button style={{ color: 'var(--brand-orange-vibey)', fontWeight: 500 }}>Resend</button>
      </div>
    </HScreen>
  );
}

function AuthMFAScreen({ onNavigate, onBack }) {
  return (
    <HScreen label="MFA">
      <HTopBar title="" onBack={onBack}/>
      <div style={{ padding: '0 4px 24px' }}>
        <div className="h-display" style={{ fontSize: 30 }}>Two-step verification</div>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 6, lineHeight: 1.5 }}>Enter the 6-digit code from your authenticator app.</div>
      </div>
      <CodeInput length={6}/>
      <div style={{ height: 16 }}/>
      <HPrimaryButton variant="gradient" full size="lg" onClick={() => onNavigate('home')}>Continue</HPrimaryButton>
    </HScreen>
  );
}

const SoftInput = ({ placeholder, type = 'text' }) => (
  <input placeholder={placeholder} type={type} style={{
    width: '100%', padding: '14px 16px', borderRadius: 14, border: 'none',
    background: 'var(--t-surface)', boxShadow: 'var(--shadow-md)', fontSize: 15,
    outline: 'none', fontFamily: 'var(--font-body)', color: 'var(--t-fg-1)',
  }}/>
);

const CodeInput = ({ length = 6 }) => (
  <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
    {Array.from({ length }).map((_, i) => (
      <input key={i} maxLength={1} style={{
        width: 44, height: 56, textAlign: 'center', fontFamily: 'var(--font-display)', fontSize: 24,
        borderRadius: 12, border: 'none', background: 'var(--t-surface)', boxShadow: 'var(--shadow-md)',
        outline: 'none', color: 'var(--t-fg-1)',
      }}/>
    ))}
  </div>
);

// ============================================================================
// EMPTY STATES
// ============================================================================
function EmptyState({ icon, title, body, ctaLabel, onCta }) {
  return (
    <HScreen label="Empty state">
      <div style={{ height: 80 }}/>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '0 24px' }}>
        <div style={{ width: 80, height: 80, borderRadius: 24, background: 'var(--t-cream)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
          <Glyph name={icon} size={36} stroke={1.6}/>
        </div>
        <div className="h-display" style={{ fontSize: 26 }}>{title}</div>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 10, lineHeight: 1.55, maxWidth: 280 }}>{body}</div>
        <div style={{ height: 24 }}/>
        <HPrimaryButton variant="gradient" size="lg" onClick={onCta}>{ctaLabel}</HPrimaryButton>
      </div>
    </HScreen>
  );
}

const EmptyHomeScreen = ({ onNavigate }) => <EmptyState icon="sparkle" title="Let's get started" body="Connect Apple Health or upload a bloodwork report — I'll start working." ctaLabel="Connect a source" onCta={() => onNavigate('settings')}/>;
const EmptyHealthScreen = ({ onNavigate }) => <EmptyState icon="pulse" title="No health data yet" body="Sync a wearable or upload a recent panel to see your score." ctaLabel="Connect Apple Health" onCta={() => onNavigate('settings')}/>;
const EmptyNutritionScreen = ({ onNavigate }) => <EmptyState icon="plate" title="Log your first meal" body="Snap a photo, or let me build a 3-day meal plan from your goals." ctaLabel="Generate a plan" onCta={() => onNavigate('mealplan')}/>;
const EmptyFitnessScreen = ({ onNavigate }) => <EmptyState icon="dumbbell" title="No workouts yet" body="Tell me your goal and I'll build today's session." ctaLabel="Build a workout" onCta={() => onNavigate('workout')}/>;

// ============================================================================
// ERROR STATES
// ============================================================================
function ErrorScreen({ icon, title, body, ctaLabel, secondaryLabel, onCta, onSecondary }) {
  return (
    <HScreen label="Error">
      <div style={{ height: 80 }}/>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '0 24px' }}>
        <div style={{ width: 76, height: 76, borderRadius: 999, background: 'color-mix(in oklab, var(--error) 12%, transparent)', color: 'var(--error)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Glyph name={icon} size={36} stroke={1.6}/>
        </div>
        <div className="h-display" style={{ fontSize: 24, marginTop: 18 }}>{title}</div>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 8, lineHeight: 1.55, maxWidth: 280 }}>{body}</div>
        <div style={{ height: 24 }}/>
        <HPrimaryButton variant="gradient" size="lg" onClick={onCta}>{ctaLabel}</HPrimaryButton>
        {secondaryLabel && <div style={{ height: 10 }}/>}
        {secondaryLabel && <HPrimaryButton variant="ghost" size="md" onClick={onSecondary}>{secondaryLabel}</HPrimaryButton>}
      </div>
    </HScreen>
  );
}

const ErrorOfflineScreen = ({ onNavigate }) => <ErrorScreen icon="refresh" title="You're offline" body="Anna needs an internet connection. We saved your last session." ctaLabel="Try again" onCta={() => onNavigate('home')}/>;
const ErrorSyncConflictScreen = ({ onNavigate }) => <ErrorScreen icon="refresh" title="Sync conflict" body="Two devices wrote different data. Pick which to keep." ctaLabel="Keep this device" secondaryLabel="Keep cloud" onCta={() => onNavigate('home')} onSecondary={() => onNavigate('home')}/>;
const ErrorPaymentDeclinedScreen = ({ onNavigate }) => <ErrorScreen icon="lock" title="Payment declined" body="Your card was declined. Update payment to keep Plus." ctaLabel="Update payment" onCta={() => onNavigate('paywall')}/>;

// ============================================================================
// PERMISSIONS
// ============================================================================
function PermissionScreen({ icon, title, body, ctaLabel, onAllow, onSkip }) {
  return (
    <HScreen label="Permissions">
      <div style={{ height: 80 }}/>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '0 24px' }}>
        <div style={{ width: 80, height: 80, borderRadius: 24, background: 'var(--t-cream)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Glyph name={icon} size={36} stroke={1.6}/>
        </div>
        <div className="h-display" style={{ fontSize: 24, marginTop: 18 }}>{title}</div>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 8, lineHeight: 1.55, maxWidth: 300 }}>{body}</div>
      </div>
      <div style={{ position: 'fixed', bottom: 24, left: 16, right: 16 }}>
        <HPrimaryButton variant="gradient" full size="lg" onClick={onAllow}>{ctaLabel}</HPrimaryButton>
        <div style={{ height: 10 }}/>
        <HPrimaryButton variant="ghost" full size="md" onClick={onSkip}>Maybe later</HPrimaryButton>
      </div>
    </HScreen>
  );
}

const PermissionsHealthScreen = ({ onNavigate }) => <PermissionScreen icon="heart" title="Connect Apple Health" body="Anna reads heart rate, steps, sleep and workouts. She never writes back without asking." ctaLabel="Allow Apple Health" onAllow={() => onNavigate('permissions-notifications')} onSkip={() => onNavigate('permissions-notifications')}/>;
const PermissionsNotificationsScreen = ({ onNavigate }) => <PermissionScreen icon="bell" title="Stay in touch" body="Reminders for your habits, your morning briefing, and gentle nudges only when they matter." ctaLabel="Allow notifications" onAllow={() => onNavigate('home')} onSkip={() => onNavigate('home')}/>;
const PermissionsCalendarScreen = ({ onNavigate }) => <PermissionScreen icon="calendar" title="Read your calendar" body="So Anna can plan workouts around your meetings (and protect your wind-down)." ctaLabel="Allow calendar" onAllow={() => onNavigate('home')} onSkip={() => onNavigate('home')}/>;

// ============================================================================
// SETTINGS DEEP STACK
// ============================================================================
function SimpleSettingsScreen({ title, onBack, rows, label }) {
  return (
    <HScreen label={label || title}>
      <HTopBar title={title} onBack={onBack}/>
      <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
        {rows.map((r, i) => (
          <HSettingsRow key={i} {...r}/>
        ))}
      </HCard>
    </HScreen>
  );
}

const AccountScreen = ({ onBack }) => <SimpleSettingsScreen title="Account" onBack={onBack} rows={[
  { icon: 'user', title: 'Full name', value: (window.HEALIFY_USER && window.HEALIFY_USER.full) || 'Kathryn Williams' },
  { icon: 'user', title: 'Email', value: (window.HEALIFY_USER && window.HEALIFY_USER.email) || 'kathryn@healify.ai' },
  { icon: 'calendar', title: 'Date of birth', value: 'Mar 14, 1978' },
  { icon: 'lock', title: 'Change password' },
  { icon: 'trash', title: 'Delete account', danger: true },
]}/>;

const IntegrationsScreen = ({ onBack }) => <SimpleSettingsScreen title="Integrations" onBack={onBack} rows={[
  { icon: 'heart', title: 'Apple Health', sub: 'Steps, sleep, heart, workouts · Oura, Whoop, Garmin, Fitbit sync through Apple Health', value: 'Connected', toggle: { on: true } },
  { icon: 'scan',  title: '23andMe',      sub: 'DNA traits',  value: 'Connected', toggle: { on: true } },
  { icon: 'droplet', title: 'AncestryDNA',sub: 'Raw DNA file',value: 'Off',       toggle: { on: false } },
]}/>;

const UnitsScreen = ({ onBack }) => <SimpleSettingsScreen title="Units" onBack={onBack} rows={[
  { icon: 'data', title: 'System', value: 'Imperial' },
  { icon: 'data', title: 'Weight', value: 'lbs' },
  { icon: 'data', title: 'Height', value: 'ft / in' },
  { icon: 'data', title: 'Temperature', value: '°F' },
  { icon: 'data', title: 'Blood glucose', value: 'mg/dL' },
]}/>;

const AppearanceScreen = ({ onBack }) => <SimpleSettingsScreen title="Appearance" onBack={onBack} rows={[
  { icon: 'sparkle', title: 'Theme', value: 'System' },
  { icon: 'data',    title: 'Text size', value: 'Default' },
  { icon: 'data',    title: 'Reduce motion', toggle: { on: false } },
]}/>;

const NotificationPrefsScreen = ({ onBack }) => <SimpleSettingsScreen title="Notifications" label="Notification prefs" onBack={onBack} rows={[
  { icon: 'sparkle', title: 'Morning briefing', value: '7:30 am', toggle: { on: true } },
  { icon: 'bell',    title: 'Habit reminders',  toggle: { on: true } },
  { icon: 'heart',   title: 'BP reads',         toggle: { on: true } },
  { icon: 'flame',   title: 'Workout',          toggle: { on: true } },
  { icon: 'plate',   title: 'Meal logging',     toggle: { on: false } },
  { icon: 'brain',   title: 'Wind-down',        value: '9:00 pm', toggle: { on: true } },
]}/>;

// Billing
function PlansScreen({ onBack, onNavigate }) {
  return (
    <HScreen label="Plans">
      <HTopBar title="Plans" onBack={onBack}/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 16 }}>
        {[
          { k: 'annual',  title: 'Annual',  sub: '2 months free', price: '$89', per: '/yr', badge: 'BEST VALUE' },
          { k: 'monthly', title: 'Monthly', sub: 'Cancel anytime', price: '$12', per: '/mo' },
          { k: 'free',    title: 'Free',    sub: 'Limited Anna', price: '$0',  per: '' },
        ].map(p => (
          <HCard key={p.k} pad="16px" radius={18} onClick={() => onNavigate('payment', { plan: p })}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 15, fontWeight: 500 }}>{p.title}</div>
                <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>{p.sub}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600 }}>{p.price}<span style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>{p.per}</span></div>
                {p.badge && <div style={{ fontSize: 10, color: 'var(--brand-orange-vibey)', fontWeight: 600, letterSpacing: 0.6 }}>{p.badge}</div>}
              </div>
            </div>
          </HCard>
        ))}
      </div>
    </HScreen>
  );
}

function PaymentScreen({ onBack, onNavigate, plan }) {
  return (
    <HScreen label="Payment">
      <HTopBar title="Payment" onBack={onBack}/>
      <HCard pad="16px" radius={18} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>{plan?.title || 'Annual'}</div>
            <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>Renews automatically</div>
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600 }}>{plan?.price || '$89'}</div>
        </div>
      </HCard>
      <HSectionLabel>Payment method</HSectionLabel>
      <HCard pad="0" radius={20} style={{ overflow: 'hidden', marginBottom: 16 }}>
        <HSettingsRow icon="data" title="Apple Pay"/>
        <HSettingsRow icon="data" title="Card · •••• 4242"/>
        <HSettingsRow icon="plus" title="Add new"/>
      </HCard>
      <HPrimaryButton variant="gradient" full size="lg" onClick={() => onNavigate('subscription')}>Subscribe</HPrimaryButton>
    </HScreen>
  );
}

const ManageSubscriptionScreen = ({ onBack }) => <SimpleSettingsScreen title="Subscription" onBack={onBack} rows={[
  { icon: 'sparkle', title: 'Plan', value: 'Life+ Annual' },
  { icon: 'calendar', title: 'Renews', value: 'Jan 14, 2027' },
  { icon: 'data',    title: 'Manage in App Store' },
  { icon: 'trash',   title: 'Cancel subscription', danger: true },
]}/>;

const ReceiptsScreen = ({ onBack, onNavigate }) => (
  <HScreen label="Receipts">
    <HTopBar title="Receipts" onBack={onBack}/>
    <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
      {[
        { d: 'Jan 14, 2026', a: '$89.00' },
        { d: 'Jan 14, 2025', a: '$79.00' },
        { d: 'Jan 14, 2024', a: '$69.00' },
      ].map((r, i) => (
        <button key={i} onClick={() => onNavigate('receipt-detail', { receipt: r })} style={{ width: '100%', display: 'flex', alignItems: 'center', padding: '14px', textAlign: 'left', background: 'transparent', color: 'var(--t-fg-1)', borderBottom: i < 2 ? '1px solid var(--t-border)' : 'none' }}>
          <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{r.d}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 500 }}>{r.a}</div>
          <Glyph name="chevR" size={14} style={{ color: 'var(--t-fg-3)', marginLeft: 10 }}/>
        </button>
      ))}
    </HCard>
  </HScreen>
);

const ReceiptDetailScreen = ({ onBack, receipt }) => (
  <HScreen label="Receipt">
    <HTopBar title="Receipt" onBack={onBack}/>
    <HCard pad="20px" radius={20}>
      <div className="h-label">Healify Life+ · Annual</div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 600, marginTop: 6 }}>{receipt?.a || '$89.00'}</div>
      <div style={{ fontSize: 12, color: 'var(--t-fg-3)', marginTop: 4 }}>Paid {receipt?.d || 'Jan 14, 2026'} · Apple Pay</div>
      <div style={{ height: 16, borderBottom: '1px solid var(--t-border)', margin: '16px 0' }}/>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, color: 'var(--t-fg-2)' }}><span>Subscription</span><span>{receipt?.a || '$89.00'}</span></div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, color: 'var(--t-fg-2)', marginTop: 6 }}><span>Tax</span><span>$0.00</span></div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, fontWeight: 600, marginTop: 12 }}><span>Total</span><span>{receipt?.a || '$89.00'}</span></div>
    </HCard>
  </HScreen>
);

// Help / Legal
function HelpScreen({ onNavigate, onBack }) {
  return (
    <HScreen label="Help">
      <HTopBar title="Help" onBack={onBack}/>
      <HCard pad="0" radius={20} style={{ overflow: 'hidden', marginBottom: 16 }}>
        <HSettingsRow icon="search" title="FAQ" onClick={() => onNavigate('faq')}/>
        <HSettingsRow icon="bell" title="Contact us" onClick={() => onNavigate('contact')}/>
        <HSettingsRow icon="flag" title="Report a problem" onClick={() => onNavigate('report')}/>
        <HSettingsRow icon="data" title="System status" onClick={() => onNavigate('status')}/>
      </HCard>
      <HSectionLabel>Legal</HSectionLabel>
      <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
        <HSettingsRow icon="shield" title="Terms of service" onClick={() => onNavigate('legal-terms')}/>
        <HSettingsRow icon="shield" title="Privacy policy" onClick={() => onNavigate('legal-privacy')}/>
        <HSettingsRow icon="data" title="About Healify" onClick={() => onNavigate('legal-about')}/>
      </HCard>
    </HScreen>
  );
}

function FAQScreen({ onBack }) {
  const items = [
    { q: 'What does Anna actually do?', a: 'Anna reads your wearable, bloodwork and self-reported data — then turns it into a daily plan and helps you act on it.' },
    { q: 'Is this medical advice?', a: 'No. Healify is a wellness coach. For diagnosis or treatment, please see a clinician.' },
    { q: 'Where is my data stored?', a: 'Encrypted at rest on our servers (AWS, region of your choice). Anna only sees what you authorize.' },
    { q: 'How do I cancel?', a: 'Settings → Subscription → Cancel. Or via the App Store.' },
  ];
  const [open, setOpen] = React.useState(null);
  return (
    <HScreen label="FAQ">
      <HTopBar title="FAQ" onBack={onBack}/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map((it, i) => (
          <HCard key={i} pad="14px" radius={16} onClick={() => setOpen(open === i ? null : i)}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
              <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.1px' }}>{it.q}</div>
              <Glyph name={open === i ? 'chevU' : 'chevD'} size={14} style={{ color: 'var(--t-fg-3)' }}/>
            </div>
            {open === i && <div style={{ marginTop: 8, fontSize: 13, color: 'var(--t-fg-2)', lineHeight: 1.5 }}>{it.a}</div>}
          </HCard>
        ))}
      </div>
    </HScreen>
  );
}

function ContactScreen({ onBack }) {
  return (
    <HScreen label="Contact">
      <HTopBar title="Contact" onBack={onBack}/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 16 }}>
        <SoftInput placeholder="Subject"/>
        <textarea placeholder="What's on your mind?" style={{ width: '100%', minHeight: 140, padding: 14, borderRadius: 14, border: 'none', background: 'var(--t-surface)', boxShadow: 'var(--shadow-md)', fontSize: 14, fontFamily: 'var(--font-body)', color: 'var(--t-fg-1)', outline: 'none', resize: 'none' }}/>
      </div>
      <HPrimaryButton variant="gradient" full size="lg" icon="send">Send message</HPrimaryButton>
    </HScreen>
  );
}

const ReportProblemScreen = ContactScreen; // same form

function StatusScreen({ onBack }) {
  const services = [
    { name: 'Anna chat',      status: 'ok' },
    { name: 'Voice service',  status: 'ok' },
    { name: 'Bloodwork OCR',  status: 'warn' },
    { name: 'Sync · Apple',   status: 'ok' },
    { name: 'Email delivery', status: 'ok' },
  ];
  return (
    <HScreen label="Status">
      <HTopBar title="Status" onBack={onBack}/>
      <HCard pad="16px" radius={20} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--warning)' }}/>
          <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>Partial outage</div>
          <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>Updated 4 min ago</div>
        </div>
      </HCard>
      <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
        {services.map((s, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px', borderBottom: i < services.length - 1 ? '1px solid var(--t-border)' : 'none' }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: s.status === 'ok' ? 'var(--success)' : s.status === 'warn' ? 'var(--warning)' : 'var(--error)' }}/>
            <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{s.name}</div>
            <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>{s.status === 'ok' ? 'Operational' : s.status === 'warn' ? 'Degraded' : 'Down'}</div>
          </div>
        ))}
      </HCard>
    </HScreen>
  );
}

function LegalScreen({ onBack, kind = 'terms' }) {
  const title = kind === 'terms' ? 'Terms of service' : kind === 'privacy' ? 'Privacy policy' : 'About Healify';
  return (
    <HScreen label={`Legal · ${kind}`}>
      <HTopBar title={title} onBack={onBack}/>
      <HCard pad="20px" radius={20} style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--t-fg-2)' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, color: 'var(--t-fg-1)', marginBottom: 8 }}>{title}</div>
        Updated May 2026. Healify is a wellness companion, not a medical device. Always consult a clinician for diagnosis or treatment. We use end-to-end encryption for your health data and never share it with advertisers. Anna sees only what you connect.
        <div style={{ height: 12 }}/>
        Read the full {title.toLowerCase()} on our website. Tap on any section above for details.
      </HCard>
    </HScreen>
  );
}

Object.assign(window, {
  SurveyIntroScreen, SurveyScreen, SurveyResultsScreen,
  AuthRegisterScreen, AuthResetScreen, AuthVerifyScreen, AuthMFAScreen,
  EmptyHomeScreen, EmptyHealthScreen, EmptyNutritionScreen, EmptyFitnessScreen,
  ErrorOfflineScreen, ErrorSyncConflictScreen, ErrorPaymentDeclinedScreen,
  PermissionsHealthScreen, PermissionsNotificationsScreen, PermissionsCalendarScreen,
  AccountScreen, IntegrationsScreen, UnitsScreen, AppearanceScreen, NotificationPrefsScreen,
  PlansScreen, PaymentScreen, ManageSubscriptionScreen, ReceiptsScreen, ReceiptDetailScreen,
  HelpScreen, FAQScreen, ContactScreen, ReportProblemScreen, StatusScreen, LegalScreen,
});
