// Variation 1: Classic Bloomberg Terminal
// Orange-on-black, 4-panel grid, tab bar, function-key legend
(() => {
  const { useState, useMemo, useEffect, useRef } = React;
  const { BlinkDot, Bar, fmt, useNow, clockStr, dateStr } = window;
  const D = window.TAM_DATA;

  // ═══ THEME ═══
  const theme = {
    bg: '#0a0a0a',
    panel: '#0f0f0f',
    panelAlt: '#141410',
    border: '#2a2a1a',
    text: '#e8c468',
    textDim: '#8a7a3e',
    textMute: '#5a4e28',
    accent: '#ff9933',
    accentBright: '#ffb84d',
    green: '#6ee26e',
    red: '#ff5c5c',
    blue: '#6aaaff',
    cyan: '#5ce6e6',
    magenta: '#e66ae6',
    headerBg: '#ff9933',
    headerText: '#000',
  };

  // ═══ COINGECKO LIVE PRICES ═══
  function useCoinGecko() {
    const [live, setLive] = useState(null);
    const [lastUpdate, setLastUpdate] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
      const ids = D.positions.map(p => p.coingeckoId).join(',');
      const url = `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd&include_24hr_change=true`;

      const fetchPrices = () => {
        fetch(url)
          .then(r => {
            if (!r.ok) throw new Error(`HTTP ${r.status}`);
            return r.json();
          })
          .then(data => { setLive(data); setLastUpdate(new Date()); setError(null); })
          .catch(e => { setError(e.message); });
      };

      fetchPrices();
      const id = setInterval(fetchPrices, 60_000);
      return () => clearInterval(id);
    }, []);

    const getPrice = (pos) => {
      if (!live || !live[pos.coingeckoId]) return { price: pos.price, change24h: pos.change24h };
      return {
        price: live[pos.coingeckoId].usd,
        change24h: live[pos.coingeckoId].usd_24h_change,
      };
    };

    return { live, lastUpdate, error, getPrice };
  }

  // ═══ HEADER ═══
  function Header({ tab, setTab, tabs }) {
    const now = useNow();
    return (
      <div style={{
        background: theme.headerBg, color: theme.headerText, display: 'flex',
        alignItems: 'stretch', fontSize: 11, fontWeight: 700, letterSpacing: '0.02em',
        textTransform: 'uppercase', borderBottom: `1px solid ${theme.border}`,
      }}>
        <div style={{ padding: '8px 14px', background: '#000', color: theme.accent, borderRight: `2px solid ${theme.accent}`, fontSize: 13 }}>
          ◆ TAM · TRADING AGENT MAREK
        </div>
        {tabs.map((t, i) => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 14px',
            background: tab === t.id ? '#000' : 'transparent',
            color: tab === t.id ? theme.accent : '#000',
            border: 'none',
            borderRight: `1px solid ${tab === t.id ? theme.border : 'rgba(0,0,0,0.2)'}`,
            cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 700,
            letterSpacing: '0.04em',
          }}>
            <span style={{ opacity: 0.6, marginRight: 5 }}>F{i + 1}</span>{t.label}
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <div style={{ padding: '8px 14px', display: 'flex', gap: 18, alignItems: 'center' }}>
          <span>CRYPTO 24/7</span>
          <BlinkDot color="#000" />
          <span>{clockStr(now)} UTC</span>
          <span>{dateStr(now)}</span>
        </div>
      </div>
    );
  }

  // ═══ FOOTER / STATUS BAR ═══
  function StatusBar({ coinError, lastUpdate }) {
    return (
      <div style={{
        background: '#000', borderTop: `1px solid ${theme.border}`,
        color: theme.textDim, fontSize: 10, padding: '5px 14px',
        display: 'flex', gap: 18, letterSpacing: '0.05em', textTransform: 'uppercase'
      }}>
        <span><span style={{ color: theme.accent }}>ALPACA</span> PAPER</span>
        <span>
          <span style={{ color: coinError ? theme.red : theme.accent }}>COINGECKO</span>
          {coinError
            ? <span style={{ color: theme.red }}> {coinError.slice(0, 20)}</span>
            : lastUpdate
              ? <span style={{ color: theme.green }}> {clockStr(lastUpdate)}</span>
              : <span style={{ color: theme.textDim }}> CONNECTING</span>
          }
        </span>
        <span><span style={{ color: theme.accent }}>GITHUB</span> PUSHED</span>
        <div style={{ flex: 1 }} />
        <span>ALLOW_LIVE=FALSE</span>
        <span>OPUS 4.7</span>
        <span>UPTIME 14D 12H</span>
      </div>
    );
  }

  // ═══ PANEL WRAPPER ═══
  function Panel({ title, children, actions, style, flex = 1 }) {
    return (
      <div style={{
        background: theme.panel, border: `1px solid ${theme.border}`,
        display: 'flex', flexDirection: 'column', overflow: 'hidden', flex,
        ...style
      }}>
        <div style={{
          background: theme.panelAlt, borderBottom: `1px solid ${theme.border}`,
          padding: '6px 10px', display: 'flex', alignItems: 'center', gap: 10,
          fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase',
          color: theme.accent,
        }}>
          <span>{title}</span>
          <div style={{ flex: 1 }} />
          {actions}
        </div>
        <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>{children}</div>
      </div>
    );
  }

  // ═══ METRIC DISPLAY ═══
  function Metric({ label, value, sub, subColor, color, big, size }) {
    return (
      <div>
        <div style={{ fontSize: 9, color: theme.textMute, letterSpacing: '0.1em' }}>{label}</div>
        <div style={{ fontSize: big ? 26 : (size || 20), color: color || theme.text, fontWeight: 700, lineHeight: 1, marginTop: 4 }}>{value}</div>
        {sub && <div style={{ fontSize: 10, color: subColor || theme.textDim, marginTop: 4, letterSpacing: '0.05em' }}>{sub}</div>}
      </div>
    );
  }

  // ═══ LIGHTWEIGHT CHARTS — equity curve ═══
  function ChartBig() {
    const containerRef = useRef(null);
    const chartRef = useRef(null);

    useEffect(() => {
      const el = containerRef.current;
      if (!el || !window.LightweightCharts) return;

      if (chartRef.current) { chartRef.current.remove(); chartRef.current = null; }

      const chart = window.LightweightCharts.createChart(el, {
        width: el.clientWidth,
        height: el.clientHeight || 180,
        layout: {
          background: { type: 'solid', color: 'transparent' },
          textColor: theme.textDim,
          fontFamily: '"JetBrains Mono", ui-monospace, monospace',
          fontSize: 10,
        },
        grid: {
          vertLines: { color: theme.border, style: 1 },
          horzLines: { color: theme.border, style: 1 },
        },
        crosshair: {
          mode: 1,
          vertLine: { color: theme.accent, labelBackgroundColor: theme.accent },
          horzLine: { color: theme.accent, labelBackgroundColor: theme.accent },
        },
        rightPriceScale: { borderColor: theme.border },
        timeScale: { borderColor: theme.border, timeVisible: true },
        handleScroll: true,
        handleScale: true,
      });
      chartRef.current = chart;

      // BTC benchmark (dim)
      const btcSeries = chart.addAreaSeries({
        lineColor: theme.textDim,
        lineWidth: 1,
        topColor: 'rgba(90,78,40,0.08)',
        bottomColor: 'rgba(90,78,40,0)',
        priceLineVisible: false,
        lastValueVisible: false,
      });
      btcSeries.setData(D.equityCurve.map(d => ({ time: d.date, value: d.spy })));

      // Portfolio (amber)
      const portSeries = chart.addAreaSeries({
        lineColor: theme.accent,
        lineWidth: 2,
        topColor: 'rgba(255,153,51,0.18)',
        bottomColor: 'rgba(255,153,51,0)',
        priceLineVisible: false,
        lastValueVisible: true,
      });
      portSeries.setData(D.equityCurve.map(d => ({ time: d.date, value: d.portfolio })));

      chart.timeScale().fitContent();

      const ro = new ResizeObserver(() => {
        if (el && chartRef.current) {
          chartRef.current.applyOptions({ width: el.clientWidth, height: el.clientHeight || 180 });
        }
      });
      ro.observe(el);

      return () => {
        ro.disconnect();
        if (chartRef.current) { chartRef.current.remove(); chartRef.current = null; }
      };
    }, []);

    return <div ref={containerRef} style={{ width: '100%', height: '100%', minHeight: 120 }} />;
  }

  // ═══ POSITIONS TABLE — crypto with live CoinGecko prices ═══
  function PositionsTable({ getPrice }) {
    function fmtQty(ticker, qty) {
      if (ticker === 'BTC') return qty.toFixed(4);
      if (['ETH', 'SOL'].includes(ticker)) return qty.toFixed(2);
      return qty.toLocaleString('en-US');
    }
    function fmtPx(ticker, price) {
      if (['DOGE'].includes(ticker)) return '$' + price.toFixed(4);
      if (price >= 1000) return '$' + price.toLocaleString('en-US', { maximumFractionDigits: 0 });
      return '$' + price.toFixed(2);
    }

    const rows = D.positions.map(p => {
      const { price, change24h } = getPrice ? getPrice(p) : { price: p.price, change24h: p.change24h };
      const mkt = p.qty * price;
      const cost = p.qty * p.avgCost;
      const upl = mkt - cost;
      const uplPct = upl / cost;
      return { ...p, livePrice: price, change24h, mkt, cost, upl, uplPct };
    });

    return (
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
        <thead>
          <tr style={{ color: theme.textMute, fontSize: 9, letterSpacing: '0.1em', textAlign: 'right' }}>
            <th style={{ textAlign: 'left', padding: '6px 10px', fontWeight: 400 }}>SYM</th>
            <th style={{ padding: '6px 6px', fontWeight: 400 }}>QTY</th>
            <th style={{ padding: '6px 6px', fontWeight: 400 }}>LAST</th>
            <th style={{ padding: '6px 6px', fontWeight: 400 }}>24h%</th>
            <th style={{ padding: '6px 6px', fontWeight: 400 }}>MKT VAL</th>
            <th style={{ padding: '6px 10px', fontWeight: 400 }}>U P/L %</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(r => (
            <tr key={r.ticker} style={{ borderTop: `1px solid ${theme.border}` }}>
              <td style={{ padding: '5px 10px', color: theme.accent, fontWeight: 700 }}>{r.ticker}</td>
              <td style={{ padding: '5px 6px', textAlign: 'right', color: theme.textDim }}>{fmtQty(r.ticker, r.qty)}</td>
              <td style={{ padding: '5px 6px', textAlign: 'right' }}>{fmtPx(r.ticker, r.livePrice)}</td>
              <td style={{ padding: '5px 6px', textAlign: 'right', color: r.change24h >= 0 ? theme.green : theme.red }}>
                {(r.change24h >= 0 ? '+' : '') + r.change24h.toFixed(2) + '%'}
              </td>
              <td style={{ padding: '5px 6px', textAlign: 'right' }}>{fmt.compact(r.mkt)}</td>
              <td style={{ padding: '5px 10px', textAlign: 'right', color: r.uplPct >= 0 ? theme.green : theme.red, fontWeight: 700 }}>{fmt.pct(r.uplPct)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }

  // ═══ ROUTINES LIST ═══
  function RoutinesList({ onRun }) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {D.routines.map(r => (
          <div key={r.id} style={{
            padding: '8px 12px', borderBottom: `1px solid ${theme.border}`,
            display: 'flex', alignItems: 'center', gap: 12, fontSize: 11,
          }}>
            <div style={{ width: 6, alignSelf: 'stretch',
              background: r.status === 'running' ? theme.green : r.status === 'scheduled' ? theme.accent : theme.border }} />
            <div style={{ flex: 1 }}>
              <div style={{ color: theme.text, fontWeight: 700 }}>{r.name}</div>
              <div style={{ color: theme.textDim, fontSize: 10, marginTop: 2 }}>{r.purpose}</div>
            </div>
            <div style={{ textAlign: 'right', fontSize: 10, color: theme.textDim, minWidth: 110 }}>
              <div style={{ color: theme.accent }}>{r.cron}</div>
              <div>NEXT · {r.nextRun}</div>
            </div>
            <button onClick={() => onRun(r.id)} style={{
              background: 'transparent', color: theme.accent, border: `1px solid ${theme.accent}`,
              padding: '4px 10px', fontFamily: 'inherit', fontSize: 10, fontWeight: 700,
              letterSpacing: '0.1em', cursor: 'pointer', textTransform: 'uppercase',
            }}>RUN</button>
          </div>
        ))}
      </div>
    );
  }

  // ═══ ACTIVITY FEED ═══
  function ActivityFeed() {
    const [items, setItems] = useState(D.activity);
    useEffect(() => {
      const id = setInterval(() => {
        setItems(prev => {
          const base = [...D.activity];
          const t = `15:3${Math.floor(Math.random() * 5)}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`;
          const pool = [
            { level: 'think', msg: 'Evaluating BTC on-chain NUPL — still in "belief" zone' },
            { level: 'info',  msg: 'Querying CoinGecko: 24h volume for SOL/LINK' },
            { level: 'ok',    msg: 'Memory sync complete: positions.md updated' },
            { level: 'info',  msg: 'Reading memory/learnings.md (AVAX unlock trap, line 8)' },
            { level: 'think', msg: 'ETH staking yield +0.2% this week — thesis strengthening' },
          ];
          const next = pool[Math.floor(Math.random() * pool.length)];
          return [...base.slice(-9), { t, routine: 'scan', ...next }];
        });
      }, 3800);
      return () => clearInterval(id);
    }, []);

    const levelColor = { info: theme.textDim, ok: theme.green, think: theme.cyan, act: theme.accent, warn: theme.red };

    return (
      <div style={{ padding: '6px 0', fontSize: 11, lineHeight: 1.5 }}>
        {items.slice(-10).map((it, i) => (
          <div key={i} style={{ padding: '2px 12px', display: 'flex', gap: 10 }}>
            <span style={{ color: theme.textMute, width: 64, flexShrink: 0 }}>{it.t}</span>
            <span style={{ color: levelColor[it.level], textTransform: 'uppercase', width: 48, fontSize: 10, flexShrink: 0 }}>{it.level}</span>
            <span style={{ color: theme.text }}>{it.msg}</span>
          </div>
        ))}
      </div>
    );
  }

  // ═══ TAB: DASHBOARD ═══
  function DashboardTab({ onRun }) {
    const { getPrice, lastUpdate, error } = useCoinGecko();
    const rm = D.riskMetrics;

    const dayPnl = 428.44;
    const dayPnlPct = 0.0042;

    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gridTemplateRows: '1fr 1fr', gap: 1, flex: 1, minHeight: 0, background: theme.border }}>

        {/* Portfolio vs BTC */}
        <Panel title="PORT · PORTFOLIO vs BTC BENCHMARK — 60D"
               actions={<span style={{ color: theme.textDim }}>60 DAYS · USD</span>}>
          <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 14, height: '100%' }}>
            {/* Top metrics row */}
            <div style={{ display: 'flex', gap: 28, flexWrap: 'nowrap' }}>
              <Metric label="TOTAL EQUITY" value={fmt.usd(D.totalEquity)} sub={`${fmt.pct(D.portfolioReturn)} SINCE LAUNCH`} subColor={D.portfolioReturn >= 0 ? theme.green : theme.red} big />
              <Metric label="BTC BENCHMARK" value={fmt.pct(D.btcBenchmarkReturn)} sub="BUY-AND-HOLD" subColor={theme.textDim} />
              <Metric label="ALPHA" value={fmt.pct(D.portfolioReturn - D.btcBenchmarkReturn)} sub="vs BTC" subColor={D.portfolioReturn > D.btcBenchmarkReturn ? theme.green : theme.red} color={D.portfolioReturn > D.btcBenchmarkReturn ? theme.green : theme.red} />
              <Metric label="TODAY" value={fmt.usd(dayPnl)} sub={fmt.pct(dayPnlPct)} subColor={theme.green} color={theme.green} />
              <Metric label="CASH" value={fmt.usd(D.cash)} sub={`${(D.cash / D.totalEquity * 100).toFixed(1)}% NAV`} subColor={theme.textDim} />
            </div>

            {/* Risk metrics row */}
            <div style={{ display: 'flex', gap: 20, borderTop: `1px solid ${theme.border}`, paddingTop: 10, flexWrap: 'nowrap' }}>
              <Metric
                label="SHARPE"
                value={rm.sharpe.toFixed(2)}
                sub={rm.sharpe > 1 ? 'GOOD' : rm.sharpe > 0.5 ? 'OK' : 'WEAK'}
                subColor={rm.sharpe > 1 ? theme.green : rm.sharpe > 0.5 ? theme.accent : theme.red}
                color={rm.sharpe > 1 ? theme.green : rm.sharpe > 0.5 ? theme.accent : theme.red}
                size={17}
              />
              <Metric label="SORTINO" value={rm.sortino.toFixed(2)} sub="DOWNSIDE-ADJ" subColor={theme.textDim} size={17} />
              <Metric
                label="MAX DD"
                value={`-${(rm.maxDD.value * 100).toFixed(1)}%`}
                sub={`PEAK ${rm.maxDD.peakDate}`}
                subColor={rm.maxDD.value < 0.05 ? theme.green : rm.maxDD.value < 0.10 ? theme.accent : theme.red}
                color={rm.maxDD.value < 0.05 ? theme.green : rm.maxDD.value < 0.10 ? theme.accent : theme.red}
                size={17}
              />
              <Metric label="CALMAR" value={rm.calmar.toFixed(2)} sub="RET / MAXDD" subColor={theme.textDim} size={17} />
              <Metric label="ANN VOL 14D" value={`${rm.rollingVol14.toFixed(1)}%`} sub="ROLLING" subColor={theme.textDim} size={17} />
            </div>

            {/* Chart */}
            <div style={{ flex: 1, minHeight: 0, position: 'relative' }}>
              <ChartBig />
            </div>
            <div style={{ fontSize: 10, display: 'flex', gap: 18, paddingTop: 2 }}>
              <span><span style={{ color: theme.accent }}>▬▬</span> TAM PORTFOLIO</span>
              <span><span style={{ color: theme.textDim }}>▬▬</span> BTC BENCHMARK</span>
              {error && <span style={{ color: theme.red }}>⚠ CoinGecko: {error}</span>}
            </div>
          </div>
        </Panel>

        {/* Positions */}
        <Panel title="POS · OPEN POSITIONS"
               actions={
                 <span style={{ color: lastUpdate ? theme.green : theme.textDim }}>
                   {lastUpdate ? `LIVE · ${clockStr(lastUpdate)}` : D.positions.length + ' HOLDINGS'}
                 </span>
               }>
          <PositionsTable getPrice={getPrice} />
        </Panel>

        {/* Routines */}
        <Panel title="RTN · SCHEDULED ROUTINES"
               actions={<span style={{ color: theme.textDim }}>5 ACTIVE · 24/7</span>}>
          <RoutinesList onRun={onRun} />
        </Panel>

        {/* Activity feed */}
        <Panel title="LOG · LIVE AGENT ACTIVITY"
               actions={<><BlinkDot color={theme.green} /><span style={{ color: theme.green, fontSize: 10 }}>SCAN RUNNING</span></>}>
          <ActivityFeed />
        </Panel>
      </div>
    );
  }

  // ═══ TAB: ROUTINES ═══
  function RoutinesTab() {
    const [sel, setSel] = useState('scan');
    const r = D.routines.find(x => x.id === sel);
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', gap: 1, flex: 1, background: theme.border, minHeight: 0 }}>
        <Panel title="RTN · ALL ROUTINES">
          {D.routines.map(r => (
            <button key={r.id} onClick={() => setSel(r.id)} style={{
              display: 'block', width: '100%', textAlign: 'left',
              background: sel === r.id ? theme.panelAlt : 'transparent',
              border: 'none', borderLeft: `3px solid ${sel === r.id ? theme.accent : 'transparent'}`,
              borderBottom: `1px solid ${theme.border}`,
              padding: '10px 12px', color: theme.text, fontFamily: 'inherit', cursor: 'pointer',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                {r.status === 'running' && <BlinkDot color={theme.green} />}
                <span style={{ color: sel === r.id ? theme.accent : theme.text, fontWeight: 700, fontSize: 12 }}>{r.name}</span>
              </div>
              <div style={{ fontSize: 10, color: theme.textDim, marginTop: 4 }}>{r.cron}</div>
            </button>
          ))}
        </Panel>
        <div style={{ display: 'grid', gridTemplateRows: 'auto 1fr auto', gap: 1, background: theme.border, minHeight: 0 }}>
          <Panel title={`RTN · ${r.name.toUpperCase()}`}
                 actions={
                   <div style={{ display: 'flex', gap: 8 }}>
                     <span style={{ color: r.status === 'running' ? theme.green : theme.textDim, textTransform: 'uppercase' }}>
                       {r.status === 'running' && <BlinkDot color={theme.green} />} {r.status}
                     </span>
                   </div>
                 }
                 style={{ maxHeight: 220 }}>
            <div style={{ padding: 16, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
              <Metric label="CRON" value={r.cron} sub="UTC 24/7" subColor={theme.textDim} />
              <Metric label="LAST RUN" value={r.lastRun} sub="COMPLETED · 0 ERR" subColor={theme.green} />
              <Metric label="NEXT RUN" value={r.nextRun} sub="SCHEDULED" subColor={theme.textDim} />
              <Metric label="AVG TOKENS" value={r.tokensAvg.toLocaleString()} sub={`~${Math.round(r.tokensAvg / 2000)}K CONTEXT`} subColor={theme.textDim} />
            </div>
          </Panel>
          <Panel title="RTN · AGENT TRANSCRIPT">
            <AgentTranscript />
          </Panel>
        </div>
      </div>
    );
  }

  function AgentTranscript() {
    const [visible, setVisible] = useState(0);
    useEffect(() => {
      setVisible(0);
      const id = setInterval(() => setVisible(v => v < D.agentThoughts.length ? v + 1 : v), 900);
      return () => clearInterval(id);
    }, []);

    return (
      <div style={{ padding: '12px 16px', fontSize: 12, lineHeight: 1.6, fontFamily: 'inherit' }}>
        {D.agentThoughts.slice(0, visible).map((m, i) => {
          const tag = { system: 'SYS', agent: 'TAM', tool: 'TOOL' }[m.role];
          const color = { system: theme.textDim, agent: theme.accent, tool: theme.cyan }[m.role];
          return (
            <div key={i} style={{ marginBottom: 10, display: 'flex', gap: 12 }}>
              <span style={{ color, fontWeight: 700, width: 52, flexShrink: 0, fontSize: 10, letterSpacing: '0.1em' }}>{tag}</span>
              <span style={{ color: m.role === 'tool' ? theme.cyan : theme.text, fontFamily: m.role === 'tool' ? 'ui-monospace' : 'inherit' }}>{m.content}</span>
            </div>
          );
        })}
        {visible < D.agentThoughts.length && (
          <div style={{ display: 'flex', gap: 12, color: theme.accent }}>
            <span style={{ width: 52, fontSize: 10 }}>TAM</span>
            <span>▎<span style={{ animation: 'tam-blink 1s infinite' }}>thinking…</span></span>
          </div>
        )}
      </div>
    );
  }

  // ═══ TAB: MEMORY FILES ═══
  function MemoryTab() {
    const [sel, setSel] = useState('CLAUDE.md');
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 1, flex: 1, background: theme.border, minHeight: 0 }}>
        <Panel title="MEM · FILE TREE" actions={<span style={{ color: theme.textDim }}>/memory</span>}>
          {D.memoryFiles.map(f => (
            <button key={f.name} onClick={() => setSel(f.name)} style={{
              display: 'block', width: '100%', textAlign: 'left',
              background: sel === f.name ? theme.panelAlt : 'transparent',
              border: 'none', borderLeft: `3px solid ${sel === f.name ? theme.accent : 'transparent'}`,
              borderBottom: `1px solid ${theme.border}`,
              padding: '8px 12px', color: theme.text, fontFamily: 'inherit', cursor: 'pointer', fontSize: 11,
            }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <span style={{ color: theme.accent }}>▸</span>
                <span style={{ color: sel === f.name ? theme.accent : theme.text, fontWeight: 700 }}>{f.name}</span>
                <div style={{ flex: 1 }} />
                <span style={{ color: theme.textMute, fontSize: 9 }}>{f.size}</span>
              </div>
              <div style={{ fontSize: 10, color: theme.textDim, marginTop: 2, paddingLeft: 16 }}>{f.desc}</div>
              <div style={{ fontSize: 9, color: theme.textMute, marginTop: 2, paddingLeft: 16 }}>updated {f.updated}</div>
            </button>
          ))}
        </Panel>
        <Panel title={`MEM · ${sel}`} actions={<span style={{ color: theme.textDim }}>READ-ONLY · AGENT WRITES</span>}>
          <pre style={{
            margin: 0, padding: 20, color: theme.text, fontSize: 12, lineHeight: 1.6,
            fontFamily: 'inherit', whiteSpace: 'pre-wrap',
          }}>{D.fileContents[sel] || '(no preview available)'}</pre>
        </Panel>
      </div>
    );
  }

  // ═══ TAB: TRADES ═══
  function TradesTab() {
    const [sel, setSel] = useState(0);
    const t = D.tradeLog[sel];

    function fmtTradeQty(ticker, qty) {
      if (qty === '—') return '—';
      if (ticker === 'BTC') return qty.toFixed ? qty.toFixed(4) : qty;
      if (['ETH', 'SOL'].includes(ticker)) return qty.toFixed ? qty.toFixed(2) : qty;
      return typeof qty === 'number' ? qty.toLocaleString('en-US') : qty;
    }

    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 1, flex: 1, background: theme.border, minHeight: 0 }}>
        <Panel title="TRD · TRADE HISTORY" actions={<span style={{ color: theme.textDim }}>{D.tradeLog.length} TRADES · 30D</span>}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
            <thead>
              <tr style={{ color: theme.textMute, fontSize: 9, letterSpacing: '0.1em' }}>
                <th style={{ textAlign: 'left', padding: '8px 12px', fontWeight: 400 }}>DATE</th>
                <th style={{ textAlign: 'left', padding: '8px 8px', fontWeight: 400 }}>TIME</th>
                <th style={{ textAlign: 'left', padding: '8px 8px', fontWeight: 400 }}>SIDE</th>
                <th style={{ textAlign: 'left', padding: '8px 8px', fontWeight: 400 }}>SYM</th>
                <th style={{ textAlign: 'right', padding: '8px 8px', fontWeight: 400 }}>QTY</th>
                <th style={{ textAlign: 'right', padding: '8px 12px', fontWeight: 400 }}>PRICE</th>
              </tr>
            </thead>
            <tbody>
              {D.tradeLog.map((t, i) => (
                <tr key={i} onClick={() => setSel(i)} style={{
                  borderTop: `1px solid ${theme.border}`,
                  background: sel === i ? theme.panelAlt : 'transparent',
                  cursor: 'pointer',
                }}>
                  <td style={{ padding: '7px 12px' }}>{t.date}</td>
                  <td style={{ padding: '7px 8px', color: theme.textDim }}>{t.time}</td>
                  <td style={{ padding: '7px 8px', color: t.action === 'BUY' ? theme.green : t.action === 'SELL' ? theme.red : theme.cyan, fontWeight: 700 }}>{t.action}</td>
                  <td style={{ padding: '7px 8px', color: theme.accent, fontWeight: 700 }}>{t.ticker}</td>
                  <td style={{ padding: '7px 8px', textAlign: 'right' }}>{fmtTradeQty(t.ticker, t.qty)}</td>
                  <td style={{ padding: '7px 12px', textAlign: 'right' }}>${typeof t.price === 'number' ? (t.price >= 100 ? t.price.toLocaleString('en-US', { maximumFractionDigits: 2 }) : t.price.toFixed(4)) : t.price}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Panel>
        <Panel title={`TRD · ${t.action} ${t.ticker}`}>
          <div style={{ padding: 20 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
              <Metric label="ACTION" value={t.action} color={t.action === 'BUY' ? theme.green : t.action === 'SELL' ? theme.red : theme.cyan} />
              <Metric label="SYMBOL" value={t.ticker} color={theme.accent} />
              <Metric label="QTY" value={String(t.qty)} />
              <Metric label="PRICE" value={`$${typeof t.price === 'number' ? t.price.toLocaleString('en-US', { maximumFractionDigits: 4 }) : t.price}`} />
              <Metric label="DATE" value={t.date} />
              <Metric label="TIME" value={t.time + ' UTC'} />
            </div>
            <div style={{ marginTop: 18 }}>
              <div style={{ fontSize: 10, color: theme.textMute, letterSpacing: '0.1em', marginBottom: 8 }}>AGENT REASONING</div>
              <div style={{
                padding: 14, border: `1px solid ${theme.border}`, borderLeft: `3px solid ${theme.accent}`,
                background: theme.panelAlt, fontSize: 12, lineHeight: 1.6, color: theme.text,
              }}>{t.reason}</div>
            </div>
            <div style={{ marginTop: 18, fontSize: 10, color: theme.textMute }}>
              <div>SOURCE: routines/{t.action === 'ADJUST' ? 'scan' : t.time < '12:00' ? 'morning-brief' : 'risk-review'}.md</div>
              <div>COMMIT: pushed to trading-routine/main</div>
            </div>
          </div>
        </Panel>
      </div>
    );
  }

  // ═══ TAB: GUARDRAILS ═══
  function GuardrailsTab() {
    const [g, setG] = useState(D.guardrails);
    const update = (k, v) => setG(prev => ({ ...prev, [k]: v }));

    const Row = ({ k, label, help, min = 0, max = 100, step = 0.5, unit = '%' }) => (
      <div style={{ padding: '16px 20px', borderBottom: `1px solid ${theme.border}`, display: 'grid', gridTemplateColumns: '1fr 200px auto', gap: 20, alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 12, color: theme.text, fontWeight: 700 }}>{label}</div>
          <div style={{ fontSize: 10, color: theme.textDim, marginTop: 4 }}>{help}</div>
        </div>
        <input type="range" min={min} max={max} step={step} value={g[k]} onChange={e => update(k, Number(e.target.value))} style={{ accentColor: theme.accent, width: '100%' }} />
        <div style={{ fontFamily: 'inherit', color: theme.accent, fontWeight: 700, fontSize: 16, minWidth: 80, textAlign: 'right' }}>{g[k]}{unit}</div>
      </div>
    );

    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 1, flex: 1, background: theme.border, minHeight: 0 }}>
        <Panel title="GRD · HARD RULES — AGENT CANNOT OVERRIDE">
          <Row k="maxPositionPct" label="Max position size" help="No single crypto holding larger than this % of equity." unit="%" min={1} max={50} step={1} />
          <Row k="dailyLossCapPct" label="Daily loss cap" help="If portfolio drops this much in 24h, agent stands down." unit="%" min={0.5} max={10} step={0.25} />
          <Row k="maxNewPerWeek" label="Max new positions / week" help="Prevents over-trading." unit="" min={1} max={8} step={1} />
          <Row k="initialStopPct" label="Initial trailing stop" help="Set on every new entry." unit="%" min={3} max={20} step={0.5} />
          <Row k="tightenAtGainPct" label="Tighten stop at gain" help="Unrealized gain % at which to tighten the trailing stop." unit="%" min={3} max={30} step={1} />
          <Row k="tightStopPct" label="Tightened stop" help="New trailing stop % once gain threshold hit." unit="%" min={2} max={15} step={0.5} />
          <Row k="minConfidencePct" label="Min confidence to trade" help="Below this, agent logs and waits." unit="%" min={50} max={95} step={5} />
          <div style={{ padding: '16px 20px', display: 'grid', gridTemplateColumns: '1fr auto', gap: 20, alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 12, color: theme.text, fontWeight: 700 }}>ALPACA_ALLOW_LIVE</div>
              <div style={{ fontSize: 10, color: theme.textDim, marginTop: 4 }}>Permanently false. Real-money trading disabled at env level. Cannot be overridden by agent.</div>
            </div>
            <div style={{
              background: theme.red, color: '#fff', padding: '6px 14px',
              fontFamily: 'inherit', fontWeight: 700, fontSize: 11, letterSpacing: '0.1em',
              opacity: 0.8,
            }}>FALSE — LOCKED</div>
          </div>
        </Panel>
        <Panel title="GRD · COMPILED RULES">
          <pre style={{ margin: 0, padding: 18, fontSize: 11, lineHeight: 1.7, color: theme.text, whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>{`# guardrails.md (auto-compiled)
# AGENT MUST OBEY.

max_position_pct      = ${g.maxPositionPct}
daily_loss_cap_pct    = ${g.dailyLossCapPct}
max_new_per_week      = ${g.maxNewPerWeek}
initial_stop_pct      = ${g.initialStopPct}
tighten_at_gain_pct   = ${g.tightenAtGainPct}
tight_stop_pct        = ${g.tightStopPct}
min_confidence_pct    = ${g.minConfidencePct}
allow_live            = false  # PERMANENT
paper_mode            = true

# No leverage. Ever.
# No margin.
# Stops are NON-NEGOTIABLE.
# DOGE/meme: max 5% combined.
# Anything < $500M market cap: SKIP.`}</pre>
        </Panel>
      </div>
    );
  }

  // ═══ TAB: RESEARCH ═══
  function ResearchTab() {
    return (
      <div style={{ flex: 1, padding: 1, background: theme.border, minHeight: 0, display: 'flex' }}>
        <Panel title="RSH · ON-CHAIN RESEARCH QUEUE" style={{ flex: 1 }}>
          <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
              { q: 'Bitcoin on-chain holder behavior May 2026',           when: '15:32:29', sources: 3, status: 'done' },
              { q: 'ETH Dencun fee burn weekly update',                   when: '08:00:12', sources: 4, status: 'done' },
              { q: 'Chainlink CCIP mainnet usage statistics',             when: '08:15:07', sources: 3, status: 'done' },
              { q: 'Solana DEX volume vs Ethereum DEX April 2026',        when: '12:00:31', sources: 5, status: 'done' },
              { q: 'Dogecoin X payments integration rumor factcheck',     when: '12:04:22', sources: 2, status: 'done' },
            ].map((r, i) => (
              <div key={i} style={{ border: `1px solid ${theme.border}`, padding: 14, background: theme.panelAlt }}>
                <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                  <span style={{ fontSize: 10, color: theme.textMute, width: 70 }}>{r.when}</span>
                  <span style={{ color: theme.accent, fontSize: 11 }}>▸ CoinGecko / Glassnode</span>
                  <span style={{ flex: 1, color: theme.text, fontSize: 12 }}>{r.q}</span>
                  <span style={{ color: theme.cyan, fontSize: 10 }}>{r.sources} SOURCES</span>
                  <span style={{ color: theme.green, fontSize: 10 }}>● {r.status.toUpperCase()}</span>
                </div>
              </div>
            ))}
          </div>
        </Panel>
      </div>
    );
  }

  // ═══ RUN MODAL ═══
  function RunModal({ id, onClose }) {
    const r = D.routines.find(x => x.id === id);
    const [step, setStep] = useState(0);
    const lines = [
      '$ claude code --routine ' + id + ' --remote',
      'cloning trading-routine@main ...',
      'spawning opus-4.7 agent ...',
      'reading memory/CLAUDE.md, memory/strategy.md, memory/guardrails.md',
      'reading memory/positions.md (6 crypto positions)',
      'GET alpaca paper /v2/account → equity $102,750',
      'GET alpaca paper /v2/positions → 6',
      'GET coingecko /simple/price?ids=bitcoin,ethereum,solana,chainlink,dogecoin,litecoin',
      'analyzing stop levels vs current prices ...',
      'BTC +17.0% unrealized → tighten stop 7% → 5%',
      'git commit -m "' + id + ' ' + new Date().toISOString().slice(0, 10) + '"',
      'DONE. tokens used: ' + r.tokensAvg.toLocaleString(),
    ];
    useEffect(() => {
      if (step < lines.length) {
        const t = setTimeout(() => setStep(s => s + 1), 350 + Math.random() * 400);
        return () => clearTimeout(t);
      }
    }, [step]);

    return (
      <div style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)', zIndex: 100,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <div style={{
          width: 720, maxHeight: '80vh', background: theme.bg, border: `1px solid ${theme.accent}`,
          color: theme.text, fontFamily: 'inherit', display: 'flex', flexDirection: 'column',
        }}>
          <div style={{
            background: theme.accent, color: '#000', padding: '8px 14px',
            display: 'flex', alignItems: 'center', fontSize: 11, fontWeight: 700, letterSpacing: '0.1em',
          }}>
            <span>▸ RUN NOW · {r.name.toUpperCase()}</span>
            <div style={{ flex: 1 }} />
            <button onClick={onClose} style={{ background: 'transparent', color: '#000', border: 'none', fontWeight: 700, fontSize: 14, cursor: 'pointer' }}>✕</button>
          </div>
          <div style={{ padding: 20, fontSize: 12, lineHeight: 1.8, minHeight: 400, maxHeight: '60vh', overflow: 'auto' }}>
            {lines.slice(0, step).map((l, i) => (
              <div key={i} style={{ color: l.startsWith('$') ? theme.accent : l.startsWith('BTC') || l.startsWith('DONE') ? theme.green : theme.text }}>{l}</div>
            ))}
            {step < lines.length && <div style={{ color: theme.accent }}>▎<span style={{ animation: 'tam-blink 1s infinite' }}>_</span></div>}
          </div>
          <div style={{ padding: 12, borderTop: `1px solid ${theme.border}`, display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
            <button onClick={onClose} style={{
              background: 'transparent', color: theme.accent, border: `1px solid ${theme.accent}`,
              padding: '6px 14px', fontFamily: 'inherit', fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', cursor: 'pointer',
            }}>{step >= lines.length ? 'CLOSE' : 'RUN IN BACKGROUND'}</button>
          </div>
        </div>
      </div>
    );
  }

  // ═══ APP ROOT ═══
  function TAM_V1() {
    const [tab, setTab] = useState('dashboard');
    const [runModal, setRunModal] = useState(null);
    const { error: coinError, lastUpdate } = useCoinGecko();

    const tabs = [
      { id: 'dashboard', label: 'Dashboard' },
      { id: 'routines',  label: 'Routines' },
      { id: 'trades',    label: 'Trades' },
      { id: 'memory',    label: 'Memory' },
      { id: 'research',  label: 'Research' },
      { id: 'guardrails',label: 'Guardrails' },
    ];

    return (
      <div style={{
        width: '100%', height: '100%', background: theme.bg, color: theme.text,
        fontFamily: '"JetBrains Mono", "Berkeley Mono", "IBM Plex Mono", ui-monospace, monospace',
        fontSize: 12, display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <Header tab={tab} setTab={setTab} tabs={tabs} />
        <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
          {tab === 'dashboard'  && <DashboardTab onRun={id => setRunModal(id)} />}
          {tab === 'routines'   && <RoutinesTab />}
          {tab === 'trades'     && <TradesTab />}
          {tab === 'memory'     && <MemoryTab />}
          {tab === 'research'   && <ResearchTab />}
          {tab === 'guardrails' && <GuardrailsTab />}
        </div>
        <StatusBar coinError={coinError} lastUpdate={lastUpdate} />
        {runModal && <RunModal id={runModal} onClose={() => setRunModal(null)} />}
      </div>
    );
  }

  window.TAM_V1 = TAM_V1;
})();
