// ui_kits/mobile/Screens.jsx
// Goji mobile screens. Composes atoms from Components.jsx.

const { useState: useStateScreens } = React;

// ─────────────────────────────────────────────────────────────
// Page chrome — scrollable content area with safe-area padding.
// ─────────────────────────────────────────────────────────────
function Page({ children, extraBottom = 0 }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let lastY = 0;
    let ticking = false;
    const fire = (detail) => window.dispatchEvent(new CustomEvent('goji-nav-compact', { detail }));
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        const y = el.scrollTop;
        if (y <= 12) fire(false);
        else if (y > lastY + 6) fire(true);
        else if (y < lastY - 6) fire(false);
        lastY = y;
        ticking = false;
      });
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    // Reset to expanded whenever a Page mounts (e.g. after tab switch).
    fire(false);
    return () => el.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <div ref={ref} style={{
      flex: 1, minHeight: 0,
      overflowY: 'auto',
      paddingBottom: 110 + extraBottom,
      background: 'var(--color-bg)',
    }}>{children}</div>
  );
}

// ─────────────────────────────────────────────────────────────
// HomeScreen — hero + this week + a couple insights
// ─────────────────────────────────────────────────────────────
function HomeScreen({ theme, onToggleTheme, onOpenInsights }) {
  return (
    <Page>
      <Header title="Goji" theme={theme} onToggleTheme={onToggleTheme} />

      <HeroCard amount="84" billsAmount={1247} billsLabel="bills due this week" />

      {/* Quick actions row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, padding: '20px 20px 0' }}>
        <QuickAction icon="send" label="Send" />
        <QuickAction icon="target" label="Set a goal" />
        <QuickAction icon="bill" label="Pay bill" />
      </div>

      <SectionTitle action="View all" onAction={onOpenInsights}>For you</SectionTitle>
      <StackedCards
        cards={[
          { id: 'bill-rent',    priority: 100, tone: 'warn',         eyebrow: 'BILLS \u00b7 DUE IN 3 DAYS',     title: 'Rent',                  body: 'Scheduled for Jan 1',                  amount: -1650, cta: 'Pay early' },
          { id: 'income',       priority: 90,  tone: 'success',      eyebrow: 'INCOME',                          title: 'Salary arrived',        body: 'Acme Inc. \u00b7 today',                amount: 4210 },
          { id: 'insight-grocery', priority: 75, tone: 'insight',    eyebrow: 'INSIGHT',                         title: 'Grocery spend up 18%',  body: 'Mostly at Whole Foods this month',     cta: 'See more' },
          { id: 'overdue-utility', priority: 95, tone: 'danger',     eyebrow: 'OVERDUE',                         title: 'Comcast Internet',      body: 'Was due Jan 8 \u00b7 2 days late',      amount: -79.99, cta: 'Pay now' },
          { id: 'account-wf',   priority: 50,  tone: 'account',      eyebrow: 'WELLS FARGO \u00b7 USD',         title: '$4,218.40',             body: 'Checking \u00b7 +$214 this week',       cta: 'Open' },
          { id: 'fx-npr',       priority: 40,  tone: 'info',         eyebrow: 'FX \u00b7 NPR \u2192 USD',       title: 'Good moment to top up',  body: 'NPR up 1.4% this week',                cta: 'Send' },
          { id: 'learn-rem',    priority: 20,  tone: 'learn',        eyebrow: 'LEARN \u00b7 4 MIN',             title: 'Sending money home calmly', body: 'Corridor rates compared',          cta: 'Read' },
        ]}
        onCardAction={() => {}}
      />
    </Page>
  );
}

function QuickAction({ icon, label }) {
  return (
    <button style={{
      background:
        'linear-gradient(180deg, rgba(255,255,255,0.06) 0%, rgba(255,255,255,0.01) 100%), rgba(193,160,129,0.08)',
      boxShadow:
        'inset 0 1px 0 rgba(255,255,255,0.10), inset 0 -1px 0 rgba(0,0,0,0.18), 0 6px 18px rgba(0,0,0,0.22)',
      backdropFilter: 'blur(12px) saturate(1.3)',
      WebkitBackdropFilter: 'blur(12px) saturate(1.3)',
      border: 'none',
      borderRadius: 18,
      padding: '14px 12px 12px',
      cursor: 'pointer',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
      color: 'var(--goji-accent)',
      transition: 'transform var(--dur-instant) var(--ease-smooth)',
    }}>
      <Icon name={icon} size={22} stroke={1.75} />
      <span style={{
        fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 500,
        color: 'var(--color-text-muted)', letterSpacing: '-0.005em',
      }}>{label}</span>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// MoneyScreen — multi-currency accounts + sparkline + transactions
// ─────────────────────────────────────────────────────────────
function MoneyScreen({ hidden, onToggleHidden }) {
  const [filter, setFilter] = useStateScreens('all');
  return (
    <Page>
      <Header title="Money" hidden={hidden} onToggleHidden={onToggleHidden} />

      {/* This week summary */}
      <div style={{ padding: '4px 20px 0' }}>
        <div style={{
          background: 'var(--color-surface)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-card)',
          padding: '20px 22px 18px',
          boxShadow: 'var(--shadow-premium)',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', top: -70, right: -50, width: 200, height: 200,
            background: 'radial-gradient(circle, var(--color-glow-subtle) 0%, transparent 70%)',
            pointerEvents: 'none',
          }} />

          {/* Eyebrow + delta pill */}
          <div style={{
            position: 'relative',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <span style={{
              fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500,
              letterSpacing: '0.12em', textTransform: 'uppercase',
              color: 'var(--color-text-muted)',
            }}>This week</span>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 600,
              padding: '3px 9px', borderRadius: 9999,
              background: 'rgba(111, 207, 151, 0.10)',
              border: '1px solid rgba(111, 207, 151, 0.25)',
              color: '#6FCF97',
              fontVariantNumeric: 'tabular-nums', fontFeatureSettings: '"tnum" 1',
            }}>
              <Icon name="arrowUp" size={11} stroke={2.5} />
              <Money amount={214} sign size="11px" color="#6FCF97" />
            </span>
          </div>

          {/* Hero number — Fraunces, primary color (not gradient — that's reserved for STS) */}
          <div style={{
            position: 'relative',
            fontFamily: 'var(--font-serif)', fontWeight: 600,
            fontSize: 44, lineHeight: 1.05, letterSpacing: '-0.03em',
            color: 'var(--color-text-primary)',
            margin: '12px 0 4px',
            fontVariantNumeric: 'tabular-nums lining-nums',
            fontFeatureSettings: '"tnum" 1, "lnum" 1',
          }}>
            <Money amount={4506.40} size="44px" color="var(--color-text-primary)" />
          </div>
          <div style={{
            position: 'relative',
            fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)',
          }}>Net across 3 accounts</div>

          {/* Sparkline */}
          <svg viewBox="0 0 320 56" width="100%" height="44"
            style={{ marginTop: 14, display: 'block', position: 'relative' }}
            preserveAspectRatio="none">
            <defs>
              <linearGradient id="sparkFill" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="#C1A081" stopOpacity="0.22"/>
                <stop offset="100%" stopColor="#C1A081" stopOpacity="0"/>
              </linearGradient>
            </defs>
            <path d="M0,40 C20,38 40,42 60,36 C80,30 100,34 120,30 C140,28 160,32 180,22 C200,16 220,20 240,16 C260,14 280,18 300,10 L320,8 L320,56 L0,56 Z" fill="url(#sparkFill)"/>
            <path d="M0,40 C20,38 40,42 60,36 C80,30 100,34 120,30 C140,28 160,32 180,22 C200,16 220,20 240,16 C260,14 280,18 300,10 L320,8" stroke="#C1A081" strokeWidth="1.5" fill="none" vectorEffect="non-scaling-stroke"/>
          </svg>

          {/* Divider */}
          <div style={{
            position: 'relative',
            height: 1, background: 'var(--color-border-subtle)',
            margin: '14px -22px 14px',
          }} />

          {/* 3 metrics — spent / sent / saved */}
          <div style={{
            position: 'relative',
            display: 'grid', gridTemplateColumns: '1fr 1px 1fr 1px 1fr',
            alignItems: 'center',
          }}>
            <Metric label="Spent"   value={`-$214`} />
            <div style={{ height: 32, background: 'var(--color-border-subtle)' }} />
            <Metric label="Sent home" value={`$340`} />
            <div style={{ height: 32, background: 'var(--color-border-subtle)' }} />
            <Metric label="Saved"   value={`$126`} />
          </div>
        </div>
      </div>

      <SectionTitle>Accounts</SectionTitle>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <AccountCard bank="Wells Fargo" mark="WF" color="#7DBEB7" currency="USD" amount={4218.40} delta={214} deltaPositive />
        <AccountCard bank="Nabil Bank" mark="NB" color="#E4B499" currency="NPR" currencySymbol="रू " amount={38450} lastSynced="2h ago" />
        <AccountCard bank="Ally Savings" mark="AL" color="#9B7BD6" currency="USD" amount={288.00} delta={0} deltaPositive />
      </div>

      <SectionTitle>Activity</SectionTitle>
      <div style={{ padding: '0 20px 0', display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4 }}>
        <Chip active={filter==='all'} onClick={()=>setFilter('all')}>All</Chip>
        <Chip active={filter==='week'} onClick={()=>setFilter('week')}>This week</Chip>
        <Chip color="#7E6896" onClick={()=>setFilter('bills')}>Bills</Chip>
        <Chip color="#E0876A" onClick={()=>setFilter('food')}>Food</Chip>
        <Chip color="#9B7BD6" onClick={()=>setFilter('family')}>Family</Chip>
      </div>
      <div style={{
        margin: '16px 20px 0',
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
        boxShadow: 'var(--shadow-premium)',
        overflow: 'hidden',
      }}>
        <TransactionRow icon="coffee" color="#E0876A" name="Blue Bottle Coffee" meta="Today · Coffee" amount={-6.50} />
        <TransactionRow icon="family" color="#9B7BD6" name="Sent to Mom" meta="Tue 14 · Family" amount={-340} />
        <TransactionRow icon="bill" color="#7E6896" name="Comcast Internet" meta="Tue 14 · Bills" amount={-79.99} />
        <TransactionRow icon="salary" color="#6FCF97" name="Salary — Acme Inc." meta="Mon 13 · Income" amount={4210} positive />
        <TransactionRow icon="home2" color="#7E6896" name="Rent" meta="Mon 13 · Bills" amount={-1650} divider={false} />
      </div>
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// InsightsScreen — AI observations as a feed of cards
// ─────────────────────────────────────────────────────────────
function InsightsScreen({ theme, onToggleTheme }) {
  return (
    <Page>
      <Header title="Insights" theme={theme} onToggleTheme={onToggleTheme} />
      <div style={{ padding: '8px 20px 0', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <InsightCard
          eyebrow="This month"
          body={<>Your grocery spend has crept up <b style={{ color: 'var(--color-text-primary)' }}>18%</b> since October. Mostly at Whole Foods.</>}
        />
        <InsightCard
          eyebrow="Family"
          body={<>Transfers to family have averaged <b style={{ color: 'var(--color-text-primary)' }}>$340/mo</b> this year. Same as 2024.</>}
          tone="good"
        />
        <InsightCard
          eyebrow="Subscriptions"
          body={<>You're paying for two music services — Spotify ($10.99) and Apple Music ($10.99). Consider keeping one.</>}
          tone="warn"
        />
        <InsightCard
          eyebrow="FX"
          body={<>NPR is up <b style={{ color: 'var(--color-text-primary)' }}>1.4%</b> against USD this week. Good moment to top up Nabil.</>}
        />
        <InsightCard
          eyebrow="Pattern"
          body={<>You spend ~<b style={{ color: 'var(--color-text-primary)' }}>$42</b> more on weekends. Friday evenings are your priciest stretch.</>}
        />
      </div>
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// ProfileScreen — user, settings rows, sign out
// ─────────────────────────────────────────────────────────────
function ProfileScreen({ theme, onToggleTheme }) {
  const rows = [
    { icon: 'user',     label: 'Personal details',  meta: 'Asha · ash@goji.app' },
    { icon: 'wallet',   label: 'Linked accounts',   meta: '3 banks · 2 currencies' },
    { icon: 'target',   label: 'Goals',             meta: '2 active' },
    { icon: 'refresh',  label: 'Currencies & FX',   meta: 'USD · NPR · EUR' },
    { icon: 'bell',     label: 'Notifications',     meta: 'Bills · weekly digest' },
    { icon: 'settings', label: 'Preferences',       meta: 'Theme · biometrics' },
  ];
  return (
    <Page>
      <Header title="Profile" theme={theme} onToggleTheme={onToggleTheme} />

      {/* Identity card */}
      <div style={{ padding: '4px 20px 0' }}>
        <div style={{
          background: 'var(--color-surface)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-card)',
          padding: 22,
          boxShadow: 'var(--shadow-premium)',
          display: 'flex', alignItems: 'center', gap: 16,
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 999,
            background: 'var(--goji-gradient)',
            display: 'grid', placeItems: 'center',
            fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 600,
            color: 'var(--goji-btn-text)', letterSpacing: '-0.02em',
          }}>A</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 17, fontWeight: 600, color: 'var(--color-text-primary)' }}>Asha Pradhan</div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-muted)', marginTop: 2 }}>Member since 2024 · Tier 2</div>
          </div>
        </div>
      </div>

      <SectionTitle>Account</SectionTitle>
      <div style={{
        margin: '0 20px',
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
        boxShadow: 'var(--shadow-premium)',
        overflow: 'hidden',
      }}>
        {rows.map((r, i) => (
          <div key={r.label} style={{
            display: 'grid', gridTemplateColumns: '38px 1fr auto',
            alignItems: 'center', gap: 14, padding: '14px 18px',
            borderBottom: i < rows.length - 1 ? '1px solid var(--color-border-subtle)' : 'none',
            cursor: 'pointer',
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: 'rgba(193,160,129,0.08)',
              border: '1px solid rgba(193,160,129,0.18)',
              color: 'var(--goji-accent)',
              display: 'grid', placeItems: 'center',
            }}>
              <Icon name={r.icon} size={18} />
            </div>
            <div>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--color-text-primary)', fontWeight: 500 }}>{r.label}</div>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)', marginTop: 2 }}>{r.meta}</div>
            </div>
            <div style={{ color: 'var(--color-text-muted)' }}>
              <Icon name="chevronRight" size={16} />
            </div>
          </div>
        ))}
      </div>

      <div style={{ padding: '24px 20px 0', display: 'flex', justifyContent: 'center' }}>
        <button style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500,
          color: '#EB5757', padding: '12px 24px',
        }}>Sign out</button>
      </div>
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// SendSheet — modal sliding from bottom. Backdrop dismiss.
// ─────────────────────────────────────────────────────────────
function SendSheet({ open, onClose }) {
  const [amount, setAmount] = useStateScreens('340');
  const [recipient, setRecipient] = useStateScreens('Mom');
  return (
    <>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, zIndex: 50,
        background: open ? 'rgba(0,0,0,0.5)' : 'transparent',
        opacity: open ? 1 : 0,
        pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity var(--dur-normal) var(--ease-smooth)',
      }} />
      {/* Sheet */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 60,
        background: 'var(--color-surface)',
        borderTopLeftRadius: 'var(--radius-sheet)',
        borderTopRightRadius: 'var(--radius-sheet)',
        boxShadow: 'var(--shadow-glass)',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform var(--dur-slow) var(--ease-smooth)',
        padding: '14px 20px 32px',
        maxHeight: '90%',
        display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        {/* Grabber */}
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--color-border-strong)', alignSelf: 'center' }} />

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h2 style={{
            margin: 0, fontFamily: 'var(--font-serif)', fontWeight: 600,
            fontSize: 24, color: 'var(--color-text-primary)', letterSpacing: '-0.02em',
          }}>Send money</h2>
          <button onClick={onClose} style={{
            width: 36, height: 36, borderRadius: 999,
            background: 'var(--color-input-bg)', border: '1px solid var(--color-border)',
            color: 'var(--color-text-body)', cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>
            <Icon name="close" size={16} />
          </button>
        </div>

        {/* Big amount entry */}
        <div style={{
          textAlign: 'center', padding: '14px 0',
          background: 'var(--color-surface-2)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-card)',
        }}>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--color-text-muted)', marginBottom: 4 }}>You send</div>
          <div style={{
            fontFamily: 'var(--font-serif)', fontWeight: 600,
            fontSize: 56, lineHeight: 1, letterSpacing: '-0.04em',
            color: 'var(--color-text-primary)',
            fontVariantNumeric: 'tabular-nums lining-nums',
            fontFeatureSettings: '"tnum" 1',
          }}>${amount}</div>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)', marginTop: 6 }}>≈ रू 45,220 · rate 132.99</div>
        </div>

        <Field label="To" leadingIcon="user" value={recipient} onChange={setRecipient} />
        <Field label="From" value="Wells Fargo · Checking" leadingIcon="wallet" />

        <div style={{ marginTop: 'auto', display: 'flex', gap: 10 }}>
          <Button variant="secondary" style={{ flex: 1 }} onClick={onClose}>Cancel</Button>
          <Button variant="primary" style={{ flex: 2 }} trailingIcon="send" onClick={onClose}>Send ${amount}</Button>
        </div>
      </div>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// SettingsSheet — full-screen overlay (same pattern as Profile).
// Name kept for back-compat but layout is now an overlay.
// ─────────────────────────────────────────────────────────────
function SettingsSheet({ open, onClose, theme, onToggleTheme, hidden, onToggleHidden }) {
  const rows = [
    { label: 'Appearance',     value: theme === 'dark' ? 'Dark' : 'Light', toggle: onToggleTheme, icon: theme === 'dark' ? 'moon' : 'sun' },
    { label: 'Hide amounts',   value: hidden ? 'On' : 'Off',                toggle: onToggleHidden, icon: hidden ? 'eyeOff' : 'eye' },
    { label: 'Biometrics',     value: 'Face ID',                            icon: 'scanFace' },
    { label: 'Notifications',  value: 'Bills · weekly',                     icon: 'bell' },
    { label: 'Currencies & FX',value: 'USD · NPR · EUR',                    icon: 'refresh' },
    { label: 'Language',       value: 'English',                            icon: 'globe' },
  ];
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 80,
      background: 'var(--color-bg)',
      opacity: open ? 1 : 0,
      transform: open ? 'scale(1)' : 'scale(0.97)',
      pointerEvents: open ? 'auto' : 'none',
      transition: 'opacity 280ms var(--ease-smooth), transform 320ms var(--ease-smooth)',
      display: 'flex', flexDirection: 'column',
      paddingTop: 56,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center',
        padding: '10px 12px 10px', height: 48, position: 'relative',
      }}>
        <button onClick={onClose} aria-label="Close" style={{
          width: 32, height: 32, borderRadius: 999,
          background: 'transparent', border: 'none', cursor: 'pointer',
          color: 'var(--color-text-primary)', display: 'grid', placeItems: 'center',
        }}>
          <Icon name="chevronLeft" size={20} stroke={2} />
        </button>
        <div style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, display: 'grid', placeItems: 'center', pointerEvents: 'none' }}>
          <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14, color: 'var(--color-text-primary)' }}>Settings</span>
        </div>
        <div style={{ width: 32, marginLeft: 'auto' }} />
      </div>

      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', paddingBottom: 32 }}>
        <div style={{ padding: '8px 20px 0' }}>
          <div style={{
            background: 'var(--color-surface)',
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-card)',
            boxShadow: 'var(--shadow-premium)',
            overflow: 'hidden',
          }}>
            {rows.map((r, i) => (
              <div key={r.label}
                onClick={r.toggle}
                style={{
                  display: 'grid', gridTemplateColumns: '38px 1fr auto',
                  alignItems: 'center', gap: 14, padding: '14px 18px',
                  borderBottom: i < rows.length - 1 ? '1px solid var(--color-border-subtle)' : 'none',
                  cursor: r.toggle ? 'pointer' : 'default',
                }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 10,
                  background: 'rgba(193,160,129,0.08)',
                  border: '1px solid rgba(193,160,129,0.18)',
                  color: 'var(--goji-accent)',
                  display: 'grid', placeItems: 'center',
                }}>
                  <Icon name={r.icon} size={18} />
                </div>
                <div style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--color-text-primary)', fontWeight: 500 }}>{r.label}</div>
                <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-muted)' }}>{r.value}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ProfileOverlay — full-screen fade-in panel. Fully opaque from t≈0
// so the home stack doesn't bleed through during the transition.
// ─────────────────────────────────────────────────────────────
function ProfileOverlay({ open, onClose, theme, onToggleTheme, onOpenSettings }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 80,
      background: 'var(--color-bg)',
      opacity: open ? 1 : 0,
      transform: open ? 'scale(1)' : 'scale(0.97)',
      pointerEvents: open ? 'auto' : 'none',
      transition: 'opacity 280ms var(--ease-smooth), transform 320ms var(--ease-smooth)',
      display: 'flex', flexDirection: 'column',
      paddingTop: 56,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center',
        padding: '10px 12px 10px', height: 48, position: 'relative',
      }}>
        <button onClick={onClose} aria-label="Close" style={{
          width: 32, height: 32, borderRadius: 999,
          background: 'transparent', border: 'none', cursor: 'pointer',
          color: 'var(--color-text-primary)', display: 'grid', placeItems: 'center',
        }}>
          <Icon name="chevronLeft" size={20} stroke={2} />
        </button>
        <div style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, display: 'grid', placeItems: 'center', pointerEvents: 'none' }}>
          <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14, color: 'var(--color-text-primary)' }}>Profile</span>
        </div>
        <div style={{ width: 32, marginLeft: 'auto' }} />
      </div>

      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', paddingBottom: 32 }}>
        {/* Identity card */}
        <div style={{ padding: '8px 20px 0' }}>
          <div style={{
            background: 'var(--color-surface)',
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-card)',
            padding: 22,
            boxShadow: 'var(--shadow-premium)',
            display: 'flex', alignItems: 'center', gap: 16,
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: 999,
              background: 'var(--goji-gradient)',
              display: 'grid', placeItems: 'center',
              fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 600,
              color: 'var(--goji-btn-text)', letterSpacing: '-0.02em',
            }}>A</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 17, fontWeight: 600, color: 'var(--color-text-primary)' }}>Asha Pradhan</div>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-muted)', marginTop: 2 }}>Member since 2024 · Tier 2</div>
            </div>
          </div>
        </div>

        <SectionTitle>Account</SectionTitle>
        <div style={{
          margin: '0 20px',
          background: 'var(--color-surface)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-card)',
          boxShadow: 'var(--shadow-premium)',
          overflow: 'hidden',
        }}>
          {[
            { icon: 'user',     label: 'Personal details',  meta: 'ash@goji.app' },
            { icon: 'wallet',   label: 'Linked accounts',   meta: '3 banks · 2 currencies' },
            { icon: 'target',   label: 'Goals',             meta: '3 active' },
            { icon: 'refresh',  label: 'Currencies & FX',   meta: 'USD · NPR · EUR' },
            { icon: 'bell',     label: 'Notifications',     meta: 'Bills · weekly' },
            { icon: 'gear',     label: 'Settings',          meta: 'Open',        onClick: onOpenSettings },
          ].map((r, i, arr) => (
            <div key={r.label}
              onClick={r.onClick}
              style={{
                display: 'grid', gridTemplateColumns: '38px 1fr auto',
                alignItems: 'center', gap: 14, padding: '14px 18px',
                borderBottom: i < arr.length - 1 ? '1px solid var(--color-border-subtle)' : 'none',
                cursor: 'pointer',
              }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background: 'rgba(193,160,129,0.08)',
                border: '1px solid rgba(193,160,129,0.18)',
                color: 'var(--goji-accent)',
                display: 'grid', placeItems: 'center',
              }}>
                <Icon name={r.icon} size={18} />
              </div>
              <div>
                <div style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--color-text-primary)', fontWeight: 500 }}>{r.label}</div>
                <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)', marginTop: 2 }}>{r.meta}</div>
              </div>
              <div style={{ color: 'var(--color-text-muted)' }}>
                <Icon name="chevronRight" size={16} />
              </div>
            </div>
          ))}
        </div>

        <div style={{ padding: '24px 20px 0', display: 'flex', justifyContent: 'center' }}>
          <button style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500,
            color: 'var(--goji-error, #EB5757)', padding: '12px 24px',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <Icon name="logout" size={16} stroke={2} /> Sign out
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SegmentedControl — top-of-screen tab switcher for sub-screens
// ─────────────────────────────────────────────────────────────
function SegmentedControl({ items, active, onChange }) {
  const ref = React.useRef(null);
  const [pos, setPos] = React.useState({ x: 0, w: 0 });

  React.useLayoutEffect(() => {
    if (!ref.current) return;
    const btns = ref.current.querySelectorAll('[data-seg]');
    const idx = items.findIndex(i => i.key === active);
    const btn = btns[idx];
    if (!btn) return;
    const containerRect = ref.current.getBoundingClientRect();
    const r = btn.getBoundingClientRect();
    setPos({ x: r.left - containerRect.left, w: r.width });
  }, [active, items]);

  return (
    <div ref={ref} style={{
      margin: '0 20px',
      position: 'relative',
      display: 'grid', gridTemplateColumns: `repeat(${items.length}, 1fr)`,
      background: 'var(--color-input-bg)',
      borderRadius: 9999,
      padding: 4,
      height: 38,
    }}>
      <div style={{
        position: 'absolute', top: 4, height: 30,
        left: pos.x, width: pos.w,
        borderRadius: 9999,
        background:
          'linear-gradient(180deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.03) 100%), rgba(193, 160, 129, 0.14)',
        boxShadow:
          'inset 0 1px 0 rgba(255, 255, 255, 0.18), inset 0 -1px 0 rgba(0, 0, 0, 0.20), 0 4px 12px rgba(0, 0, 0, 0.30)',
        backdropFilter: 'blur(14px) saturate(1.4)',
        WebkitBackdropFilter: 'blur(14px) saturate(1.4)',
        transition: 'left 420ms cubic-bezier(0.34, 1.10, 0.64, 1), width 420ms cubic-bezier(0.34, 1.10, 0.64, 1)',
        pointerEvents: 'none',
      }} />
      {items.map(item => (
        <button key={item.key}
          data-seg
          onClick={() => onChange(item.key)}
          style={{
            position: 'relative', zIndex: 2,
            background: 'transparent', border: 'none', cursor: 'pointer',
            fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600,
            color: active === item.key ? 'var(--goji-accent)' : 'var(--color-text-body)',
            transition: 'color 280ms var(--ease-smooth)',
            display: 'grid', placeItems: 'center',
          }}>
          {item.label}
        </button>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// InsightsAIScreen — hub with 3 sub-screens: Overview, Spending, AI Coach
// ─────────────────────────────────────────────────────────────
const AI_SUB_PAGES = [
  { key: 'overview', label: 'Overview' },
  { key: 'spending', label: 'Spending' },
  { key: 'coach',    label: 'AI Coach' },
];

function InsightsAIScreen({ hidden, onToggleHidden, onOpenSettings }) {
  const [sub, setSub] = React.useState(0);
  const activeKey = AI_SUB_PAGES[sub].key;

  return (
    <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
      <Header title="Insights AI" hidden={hidden} onToggleHidden={onToggleHidden} />
      <div style={{ padding: '4px 0 12px', flexShrink: 0 }}>
        <SegmentedControl
          items={AI_SUB_PAGES}
          active={activeKey}
          onChange={(k) => setSub(AI_SUB_PAGES.findIndex(p => p.key === k))}
        />
      </div>

      <SwipePager page={sub} onPageChange={setSub}>
        <AIOverview />
        <AISpending />
        <AICoach />
      </SwipePager>
    </div>
  );
}

// ─── Sub-screen: Overview ─────────────────────────────────────
function AIOverview() {
  return (
    <Page extraBottom={56}>
      <div style={{ padding: '4px 20px 0' }}>
        <div style={{
          background: 'var(--color-surface-2)',
          border: '1px solid var(--color-border-accent)',
          borderRadius: 'var(--radius-card)',
          padding: '18px 20px',
          boxShadow: 'var(--shadow-premium)',
          display: 'flex', gap: 14, alignItems: 'flex-start',
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: 'var(--goji-gradient)',
            display: 'grid', placeItems: 'center',
            color: 'var(--goji-btn-text)', flexShrink: 0,
            boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.3), 0 2px 8px rgba(193,160,129,0.3)',
          }}>
            <Icon name="sparkle" size={18} stroke={2} />
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--color-text-muted)' }}>Today's brief</div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 14, lineHeight: 1.5, color: 'var(--color-text-primary)', marginTop: 4 }}>
              Salary lands Friday — you're <b>$214 ahead</b> of last week. Three bills total <b>$1,740</b> this month. Want me to set aside Rent on payday?
            </div>
          </div>
        </div>
      </div>

      <SectionTitle>Observations</SectionTitle>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <InsightCard eyebrow="Pattern" body={<>You spend ~<b style={{ color: 'var(--color-text-primary)' }}>$42</b> more on weekends — Friday evenings are your priciest stretch.</>} />
        <InsightCard eyebrow="Family"  body={<>Transfers to family averaged <b style={{ color: 'var(--color-text-primary)' }}>$340/mo</b> this year. Same as 2024.</>} tone="good" />
        <InsightCard eyebrow="Subs"    body={<>You're paying for Spotify and Apple Music. Consider keeping one — saves <b style={{ color: 'var(--color-text-primary)' }}>$132/yr</b>.</>} tone="warn" />
        <InsightCard eyebrow="FX"      body={<>NPR is up <b style={{ color: 'var(--color-text-primary)' }}>1.4%</b> against USD this week. Good moment to top up Nabil.</>} />
      </div>
    </Page>
  );
}

// ─── Sub-screen: Spending ─────────────────────────────────────
function AISpending() {
  const cats = [
    { name: 'Groceries',        amount: 324, color: '#E0876A', pct: 28 },
    { name: 'Family transfers', amount: 340, color: '#C17A74', pct: 29 },
    { name: 'Transport',        amount: 112, color: '#7DBEB7', pct: 10 },
    { name: 'Coffee & dining',  amount: 96,  color: '#D4AA45', pct: 8 },
    { name: 'Subscriptions',    amount: 56,  color: '#9B7BD6', pct: 5 },
    { name: 'Other',            amount: 232, color: '#888888', pct: 20 },
  ];
  const total = cats.reduce((s, c) => s + c.amount, 0);
  return (
    <Page extraBottom={56}>
      <div style={{ padding: '4px 20px 0' }}>
        <div style={{
          background: 'var(--color-surface)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-card)',
          padding: '20px 22px',
          boxShadow: 'var(--shadow-premium)',
        }}>
          <div style={{
            fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--color-text-muted)', marginBottom: 6,
          }}>This month so far</div>
          <Money amount={-total} size="32px" color="var(--color-text-primary)" />
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)', marginTop: 6 }}>
            18 days · <Money amount={-Math.round(total/18)} size="12px" color="var(--color-text-body)" /> /day average
          </div>

          {/* Stacked bar */}
          <div style={{ display: 'flex', height: 8, borderRadius: 999, overflow: 'hidden', marginTop: 16, background: 'var(--color-input-bg)' }}>
            {cats.map(c => (
              <div key={c.name} style={{ width: `${c.pct}%`, background: c.color }} />
            ))}
          </div>
        </div>
      </div>

      <SectionTitle>By category</SectionTitle>
      <div style={{
        margin: '0 20px',
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
        boxShadow: 'var(--shadow-premium)',
        overflow: 'hidden',
      }}>
        {cats.map((c, i) => (
          <div key={c.name} style={{
            display: 'grid', gridTemplateColumns: '16px 1fr auto auto', alignItems: 'center', gap: 12,
            padding: '14px 18px',
            borderBottom: i < cats.length - 1 ? '1px solid var(--color-border-subtle)' : 'none',
          }}>
            <span style={{ width: 10, height: 10, borderRadius: 999, background: c.color }} />
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--color-text-primary)' }}>{c.name}</div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)' }}>{c.pct}%</div>
            <Money amount={-c.amount} size="14px" color="var(--color-text-primary)" />
          </div>
        ))}
      </div>
    </Page>
  );
}

// ─── Sub-screen: AI Coach ─────────────────────────────────────
function AICoach() {
  return (
    <Page>
      <SectionTitle>Suggested</SectionTitle>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          'How much did I spend on groceries this month?',
          "What's a safe amount to save toward my trip?",
          'Show me my biggest expenses this year.',
          'How can I reduce my subscription spend?',
        ].map(q => (
          <button key={q} style={{
            textAlign: 'left',
            background: 'var(--color-input-bg)', border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-input)',
            padding: '14px 16px',
            fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-body)',
            cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
          }}>
            <span>{q}</span>
            <Icon name="arrowRight" size={14} style={{ color: 'var(--goji-accent)', flexShrink: 0 }} />
          </button>
        ))}
      </div>

      <SectionTitle>Recent</SectionTitle>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{
          background: 'var(--color-surface)', border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-card)', padding: '14px 16px', boxShadow: 'var(--shadow-premium)',
        }}>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)' }}>You asked</div>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--color-text-primary)', marginTop: 4 }}>"Can I afford to send $400 home this month?"</div>
          <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--color-border-subtle)' }}>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--goji-accent)' }}>Goji</div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-body)', marginTop: 4, lineHeight: 1.5 }}>
              Yes — after Rent and Comcast, you'll have $1,128 left. $400 home keeps $728 for the rest of the month.
            </div>
          </div>
        </div>
      </div>

      <div style={{ padding: '24px 20px 8px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background: 'var(--color-surface)', border: '1px solid var(--color-border-accent)',
          borderRadius: 9999, padding: '6px 6px 6px 18px',
          boxShadow: 'var(--shadow-premium)',
        }}>
          <Icon name="chat" size={16} style={{ color: 'var(--color-text-muted)' }} />
          <input placeholder="Ask about your spending…" style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--color-text-primary)',
          }} />
          <button style={{
            width: 36, height: 36, borderRadius: 999,
            background: 'var(--goji-gradient)', border: 'none', cursor: 'pointer',
            color: 'var(--goji-btn-text)', display: 'grid', placeItems: 'center',
          }}>
            <Icon name="arrowRight" size={16} stroke={2.25} />
          </button>
        </div>
      </div>
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// LearnScreen — educational content for diaspora finance
// ─────────────────────────────────────────────────────────────
function LearnScreen({ hidden, onToggleHidden, onOpenSettings }) {
  const articles = [
    { eyebrow: 'Diaspora · 4 min', title: 'Sending money home without losing 8% to fees', body: 'A look at corridor rates between major remittance providers — and when bank wires actually win.' },
    { eyebrow: 'Basics · 3 min',   title: 'What "safe to spend" actually means',           body: 'How Goji computes the one number, and what it deliberately ignores.' },
    { eyebrow: 'Investing · 6 min',title: 'Your first emergency fund — calmly',            body: 'Why 3 months feels safer than 6, and other unhelpful aphorisms reconsidered.' },
    { eyebrow: 'FX · 5 min',       title: 'Dollar-cost averaging into NPR',                body: 'A non-rigorous, very human approach to multi-currency saving.' },
    { eyebrow: 'Goals · 4 min',    title: 'Why your savings goal keeps stalling',          body: 'The boring research on what actually makes goals stick.' },
  ];
  return (
    <Page>
      <Header title="Learn" hidden={hidden} onToggleHidden={onToggleHidden} />

      {/* Featured */}
      <div style={{ padding: '4px 20px 0' }}>
        <div style={{
          background: 'var(--color-surface-2)',
          border: '1px solid var(--color-border-accent)',
          borderRadius: 'var(--radius-card)',
          padding: '22px',
          boxShadow: 'var(--shadow-premium)',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', top: -60, right: -60, width: 180, height: 180,
            background: 'radial-gradient(circle, rgba(227,183,136,0.16) 0%, transparent 70%)',
            pointerEvents: 'none',
          }} />
          <div style={{ position: 'relative' }}>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--goji-accent)' }}>Featured</div>
            <h3 style={{ margin: '8px 0 8px', fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--color-text-primary)', lineHeight: 1.2 }}>The calm money mindset for diaspora life</h3>
            <p style={{ margin: 0, fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-body)', lineHeight: 1.5 }}>How to think about two currencies, two households, and one life without the spreadsheet anxiety.</p>
            <button style={{
              marginTop: 14, background: 'transparent', border: 'none', cursor: 'pointer',
              fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
              color: 'var(--goji-accent)', padding: 0,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>Read · 7 min <Icon name="arrowRight" size={14} stroke={2} /></button>
          </div>
        </div>
      </div>

      {/* Category chips */}
      <div style={{ padding: '20px 20px 0', display: 'flex', gap: 8, overflowX: 'auto' }}>
        {['Diaspora', 'FX', 'Investing', 'Basics', 'Goals'].map((c, i) => (
          <Chip key={c} active={i === 0}>{c}</Chip>
        ))}
      </div>

      <SectionTitle>All articles</SectionTitle>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {articles.map((a, i) => (
          <article key={i} style={{
            background: 'var(--color-surface)',
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-card)',
            padding: '16px 18px',
            boxShadow: 'var(--shadow-premium)',
            display: 'grid', gridTemplateColumns: '1fr auto', gap: 14, alignItems: 'center',
          }}>
            <div>
              <div style={{
                fontFamily: 'var(--font-sans)', fontSize: 10, fontWeight: 500,
                letterSpacing: '0.12em', textTransform: 'uppercase',
                color: 'var(--color-text-muted)', marginBottom: 6,
              }}>{a.eyebrow}</div>
              <h4 style={{ margin: 0, fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14, lineHeight: 1.35, color: 'var(--color-text-primary)' }}>{a.title}</h4>
              <p style={{ margin: '4px 0 0', fontFamily: 'var(--font-sans)', fontSize: 12, lineHeight: 1.45, color: 'var(--color-text-body)' }}>{a.body}</p>
            </div>
            <div style={{
              width: 40, height: 40, borderRadius: 10,
              background: 'rgba(193,160,129,0.08)',
              border: '1px solid rgba(193,160,129,0.18)',
              color: 'var(--goji-accent)',
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              <Icon name="book" size={18} />
            </div>
          </article>
        ))}
      </div>
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// HowCalculatedSheet — explains the safe-to-spend math
// ─────────────────────────────────────────────────────────────
function HowCalculatedSheet({ open, onClose }) {
  const rows = [
    { label: 'Total balance',                   value: 4506, sign: false },
    { label: 'Upcoming bills · next 30 days',   value: -1740, sign: true },
    { label: 'Daily essentials buffer',          value: -200, sign: true, muted: true },
    { label: 'Available',                       value: 2566, emphasis: true },
  ];
  return (
    <>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, zIndex: 50,
        background: open ? 'rgba(0,0,0,0.5)' : 'transparent',
        opacity: open ? 1 : 0,
        pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity var(--dur-normal) var(--ease-smooth)',
      }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 60,
        background: 'var(--color-surface)',
        borderTopLeftRadius: 'var(--radius-sheet)',
        borderTopRightRadius: 'var(--radius-sheet)',
        boxShadow: 'var(--shadow-glass)',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform var(--dur-slow) var(--ease-smooth)',
        padding: '14px 20px 28px',
        display: 'flex', flexDirection: 'column', gap: 16,
        maxHeight: '85%',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--color-border-strong)', alignSelf: 'center' }} />
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <div>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--color-text-muted)' }}>How it works</div>
            <h2 style={{
              margin: '4px 0 0', fontFamily: 'var(--font-serif)', fontWeight: 600,
              fontSize: 22, color: 'var(--color-text-primary)', letterSpacing: '-0.02em',
            }}>Your safe-to-spend, calmly</h2>
          </div>
          <button onClick={onClose} aria-label="Close" style={{
            width: 32, height: 32, borderRadius: 999,
            background: 'var(--color-input-bg)', border: '1px solid var(--color-border)',
            color: 'var(--color-text-body)', cursor: 'pointer',
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>
            <Icon name="close" size={14} />
          </button>
        </div>

        <p style={{
          margin: 0,
          fontFamily: 'var(--font-sans)', fontSize: 14, lineHeight: 1.5,
          color: 'var(--color-text-body)',
        }}>
          Goji takes everything you have, removes what's already promised — bills, the daily buffer you've set — and spreads what remains evenly across the days until your next paycheck.
        </p>

        {/* Breakdown card */}
        <div style={{
          background: 'var(--color-surface-2)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-card)',
          padding: 16,
        }}>
          {rows.map((r, i) => (
            <div key={r.label} style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              padding: '10px 0',
              borderBottom: i < rows.length - 1 ? '1px solid var(--color-border-subtle)' : 'none',
            }}>
              <span style={{
                fontFamily: 'var(--font-sans)', fontSize: 13,
                color: r.emphasis ? 'var(--color-text-primary)' : 'var(--color-text-body)',
                fontWeight: r.emphasis ? 600 : 400,
              }}>{r.label}</span>
              <Money
                amount={r.value}
                sign={r.sign}
                size="15px"
                color={r.emphasis ? 'var(--color-text-primary)' : 'var(--color-text-primary)'}
              />
            </div>
          ))}

          {/* Division step */}
          <div style={{
            marginTop: 8, padding: '12px 14px',
            background: 'rgba(193, 160, 129, 0.06)',
            border: '1px solid var(--color-border-accent)',
            borderRadius: 'var(--radius-input)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          }}>
            <span style={{
              fontFamily: 'var(--font-sans)', fontSize: 12,
              color: 'var(--color-text-body)',
            }}>Available ÷ <b style={{ color: 'var(--color-text-primary)' }}>4 days</b> to payday</span>
            <span style={{
              fontFamily: 'var(--font-serif)', fontWeight: 600,
              fontSize: 22, letterSpacing: '-0.02em',
              background: 'var(--goji-gradient)',
              WebkitBackgroundClip: 'text', backgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              fontVariantNumeric: 'tabular-nums lining-nums',
              fontFeatureSettings: '"tnum" 1, "lnum" 1',
            }}>$84/day</span>
          </div>
        </div>

        <div style={{
          background: 'var(--color-surface-2)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-card)',
          padding: '14px 16px',
          fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)',
          lineHeight: 1.5,
        }}>
          <b style={{ color: 'var(--color-text-primary)', fontWeight: 600 }}>Safe to send</b> uses the same math over a 30-day horizon — the most you can comfortably transfer without dipping into your buffer.
        </div>
      </div>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// VoiceSheet — FAB voice command center.
// States: idle (auto-skipped) → recording → processing → confirm
// Intent cycles between bill / transaction / goal / budget.
// ─────────────────────────────────────────────────────────────
function VoiceSheet({ open, onClose }) {
  const [state, setState] = React.useState('recording');
  const [intentIdx, setIntentIdx] = React.useState(0);

  const INTENTS = [
    {
      type: 'bill', label: 'BILL', tone: '#7E6896',
      transcript: 'Add a Spotify Family bill, $10.99 monthly starting January 22.',
      fields: [
        { label: 'Name',        value: 'Spotify Family' },
        { label: 'Amount',      value: '−$10.99',         money: true },
        { label: 'Frequency',   value: 'Monthly' },
        { label: 'Next charge', value: 'Jan 22' },
        { label: 'Category',    value: 'Subscriptions' },
      ],
      cta: 'Add bill',
    },
    {
      type: 'transaction', label: 'TRANSACTION', tone: '#E0876A',
      transcript: 'I spent fourteen dollars on coffee at Blue Bottle today.',
      fields: [
        { label: 'Merchant',  value: 'Blue Bottle Coffee' },
        { label: 'Amount',    value: '−$14.00',         money: true },
        { label: 'Category',  value: 'Coffee & dining' },
        { label: 'Date',      value: 'Today · 9:41 AM' },
      ],
      cta: 'Log transaction',
    },
    {
      type: 'goal', label: 'GOAL', tone: '#9B7BD6',
      transcript: 'Save $2,500 for my trip home by next March.',
      fields: [
        { label: 'Name',         value: 'Trip home' },
        { label: 'Target',       value: '$2,500',          money: true },
        { label: 'Target date',  value: 'Mar 2027' },
        { label: 'Auto-save',    value: '$190 / month' },
      ],
      cta: 'Set goal',
    },
    {
      type: 'budget', label: 'BUDGET', tone: '#D4AA45',
      transcript: 'Cap my coffee budget at eighty dollars a month.',
      fields: [
        { label: 'Category',  value: 'Coffee & dining' },
        { label: 'Cap',       value: '$80 / month',     money: true },
        { label: 'Resets',    value: 'First of the month' },
      ],
      cta: 'Set budget',
    },
  ];
  const intent = INTENTS[intentIdx % INTENTS.length];

  const stop = () => {
    setState('processing');
    setTimeout(() => setState('confirm'), 900);
  };
  const confirm = () => {
    onClose();
    setTimeout(() => { setIntentIdx(i => i + 1); setState('recording'); }, 500);
  };
  const cancel = () => {
    onClose();
    setTimeout(() => setState('recording'), 500);
  };

  // Reset to recording each time it opens fresh
  React.useEffect(() => {
    if (open) setState('recording');
  }, [open]);

  return (
    <>
      <div onClick={cancel} style={{
        position: 'absolute', inset: 0, zIndex: 50,
        background: open ? 'rgba(0,0,0,0.5)' : 'transparent',
        opacity: open ? 1 : 0,
        pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity var(--dur-normal) var(--ease-smooth)',
      }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 60,
        background: 'var(--color-surface)',
        borderTopLeftRadius: 'var(--radius-sheet)',
        borderTopRightRadius: 'var(--radius-sheet)',
        boxShadow: 'var(--shadow-glass)',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform var(--dur-slow) var(--ease-smooth)',
        padding: '14px 20px 28px',
        display: 'flex', flexDirection: 'column', gap: 16,
        maxHeight: '88%', minHeight: 380,
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--color-border-strong)', alignSelf: 'center' }} />

        {state === 'recording' && <VoiceRecording onStop={stop} onCancel={cancel} />}
        {state === 'processing' && <VoiceProcessing transcript={intent.transcript} />}
        {state === 'confirm' && (
          <VoiceConfirm intent={intent} onCancel={cancel} onConfirm={confirm} />
        )}
      </div>
    </>
  );
}

function VoiceWaveform({ bars = 9 }) {
  const refs = React.useRef([]);
  React.useEffect(() => {
    let raf;
    const tick = (t) => {
      refs.current.forEach((el, i) => {
        if (!el) return;
        const phase = i * 0.55;
        const scale = 0.25 + 0.75 * Math.abs(Math.sin(t / 220 + phase));
        el.style.transform = `scaleY(${scale})`;
      });
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <div style={{ display: 'flex', gap: 8, height: 64, alignItems: 'center', justifyContent: 'center' }}>
      {Array.from({ length: bars }).map((_, i) => (
        <div key={i} ref={el => refs.current[i] = el} style={{
          width: 4, height: 64, borderRadius: 4,
          background: 'var(--goji-gradient)',
          transformOrigin: 'center',
          willChange: 'transform',
        }} />
      ))}
    </div>
  );
}

function VoiceRecording({ onStop, onCancel }) {
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--goji-accent)' }}>● Listening</div>
          <h2 style={{
            margin: '4px 0 0', fontFamily: 'var(--font-serif)', fontWeight: 600,
            fontSize: 22, color: 'var(--color-text-primary)', letterSpacing: '-0.02em',
          }}>I'm listening.</h2>
        </div>
        <button onClick={onCancel} aria-label="Cancel" style={{
          width: 32, height: 32, borderRadius: 999,
          background: 'var(--color-input-bg)', border: '1px solid var(--color-border)',
          color: 'var(--color-text-body)', cursor: 'pointer',
          display: 'grid', placeItems: 'center',
        }}>
          <Icon name="close" size={14} />
        </button>
      </div>

      <div style={{
        padding: '32px 12px 28px',
        background: 'var(--color-surface-2)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
      }}>
        <VoiceWaveform />
        <div style={{
          textAlign: 'center', marginTop: 24,
          fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-muted)',
          lineHeight: 1.5,
        }}>
          Tell me about a bill, a transaction, a goal, or a budget.
        </div>
      </div>

      <button onClick={onStop} style={{
        marginTop: 'auto',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        height: 56, borderRadius: 9999, padding: '0 24px',
        background: 'var(--goji-gradient)', border: 'none', cursor: 'pointer',
        color: 'var(--goji-btn-text)',
        fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 600,
        boxShadow: 'var(--shadow-fab)',
      }}>
        <Icon name="stopSquare" size={16} /> Stop & send
      </button>
    </>
  );
}

function VoiceProcessing({ transcript }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18, padding: '12px 4px 32px' }}>
      <div>
        <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--color-text-muted)' }}>You said</div>
        <p style={{
          margin: '6px 0 0',
          fontFamily: 'var(--font-serif)', fontWeight: 500, fontSize: 19, lineHeight: 1.35, letterSpacing: '-0.01em',
          color: 'var(--color-text-primary)',
        }}>"{transcript}"</p>
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '14px 16px',
        background: 'var(--color-surface-2)',
        border: '1px solid var(--color-border-accent)',
        borderRadius: 'var(--radius-card)',
      }}>
        <span style={{
          display: 'inline-block', width: 16, height: 16, borderRadius: 999,
          border: '2px solid var(--goji-accent)', borderTopColor: 'transparent',
          animation: 'goji-spin 700ms linear infinite',
        }} />
        <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--color-text-body)' }}>
          Reading what you said…
        </span>
      </div>
    </div>
  );
}

function VoiceConfirm({ intent, onCancel, onConfirm }) {
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '3px 9px', borderRadius: 9999,
            background: `${intent.tone}1a`, border: `1px solid ${intent.tone}40`,
            color: intent.tone,
            fontFamily: 'var(--font-sans)', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: intent.tone }} />
            {intent.label}
          </div>
          <h2 style={{
            margin: '8px 0 0', fontFamily: 'var(--font-serif)', fontWeight: 600,
            fontSize: 22, color: 'var(--color-text-primary)', letterSpacing: '-0.02em',
          }}>Does this look right?</h2>
        </div>
        <button onClick={onCancel} aria-label="Close" style={{
          width: 32, height: 32, borderRadius: 999,
          background: 'var(--color-input-bg)', border: '1px solid var(--color-border)',
          color: 'var(--color-text-body)', cursor: 'pointer',
          display: 'grid', placeItems: 'center', flexShrink: 0,
        }}>
          <Icon name="close" size={14} />
        </button>
      </div>

      <div style={{
        background: 'var(--color-surface-2)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
        padding: '14px 16px',
      }}>
        <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 500, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--color-text-muted)' }}>You said</div>
        <p style={{
          margin: '4px 0 0', fontFamily: 'var(--font-sans)', fontSize: 13, lineHeight: 1.5,
          color: 'var(--color-text-body)',
        }}>"{intent.transcript}"</p>
      </div>

      <div style={{
        background: 'var(--color-surface-2)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
        overflow: 'hidden',
      }}>
        {intent.fields.map((f, i) => (
          <div key={f.label} style={{
            display: 'grid', gridTemplateColumns: '110px 1fr',
            alignItems: 'center', gap: 12, padding: '12px 16px',
            borderBottom: i < intent.fields.length - 1 ? '1px solid var(--color-border-subtle)' : 'none',
          }}>
            <span style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-text-muted)' }}>{f.label}</span>
            <span style={{
              fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500,
              color: 'var(--color-text-primary)',
              fontVariantNumeric: f.money ? 'tabular-nums lining-nums' : 'normal',
              fontFeatureSettings: f.money ? '"tnum" 1, "lnum" 1' : 'normal',
              letterSpacing: f.money ? '-0.01em' : 0,
            }}>{f.value}</span>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 'auto', display: 'flex', gap: 10 }}>
        <button onClick={onCancel} style={{
          flex: 1, height: 52, borderRadius: 9999,
          background: 'var(--color-input-bg)',
          border: '1px solid var(--color-border-strong)',
          color: 'var(--color-text-primary)',
          fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
          cursor: 'pointer',
        }}>Cancel</button>
        <button onClick={onConfirm} style={{
          flex: 2, height: 52, borderRadius: 9999,
          background: 'var(--goji-gradient)',
          border: 'none', color: 'var(--goji-btn-text)',
          fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
          cursor: 'pointer',
          boxShadow: 'var(--shadow-fab)',
        }}>{intent.cta}</button>
      </div>
    </>
  );
}

Object.assign(window, {
  SettingsSheet, ProfileOverlay,
  InsightsAIScreen, AIOverview, AISpending, AICoach,
  LearnScreen, SegmentedControl,
});
