// terminal.jsx — App entry point. Routes between the 6 tabs and the
// holding-detail overlay. Persists active tab in localStorage so navigation
// survives reload.

const STORAGE_KEY = 'tx-terminal-state';

function loadState() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}'); }
  catch { return {}; }
}
function saveState(s) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch {}
}

function App() {
  const stored = loadState();
  const [tab, setTab] = React.useState(stored.tab || 'markets');
  const [detailSym, setDetailSym] = React.useState(null);
  const [orderSym, setOrderSym] = React.useState(null);
  const [orderMode, setOrderMode] = React.useState('live');
  const [showNews, setShowNews] = React.useState(false);
  const [showSearch, setShowSearch] = React.useState(false);
  const [showAccount, setShowAccount] = React.useState(false);

  React.useEffect(() => { saveState({ tab }); }, [tab]);
  React.useEffect(() => {
    window.__txNav = (target) => {
      const reset = () => { setOrderSym(null); setDetailSym(null); setShowNews(false); setShowSearch(false); setShowAccount(false); };
      reset();
      if (target === 'news')    setShowNews(true);
      if (target === 'search')  setShowSearch(true);
      if (target === 'account') setShowAccount(true);
    };
    return () => { delete window.__txNav; };
  }, []);

  const openDetail = (sym) => { setShowNews(false); setShowSearch(false); setShowAccount(false); setDetailSym(sym); };
  const closeDetail = () => setDetailSym(null);
  const openOrder = (sym, mode = 'live') => { setOrderMode(mode); setOrderSym(sym); };
  const closeOrder = () => setOrderSym(null);
  const closeNews = () => setShowNews(false);
  const closeSearch = () => setShowSearch(false);
  const closeAccount = () => setShowAccount(false);

  return (
    <PhoneFrame>
      {orderSym ? (
        <OrderTicketScreen sym={orderSym} mode={orderMode} onClose={closeOrder}/>
      ) : showSearch ? (
        <SearchScreen onOpenDetail={openDetail} onClose={closeSearch}/>
      ) : showAccount ? (
        <AccountScreen onBack={closeAccount} onOpenDetail={openDetail}/>
      ) : showNews ? (
        <NewsScreenWrapper onOpenDetail={openDetail} onClose={closeNews}/>
      ) : detailSym ? (
        <HoldingDetailScreen sym={detailSym} onBack={closeDetail} onTrade={openOrder}/>
      ) : (
        <>
          {tab === 'watchlists' && <WatchlistsScreen onOpenDetail={openDetail}/>}
          {tab === 'markets'    && <MarketsScreen    onOpenDetail={openDetail}/>}
          {tab === 'portfolio'  && <PortfolioScreen  onOpenDetail={openDetail}/>}
          {tab === 'receipts'   && <ReceiptsScreen   onOpenDetail={() => {}}/>}
          {tab === 'insights'   && <InsightsScreen/>}
          {tab === 'council'    && <CouncilTab/>}
        </>
      )}
      {!orderSym && !showSearch && !showAccount && (
        <BottomTabBar active={tab} onChange={(k) => {
          setShowNews(false); setShowSearch(false); setShowAccount(false); setDetailSym(null); setTab(k);
        }}/>
      )}
    </PhoneFrame>
  );
}

// Light wrapper so News gets a back button like the other overlays.
function NewsScreenWrapper({ onOpenDetail, onClose }) {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      <NewsScreen onOpenDetail={onOpenDetail}/>
      <div style={{
        position: 'absolute', top: 14, left: 14, zIndex: 30,
      }}>
        <button onClick={onClose} style={{
          width: 32, height: 32, borderRadius: 16, background: TM.surfaceHi,
          border: `1px solid ${TM.border}`, color: TM.text,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 1L3 7l6 6" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
    </div>
  );
}

// ── Council tab — a quick on-ramp to the full Council page ───
function CouncilTab() {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'auto' }} className="tx-scroll">
      <TopBar title="The Council"/>
      <div style={{
        margin: '16px 16px 0', padding: '20px 18px',
        background: `linear-gradient(135deg, ${TM.cyanSoft}, rgba(40,35,155,0.10))`,
        border: `1px solid ${TM.cyan}55`, borderRadius: 12,
        textAlign: 'center',
      }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '4px 10px', background: 'rgba(244,244,240,0.06)',
          border: `1px solid ${TM.border}`, borderRadius: 99,
          fontFamily: GM, fontSize: 9.5, color: TM.cyan, letterSpacing: 1.2, fontWeight: 600,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: TM.green,
            animation: 'pulse-soft 1.6s ease-out infinite' }}/>
          25 / 25 LIVE
        </div>
        <div style={{ marginTop: 14, fontFamily: GE, fontSize: 21, fontWeight: 600, color: TM.text, letterSpacing: -0.5, lineHeight: 1.2 }}>
          25 named agents.<br/>One NFT contract.<br/>Every vote on Base.
        </div>
        <a href="council.html" style={{
          display: 'inline-block', marginTop: 16, padding: '12px 22px',
          background: TM.orange, color: '#fff', borderRadius: 10,
          fontFamily: GE, fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
        }}>Enter the Council →</a>
      </div>

      <SectionHeader title="What you'll find"/>
      <div style={{ padding: '0 16px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[
          { k: 'ROSTER',      v: '25 named NFT cards — name, role, stake, accuracy, slash count' },
          { k: 'INDEPENDENCE', v: '25 × 25 agreement matrix proving the agents don\'t vote in lockstep' },
          { k: 'HEARTBEAT',   v: 'Daily nonce + 25 signed responses + 30-day calendar' },
          { k: 'SLASHING',    v: 'Public ledger of every wrong vote with on-chain transaction' },
          { k: 'LINEAGE',     v: 'The brand mark evolves each quarter, every version verifiable' },
          { k: 'VERIFY',      v: '6 code blocks anyone can run from a free RPC' },
        ].map(it => (
          <div key={it.k} style={{
            display: 'grid', gridTemplateColumns: '90px 1fr', gap: 14, alignItems: 'flex-start',
            padding: '10px 0', borderTop: `1px solid ${TM.border}`,
          }}>
            <span style={{ fontFamily: GM, fontSize: 10, color: TM.cyan, letterSpacing: 1, fontWeight: 600 }}>{it.k}</span>
            <span style={{ fontFamily: GE, fontSize: 13.5, color: TM.text, letterSpacing: -0.1, lineHeight: 1.5 }}>{it.v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
