// terminal-account.jsx — Account / Profile screen + Alerts inbox.
// Long-press or tap the wordmark in any header opens this. Mirrors the
// templated pattern: hero card on top, grouped list rows beneath.

const ACCOUNT = {
  name:     'Jamie Whitmore',
  email:    'jamie@lakenormancapital.com',
  member:   'Member since May 2026',
  tier:     'Full Sweep',
  walletShort: '0x9092…bb8c',
  cashUSD:  8420.18,
  buyingPower: 16840.36,
  marginUsed: 0,
  marginAvailable: 25000,
};

const ALERTS = [
  { id: 1, kind: 'cleared',  sym: 'NVDA', body: 'Council cleared your NVDA buy · 23/25 verifiers',     minsAgo: 7   },
  { id: 2, kind: 'price',    sym: 'BTC',  body: 'BTC crossed $62,000 price alert',                      minsAgo: 18  },
  { id: 3, kind: 'refused',  sym: 'GME',  body: 'Council refused a GME order · 8/25 verifiers',         minsAgo: 41  },
  { id: 4, kind: 'heartbeat',sym: '',     body: 'Daily heartbeat complete · 25/25 signed',              minsAgo: 90  },
  { id: 5, kind: 'cleared',  sym: 'SPY',  body: 'Council cleared your SPY buy · 24/25 verifiers',       minsAgo: 134 },
  { id: 6, kind: 'system',   sym: '',     body: 'New compute dispatcher commit · 5e504bfd',             minsAgo: 200 },
];

function AccountScreen({ onBack, onOpenDetail }) {
  const [tab, setTab] = React.useState('profile');

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: TM.surface }} className="tx-scroll">
      <TopBar title="Account" subtitle={ACCOUNT.member} onBack={onBack}
        right={<button style={{
          width: 32, height: 32, borderRadius: 16, color: TM.muted,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="1.6"/>
            <path d="M12 1v4M12 19v4M4.2 4.2l2.8 2.8M17 17l2.8 2.8M1 12h4M19 12h4M4.2 19.8L7 17M17 7l2.8-2.8"
              stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
        </button>}/>

      {/* Tab strip */}
      <div style={{ padding: '12px 16px 0' }}>
        <Segmented value={tab} onChange={setTab} options={[
          { key: 'profile', label: 'Profile' },
          { key: 'alerts',  label: `Alerts (${ALERTS.length})` },
          { key: 'settings',label: 'Settings' },
        ]}/>
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }} className="tx-scroll">
        {tab === 'profile'  && <ProfileTab/>}
        {tab === 'alerts'   && <AlertsTab onOpenDetail={onOpenDetail}/>}
        {tab === 'settings' && <SettingsTab/>}
      </div>
    </div>
  );
}

function ProfileTab() {
  return (
    <>
      {/* Identity hero */}
      <div style={{
        padding: '20px 16px', display: 'flex', alignItems: 'center', gap: 14,
        borderBottom: `1px solid ${TM.border}`,
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: 28,
          background: TM.cyanSoft, border: `1px solid ${TM.cyan}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: GE, fontSize: 22, fontWeight: 600, color: TM.cyan, letterSpacing: -0.4,
        }}>
          {ACCOUNT.name.split(' ').map(s => s[0]).slice(0, 2).join('')}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: GE, fontSize: 17, fontWeight: 600, color: TM.text, letterSpacing: -0.3 }}>{ACCOUNT.name}</div>
          <div style={{ fontFamily: GE, fontSize: 12.5, color: TM.muted, marginTop: 2 }}>{ACCOUNT.email}</div>
          <div style={{
            marginTop: 8, display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '3px 8px', background: TM.orangeSoft, border: `1px solid ${TM.orange}55`, borderRadius: 4,
            fontFamily: GM, fontSize: 10, color: TM.orange, fontWeight: 600, letterSpacing: 0.6,
          }}>
            <span style={{ width: 5, height: 5, borderRadius: 3, background: TM.orange }}/>
            {ACCOUNT.tier.toUpperCase()} · ACTIVE
          </div>
        </div>
      </div>

      {/* Cash + buying power */}
      <SectionHeader title="Cash & buying power"/>
      <div style={{
        margin: '0 16px', padding: '14px 16px',
        background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 10,
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14,
      }}>
        <Stat k="Cash"           v={`$${ACCOUNT.cashUSD.toFixed(2)}`}/>
        <Stat k="Buying power"   v={`$${ACCOUNT.buyingPower.toFixed(2)}`} color={TM.green}/>
        <Stat k="Margin used"    v={`$${ACCOUNT.marginUsed.toFixed(2)}`}/>
        <Stat k="Margin avail."  v={`$${ACCOUNT.marginAvailable.toLocaleString()}`}/>
      </div>

      {/* Wallet */}
      <SectionHeader title="On-chain identity"/>
      <div style={{
        margin: '0 16px', padding: '14px 16px',
        background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 10,
      }}>
        <Mono color={TM.muted}>SMART WALLET · BASE</Mono>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 6 }}>
          <span style={{ fontFamily: GM, fontSize: 14, color: TM.text, letterSpacing: 0.3 }}>{ACCOUNT.walletShort}</span>
          <a href="#" style={{ fontFamily: GM, fontSize: 10, color: TM.cyan, letterSpacing: 0.6, fontWeight: 600 }}>BASESCAN ↗</a>
        </div>
        <div style={{ marginTop: 12, fontFamily: GE, fontSize: 12, color: TM.muted, letterSpacing: -0.05, lineHeight: 1.55 }}>
          All receipts you generate are anchored to this address on Base. Connected to your TradeXchange account via the magic link you signed in with.
        </div>
      </div>

      {/* Quick actions */}
      <SectionHeader title="Quick actions"/>
      <div style={{ padding: '0 16px 24px', display: 'flex', flexDirection: 'column', gap: 0 }}>
        {[
          { k: 'Deposit funds',          c: TM.green  },
          { k: 'Withdraw funds',         c: TM.text   },
          { k: 'Connect broker',         c: TM.cyan   },
          { k: 'Download tax statements',c: TM.muted  },
          { k: 'Refer a trader · earn $50',c: TM.orange },
        ].map((row, i) => (
          <button key={row.k} style={{
            width: '100%', textAlign: 'left',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 0', borderTop: i === 0 ? `1px solid ${TM.border}` : 'none',
            borderBottom: `1px solid ${TM.border}`,
          }}>
            <span style={{ fontFamily: GE, fontSize: 14, color: row.c, letterSpacing: -0.1, fontWeight: 500 }}>{row.k}</span>
            <span style={{ color: TM.muted, fontSize: 18 }}>›</span>
          </button>
        ))}
      </div>
    </>
  );
}

function AlertsTab({ onOpenDetail }) {
  return (
    <>
      <div style={{
        margin: '14px 16px 0', padding: '12px 14px',
        background: TM.cyanSoft, border: `1px solid ${TM.cyan}55`, borderRadius: 10,
      }}>
        <Mono color={TM.cyan} weight={600}>EVERY ALERT IS REPLAYABLE</Mono>
        <div style={{ marginTop: 6, fontFamily: GE, fontSize: 12.5, color: TM.text, letterSpacing: -0.05, lineHeight: 1.55 }}>
          Council notifications carry the same receipt you'd see in the Receipts tab. Tap any cleared / refused row to inspect its compute proof and verifier breakdown.
        </div>
      </div>

      <div style={{ marginTop: 14 }}>
        {ALERTS.map((a, i) => <AlertRow key={a.id} alert={a} onClick={() => a.sym && onOpenDetail && onOpenDetail(a.sym)} last={i === ALERTS.length - 1}/>)}
      </div>

      <div style={{ padding: '20px 16px 32px', textAlign: 'center' }}>
        <button style={{ color: TM.muted, fontFamily: GE, fontSize: 13 }}>Mark all as read</button>
      </div>
    </>
  );
}

function AlertRow({ alert, onClick, last }) {
  const meta = ({
    cleared:   { color: TM.green,  icon: '✓', label: 'CLEARED' },
    refused:   { color: TM.red,    icon: '✗', label: 'REFUSED' },
    price:     { color: TM.cyan,   icon: '↑', label: 'PRICE'   },
    heartbeat: { color: TM.violet, icon: '◉', label: 'PULSE'   },
    system:    { color: TM.muted,  icon: '·', label: 'SYSTEM'  },
  })[alert.kind] || { color: TM.muted, icon: '·', label: '' };

  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left',
      display: 'grid', gridTemplateColumns: '36px 1fr auto', gap: 12, alignItems: 'center',
      padding: '12px 16px', borderBottom: last ? 'none' : `1px solid ${TM.border}`,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 16,
        background: meta.color + '22', border: `1px solid ${meta.color}55`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: meta.color, fontFamily: GM, fontWeight: 600, fontSize: 14,
      }}>{meta.icon}</div>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {alert.sym && (
            <span style={{ fontFamily: GM, fontSize: 11, fontWeight: 600, color: TM.text, letterSpacing: 0.4 }}>{alert.sym}</span>
          )}
          <Mono color={meta.color} size={9.5} weight={600}>{meta.label}</Mono>
        </div>
        <div style={{ marginTop: 4, fontFamily: GE, fontSize: 13, color: TM.text, letterSpacing: -0.1, lineHeight: 1.4 }}>
          {alert.body}
        </div>
      </div>
      <Mono color={TM.muted} size={10}>
        {alert.minsAgo < 60 ? `${alert.minsAgo}m` : `${Math.floor(alert.minsAgo/60)}h ${alert.minsAgo%60}m`}
      </Mono>
    </button>
  );
}

function SettingsTab() {
  const [pushEnabled, setPush] = React.useState(true);
  const [emailEnabled, setEmail] = React.useState(true);
  const [refusalSound, setRefusalSound] = React.useState(false);
  const [hideBalances, setHideBalances] = React.useState(false);

  return (
    <>
      <SectionHeader title="Notifications"/>
      <div style={{ padding: '0 16px' }}>
        <ToggleRow label="Push notifications"     desc="Real-time alerts when the Council clears or refuses an order." value={pushEnabled} onChange={setPush}/>
        <ToggleRow label="Email digests"          desc="Daily summary of receipts, P/L, and Council activity." value={emailEnabled} onChange={setEmail}/>
        <ToggleRow label="Refusal sound"          desc="Play a soft chime when an order is refused." value={refusalSound} onChange={setRefusalSound} last/>
      </div>

      <SectionHeader title="Privacy"/>
      <div style={{ padding: '0 16px' }}>
        <ToggleRow label="Hide balances by default" desc="Replace dollar amounts with •••• until tapped." value={hideBalances} onChange={setHideBalances}/>
        <ToggleRow label="Receipts public on Basescan" desc="Other people can see your trade fingerprints. On = trust signal, off = silence." value={true} onChange={() => {}} last/>
      </div>

      <SectionHeader title="About"/>
      <div style={{ padding: '0 16px 32px' }}>
        {[
          { k: 'Platform version',    v: 'Terminal v1.0 · May 21 2026' },
          { k: 'Dispatcher commit',   v: '5e504bfd' },
          { k: 'Brand seed',          v: '1779342991571' },
          { k: 'License',             v: 'EpochCore LLC · All rights reserved' },
        ].map((it, i, arr) => (
          <div key={it.k} style={{
            display: 'flex', justifyContent: 'space-between',
            padding: '14px 0',
            borderTop: i === 0 ? `1px solid ${TM.border}` : 'none',
            borderBottom: `1px solid ${TM.border}`,
          }}>
            <span style={{ fontFamily: GE, fontSize: 13.5, color: TM.muted, letterSpacing: -0.05 }}>{it.k}</span>
            <span style={{ fontFamily: GM, fontSize: 12, color: TM.text, letterSpacing: 0.2 }}>{it.v}</span>
          </div>
        ))}
        <div style={{ marginTop: 18, textAlign: 'center' }}>
          <button style={{
            fontFamily: GE, fontSize: 13, color: TM.red,
            padding: '12px 24px', border: `1px solid ${TM.red}55`, borderRadius: 8,
          }}>Sign out</button>
        </div>
      </div>
    </>
  );
}

function ToggleRow({ label, desc, value, onChange, last }) {
  return (
    <div style={{
      padding: '14px 0',
      borderTop: `1px solid ${TM.border}`,
      borderBottom: last ? `1px solid ${TM.border}` : 'none',
      display: 'flex', alignItems: 'flex-start', gap: 16,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: GE, fontSize: 14, color: TM.text, fontWeight: 500, letterSpacing: -0.1 }}>{label}</div>
        <div style={{ marginTop: 3, fontFamily: GE, fontSize: 12, color: TM.muted, letterSpacing: -0.05, lineHeight: 1.5 }}>{desc}</div>
      </div>
      <button onClick={() => onChange(!value)} style={{
        width: 40, height: 24, borderRadius: 12, position: 'relative', flexShrink: 0,
        background: value ? TM.green : 'rgba(244,244,240,0.15)',
        transition: 'background .15s',
      }}>
        <span style={{
          position: 'absolute', top: 2, left: value ? 18 : 2, width: 20, height: 20, borderRadius: 10,
          background: '#fff', transition: 'left .15s',
        }}/>
      </button>
    </div>
  );
}

Object.assign(window, { AccountScreen, ACCOUNT, ALERTS });
