// terminal-search.jsx — Global search overlay.
// The search icon in any header opens this. Live-filters across all
// symbols, surfaces recent searches, and one-tap routes to Holding Detail.

const ALL_SYMS = [
  // Stocks
  { sym: 'AAPL', name: 'Apple Inc.',          kind: 'stock' },
  { sym: 'NVDA', name: 'NVIDIA',              kind: 'stock' },
  { sym: 'TSLA', name: 'Tesla',               kind: 'stock' },
  { sym: 'MSFT', name: 'Microsoft',           kind: 'stock' },
  { sym: 'GOOGL',name: 'Alphabet',            kind: 'stock' },
  { sym: 'AMZN', name: 'Amazon',              kind: 'stock' },
  { sym: 'META', name: 'Meta Platforms',      kind: 'stock' },
  { sym: 'GME',  name: 'GameStop',            kind: 'stock' },
  // Commodities
  { sym: 'WTI',  name: 'Crude Oil',           kind: 'commodity' },
  { sym: 'GOLD', name: 'Gold',                kind: 'commodity' },
  { sym: 'SILV', name: 'Silver',              kind: 'commodity' },
  // Forex
  { sym: 'DXY',     name: 'USD Index',        kind: 'forex' },
  { sym: 'XAU/USD', name: 'Gold / USD',       kind: 'forex' },
  { sym: 'EUR/USD', name: 'Euro / USD',       kind: 'forex' },
  // Bonds
  { sym: 'US2Y',  name: '2-Year Treasury',    kind: 'bond' },
  { sym: 'US5Y',  name: '5-Year Treasury',    kind: 'bond' },
  { sym: 'US10Y', name: '10-Year Treasury',   kind: 'bond' },
  // Crypto
  { sym: 'BTC', name: 'Bitcoin',              kind: 'crypto' },
  { sym: 'ETH', name: 'Ethereum',             kind: 'crypto' },
  { sym: 'SOL', name: 'Solana',               kind: 'crypto' },
  // ETFs
  { sym: 'SPY', name: 'S&P 500',              kind: 'etf' },
  { sym: 'QQQ', name: 'Nasdaq 100',           kind: 'etf' },
  { sym: 'IWM', name: 'Russell 2000',         kind: 'etf' },
];

const KIND_COLORS = {
  stock:     TM.cyan,
  commodity: TM.amber,
  forex:     TM.violet,
  bond:      TM.green,
  crypto:    TM.orange,
  etf:       TM.muted,
};

const KIND_LABELS = {
  stock:     'STOCK',
  commodity: 'CMDTY',
  forex:     'FX',
  bond:      'BOND',
  crypto:    'CRYPTO',
  etf:       'ETF',
};

function loadRecents() {
  try { return JSON.parse(localStorage.getItem('tx-recents') || '[]'); }
  catch { return []; }
}
function saveRecents(arr) {
  try { localStorage.setItem('tx-recents', JSON.stringify(arr.slice(0, 8))); } catch {}
}

function SearchScreen({ onOpenDetail, onClose }) {
  const [q, setQ] = React.useState('');
  const [recents, setRecents] = React.useState(loadRecents);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    inputRef.current && inputRef.current.focus();
  }, []);

  const trimmed = q.trim().toUpperCase();
  const matches = trimmed.length === 0 ? [] : ALL_SYMS.filter(s =>
    s.sym.includes(trimmed) || s.name.toUpperCase().includes(trimmed)
  ).slice(0, 12);

  const pickTrending = ['NVDA', 'BTC', 'TSLA', 'SPY', 'ETH', 'GOLD'].map(s =>
    ALL_SYMS.find(x => x.sym === s)).filter(Boolean);

  const onPick = (sym) => {
    const next = [sym, ...recents.filter(r => r !== sym)].slice(0, 8);
    setRecents(next);
    saveRecents(next);
    onOpenDetail(sym);
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: TM.surface }} className="tx-scroll">
      {/* Search bar — the whole top */}
      <div style={{
        padding: '14px 16px 12px',
        borderBottom: `1px solid ${TM.border}`,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <button onClick={onClose} style={{
          width: 32, height: 32, borderRadius: 16, 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 style={{
          flex: 1, display: 'flex', alignItems: 'center', gap: 8,
          background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 8,
          padding: '8px 12px',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <circle cx="11" cy="11" r="7" stroke={TM.muted} strokeWidth="1.6"/>
            <line x1="16" y1="16" x2="21" y2="21" stroke={TM.muted} strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)}
            placeholder="Search any symbol or name…"
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontFamily: GE, fontSize: 14, color: TM.text, letterSpacing: -0.1,
            }}/>
          {q && (
            <button onClick={() => setQ('')} style={{ color: TM.muted, fontSize: 16, lineHeight: 1 }}>×</button>
          )}
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }} className="tx-scroll">
        {trimmed.length > 0 ? (
          <>
            <SectionHeader title={`Results · ${matches.length}`}/>
            {matches.length === 0 ? (
              <div style={{ padding: '32px 16px', textAlign: 'center', color: TM.muted, fontFamily: GE, fontSize: 13 }}>
                No symbols match "{q}". Try a ticker like NVDA or BTC.
              </div>
            ) : matches.map(s => <SearchRow key={s.sym} entry={s} onClick={() => onPick(s.sym)}/>)}
          </>
        ) : (
          <>
            {recents.length > 0 && (
              <>
                <SectionHeader title="Recent"
                  action="Clear"
                  onAction={() => { setRecents([]); saveRecents([]); }}/>
                {recents.map(s => {
                  const entry = ALL_SYMS.find(x => x.sym === s);
                  if (!entry) return null;
                  return <SearchRow key={s} entry={entry} onClick={() => onPick(s)}/>;
                })}
              </>
            )}
            <SectionHeader title="Trending"/>
            {pickTrending.map(s => <SearchRow key={s.sym} entry={s} onClick={() => onPick(s.sym)} trending/>)}

            <SectionHeader title="Browse by category"/>
            <div style={{
              padding: '0 16px 16px',
              display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8,
            }}>
              {Object.keys(KIND_LABELS).map(k => (
                <div key={k} style={{
                  padding: '14px 8px',
                  background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 8,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                }}>
                  <span style={{
                    width: 8, height: 8, borderRadius: 4, background: KIND_COLORS[k],
                  }}/>
                  <span style={{ fontFamily: GM, fontSize: 10, color: TM.text, letterSpacing: 0.6 }}>{KIND_LABELS[k]}</span>
                  <span style={{ fontFamily: GE, fontSize: 11, color: TM.muted }}>
                    {ALL_SYMS.filter(s => s.kind === k).length}
                  </span>
                </div>
              ))}
            </div>
          </>
        )}
        <div style={{ height: 16 }}/>
      </div>
    </div>
  );
}

function SearchRow({ entry, onClick, trending = false }) {
  const tile = marketTileFor(entry.sym);
  const color = tile.up ? TM.green : TM.red;
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left',
      display: 'grid', gridTemplateColumns: '36px 1fr auto 90px', gap: 12, alignItems: 'center',
      padding: '12px 16px', borderBottom: `1px solid ${TM.border}`,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 18,
        background: KIND_COLORS[entry.kind] + '1a',
        border: `1px solid ${KIND_COLORS[entry.kind]}55`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: GM, fontSize: 10, fontWeight: 600,
        color: KIND_COLORS[entry.kind], letterSpacing: 0.3,
      }}>{entry.sym.slice(0, 3)}</div>
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontFamily: GE, fontSize: 14.5, fontWeight: 600, color: TM.text, letterSpacing: -0.2 }}>{entry.sym}</span>
          {trending && (
            <span style={{
              fontFamily: GM, fontSize: 9, color: TM.orange,
              padding: '1px 6px', border: `1px solid ${TM.orange}55`, borderRadius: 3,
              letterSpacing: 0.5, fontWeight: 600,
            }}>↑ TRENDING</span>
          )}
        </div>
        <div style={{ fontFamily: GE, fontSize: 12, color: TM.muted, marginTop: 2, letterSpacing: -0.05 }}>{entry.name}</div>
      </div>
      <Pill color={KIND_COLORS[entry.kind]} border={KIND_COLORS[entry.kind]}>{KIND_LABELS[entry.kind]}</Pill>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontFamily: GM, fontSize: 13, fontWeight: 600, color: TM.text, letterSpacing: -0.1 }}>
          {entry.kind === 'forex' || entry.sym === 'EUR/USD' ? tile.price.toFixed(4) : tile.price.toLocaleString(undefined, { maximumFractionDigits: 2 })}
        </div>
        <div style={{ fontFamily: GM, fontSize: 11, color, marginTop: 2 }}>
          {tile.up ? '+' : ''}{tile.pct.toFixed(2)}%
        </div>
      </div>
    </button>
  );
}

Object.assign(window, { SearchScreen, ALL_SYMS });
