// terminal-onboarding.jsx — 3-step first-run modal.
// localStorage flag `tx-onboarded` skips on subsequent loads.
// Triggered from terminal.jsx App() useEffect on mount.

const ONBOARD_KEY = 'tx-onboarded';

function hasOnboarded() {
  try { return localStorage.getItem(ONBOARD_KEY) === '1'; }
  catch { return false; }
}
function setOnboarded() {
  try { localStorage.setItem(ONBOARD_KEY, '1'); } catch {}
}

function OnboardingModal({ onDone }) {
  const [step, setStep] = React.useState(0);
  const total = 3;
  const next = () => { if (step < total - 1) setStep(step + 1); else finish(); };
  const back = () => setStep(Math.max(0, step - 1));
  const finish = () => { setOnboarded(); onDone(); };

  const steps = [
    {
      eyebrow: 'COUNCIL',
      title: '25 AI agents watch every trade',
      body: 'Before any order touches a broker, 25 named agents on Base mainnet vote on it. ≥17/25 must clear. Refusals are public.',
      cta: 'Show me Shadow mode →',
      visual: <CouncilVoteBar/>,
    },
    {
      eyebrow: 'SHADOW',
      title: 'Test conviction risk-free',
      body: 'Shadow mode lets you place orders that NEVER reach the broker — but the Council still votes, and you get the same signed receipt anchored on-chain.',
      cta: 'Last step →',
      visual: <ShadowDemo/>,
    },
    {
      eyebrow: 'CONNECT',
      title: 'Connect a broker when ready',
      body: 'Alpaca or MooMoo. Or run shadow-only forever — the platform is free to explore.',
      cta: 'Open the terminal →',
      visual: <BrokerLogos/>,
    },
  ];
  const s = steps[step];

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(6,7,10,0.94)', backdropFilter: 'blur(12px)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Skip in top-right */}
      <button onClick={finish} style={{
        position: 'absolute', top: 14, right: 16, zIndex: 110,
        fontFamily: GM, fontSize: 10, color: TM.muted, letterSpacing: 1, fontWeight: 600,
      }}>SKIP ×</button>

      {/* Visual */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
        {s.visual}
      </div>

      {/* Copy block */}
      <div style={{ padding: '0 24px 32px' }}>
        <div style={{ fontFamily: GM, fontSize: 10, color: TM.cyan, letterSpacing: 1.6, fontWeight: 600 }}>
          {s.eyebrow}
        </div>
        <h2 style={{
          margin: '8px 0 12px', fontFamily: GE, fontSize: 24, fontWeight: 600,
          color: TM.text, letterSpacing: -0.6, lineHeight: 1.15,
        }}>{s.title}</h2>
        <p style={{
          margin: 0, fontFamily: GE, fontSize: 14, color: TM.muted,
          letterSpacing: -0.05, lineHeight: 1.55,
        }}>{s.body}</p>

        {/* Step dots */}
        <div style={{ display: 'flex', gap: 6, marginTop: 24, justifyContent: 'center' }}>
          {Array.from({ length: total }).map((_, i) => (
            <span key={i} style={{
              width: i === step ? 24 : 6, height: 6, borderRadius: 3,
              background: i === step ? TM.orange : 'rgba(244,244,240,0.20)',
              transition: 'width .15s, background .15s',
            }}/>
          ))}
        </div>

        {/* CTAs */}
        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          {step > 0 && (
            <button onClick={back} style={{
              padding: '14px 18px', borderRadius: 10,
              border: `1px solid ${TM.border}`, color: TM.text,
              fontFamily: GE, fontSize: 14, fontWeight: 500,
            }}>← Back</button>
          )}
          <button onClick={next} style={{
            flex: 1, padding: '14px 18px', borderRadius: 10,
            background: TM.orange, color: '#fff',
            fontFamily: GE, fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
          }}>{s.cta}</button>
        </div>
      </div>
    </div>
  );
}

function CouncilVoteBar() {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    if (n >= 25) return;
    const id = setTimeout(() => setN(n + 1), 50);
    return () => clearTimeout(id);
  }, [n]);
  return (
    <div style={{ width: '100%', maxWidth: 280, textAlign: 'center' }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
        {Array.from({ length: 25 }).map((_, i) => (
          <div key={i} style={{
            aspectRatio: '1 / 1', borderRadius: 4,
            background: i < n ? TM.green : 'rgba(244,244,240,0.06)',
            border: `1px solid ${i < n ? TM.green : TM.border}`,
            transition: 'background .15s, border-color .15s',
          }}/>
        ))}
      </div>
      <div style={{ marginTop: 16, fontFamily: GM, fontSize: 12, color: n >= 17 ? TM.green : TM.muted, letterSpacing: 0.6, fontWeight: 600 }}>
        {n} / 25 {n >= 17 ? '· CLEARED' : '· VOTING…'}
      </div>
    </div>
  );
}

function ShadowDemo() {
  return (
    <div style={{
      padding: 24, borderRadius: 16,
      background: TM.surfaceHi, border: `1px solid ${TM.cyan}55`,
      width: '100%', maxWidth: 280, textAlign: 'center',
    }}>
      <div style={{ fontFamily: GM, fontSize: 9.5, color: TM.cyan, letterSpacing: 1.4, fontWeight: 600 }}>
        ◐ SHADOW MODE
      </div>
      <div style={{ marginTop: 14, fontFamily: GE, fontSize: 32, fontWeight: 600, color: TM.text, letterSpacing: -0.6 }}>
        BUY 1 NVDA
      </div>
      <div style={{ marginTop: 4, fontFamily: GM, fontSize: 11, color: TM.muted, letterSpacing: 0.4 }}>
        @ MARKET · ZERO EXPOSURE
      </div>
      <div style={{
        marginTop: 16, padding: '8px 12px', borderRadius: 6,
        background: TM.greenSoft, border: `1px solid ${TM.green}55`,
        fontFamily: GM, fontSize: 10.5, color: TM.green, letterSpacing: 0.4, fontWeight: 600,
      }}>
        ✓ COUNCIL CLEARED · 23/25 · RECEIPT 0xa84e…
      </div>
    </div>
  );
}

function BrokerLogos() {
  return (
    <div style={{ width: '100%', maxWidth: 280, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <BrokerCard name="Alpaca"  blurb="Stocks · options · crypto · paper & live"/>
      <BrokerCard name="MooMoo"  blurb="US stocks · global markets · options"/>
      <BrokerCard name="Shadow only" blurb="No broker · zero exposure · still on-chain"/>
    </div>
  );
}
function BrokerCard({ name, blurb }) {
  return (
    <div style={{
      padding: '14px 16px', borderRadius: 12,
      background: TM.surfaceHi, border: `1px solid ${TM.border}`,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: GE, fontSize: 14, fontWeight: 600, color: TM.text, letterSpacing: -0.2 }}>{name}</div>
        <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted, marginTop: 2, letterSpacing: -0.05 }}>{blurb}</div>
      </div>
      <span style={{ color: TM.cyan, fontSize: 18 }}>›</span>
    </div>
  );
}

Object.assign(window, { OnboardingModal, hasOnboarded, setOnboarded, ONBOARD_KEY });
