/* picker.jsx — Market picker modal. Hyperliquid-style coin list with search,
   category tabs, and per-row mock metrics. Dims the screen behind. */

const { useState: pkUseState, useEffect: pkUseEffect, useMemo: pkUseMemo, useRef: pkUseRef } = React;

const CATEGORIES = [
  { id: 'all',       label: 'All' },
  { id: 'favorites', label: 'Favorites' },
  { id: 'crypto',    label: 'Crypto' },
  { id: 'rwa',       label: 'RWA' },
];

const SUBCATS = [
  { id: 'all',     label: 'All' },
  { id: 'majors',  label: 'Majors' },
  { id: 'defi',    label: 'Defi' },
  { id: 'l2',      label: 'Layer 2' },
  { id: 'memes',   label: 'Memes' },
  { id: 'rwa',     label: 'RWA' },
];

function fmtCompactUsd(n) {
  if (n == null) return '—';
  const abs = Math.abs(n);
  if (abs >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
  if (abs >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
  if (abs >= 1e3) return `$${(n / 1e3).toFixed(2)}K`;
  return `$${n.toFixed(2)}`;
}
function fmtPrice(n) {
  if (n >= 1000) return n.toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
  if (n >= 1)    return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 4 });
  return n.toFixed(4);
}

function PickerRow({ coin, isFav, onFav, onPick }) {
  const positive = coin.change24 >= 0;
  const bg = (window.COIN_COLORS && window.COIN_COLORS[coin.sym]) || '#666';
  const glyph = coin.sym === 'BTC' ? '₿' : coin.sym === 'ETH' ? 'Ξ' : coin.sym[0];
  const [imgFailed, setImgFailed] = pkUseState(false);
  const iconUrl = `https://assets.coincap.io/assets/icons/${coin.sym.toLowerCase()}@2x.png`;
  return (
    <div
      onClick={() => onPick(coin)}
      className="grid grid-cols-[20px_minmax(140px,1.5fr)_1fr_88px_1fr_1fr_1fr] items-center gap-3 px-5 h-[44px] hover:bg-bg-hover cursor-pointer hl-b"
    >
      <button
        onClick={(e) => { e.stopPropagation(); onFav(coin.sym); }}
        className={`w-4 h-4 flex items-center justify-center ${isFav ? 'text-amber' : 'text-text-3 hover:text-text-2'}`}
        aria-label={isFav ? 'Unfavorite' : 'Favorite'}
      >
        <svg width="14" height="14" viewBox="0 0 14 14" fill={isFav ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.2">
          <path d="M7 1.5l1.8 3.6 4 .6-2.9 2.8.7 4-3.6-1.9-3.6 1.9.7-4L1.2 5.7l4-.6L7 1.5z" />
        </svg>
      </button>
      <div className="flex items-center gap-2.5 min-w-0">
        {!imgFailed ? (
          <img src={iconUrl} alt={coin.sym} onError={() => setImgFailed(true)} style={{ width: 22, height: 22, borderRadius: 11, display: 'block' }} className="shrink-0" />
        ) : (
          <div className="w-[22px] h-[22px] rounded-full flex items-center justify-center shrink-0" style={{ background: bg }}>
            <span className="font-sans font-bold text-[11px] text-white leading-none">{glyph}</span>
          </div>
        )}
        <span className="font-sans text-[13px] text-text whitespace-nowrap">{coin.sym}</span>
        <span className="font-mono text-[10px] tracking-[0.06em] text-text-3 bg-bg-3 border border-line-3 px-1.5 h-[16px] inline-flex items-center rounded shrink-0">{coin.leverage}</span>
      </div>
      <div className="font-mono text-[12.5px] text-text text-right">{fmtPrice(coin.spot)}</div>
      <div className={`font-mono text-[12px] text-right ${positive ? 'text-green' : 'text-red'}`}>
        {positive ? '+' : ''}{coin.change24.toFixed(2)}%
      </div>
      <div className="font-mono text-[12.5px] text-text text-right">{fmtCompactUsd(coin.vol24)}</div>
      <div className="font-mono text-[12.5px] text-text text-right">{fmtCompactUsd(coin.oi)}</div>
      <div className={`font-mono text-[12px] text-right ${coin.funding >= 0 ? 'text-text-2' : 'text-red'}`}>
        {(coin.funding >= 0 ? '+' : '') + (coin.funding * 100).toFixed(4)}%
      </div>
    </div>
  );
}

function MarketPicker({ open, onClose, onPick, currentSym }) {
  const coins = window.TR.COINS;
  const [q, setQ] = pkUseState('');
  const [topTab, setTopTab] = pkUseState('all');
  const [subTab, setSubTab] = pkUseState('all');
  const [favs, setFavs] = pkUseState(() => new Set(['BTC', 'ETH']));
  const inputRef = pkUseRef(null);

  // Only depend on `open` so we don't keep wiping `q` on every parent re-render
  // (the live clock in TradeApp re-renders every second and would otherwise pass a
  //  fresh `onClose` identity into this effect, resetting the search field constantly).
  const onCloseRef = pkUseRef(onClose);
  pkUseEffect(() => { onCloseRef.current = onClose; }, [onClose]);
  pkUseEffect(() => {
    if (!open) return;
    setQ(''); setTopTab('all'); setSubTab('all');
    setTimeout(() => inputRef.current && inputRef.current.focus(), 60);
    const onKey = (e) => {
      if (e.key === 'Escape') { onCloseRef.current && onCloseRef.current(); e.preventDefault(); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  const filtered = pkUseMemo(() => {
    const qLow = q.trim().toLowerCase();
    return coins.filter(c => {
      if (topTab === 'favorites' && !favs.has(c.sym)) return false;
      if (topTab === 'crypto' && c.cat === 'rwa') return false;
      if (topTab === 'rwa' && c.cat !== 'rwa') return false;
      if (subTab !== 'all' && c.cat !== subTab) return false;
      if (qLow && !(c.sym.toLowerCase().includes(qLow) || c.name.toLowerCase().includes(qLow))) return false;
      return true;
    });
  }, [coins, q, topTab, subTab, favs]);

  const toggleFav = (sym) => {
    setFavs(prev => {
      const next = new Set(prev);
      if (next.has(sym)) next.delete(sym); else next.add(sym);
      return next;
    });
  };

  if (!open) return null;

  return (
    <div className="absolute inset-0 z-50 flex items-start justify-center pt-[80px]" onClick={onClose}>
      {/* Backdrop — dim + blur the screen behind */}
      <div className="absolute inset-0" style={{ background: 'rgba(0,0,0,0.62)', backdropFilter: 'blur(2px)' }} />

      {/* Modal */}
      <div
        onClick={(e) => e.stopPropagation()}
        className="relative bg-bg-1 border border-line-3 rounded-xl shadow-2xl w-[920px] max-h-[640px] flex flex-col overflow-hidden"
        style={{ boxShadow: '0 20px 60px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.04) inset' }}
      >
        {/* Search row */}
        <div className="h-[48px] px-4 flex items-center gap-3 hl-b shrink-0">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="#888" strokeWidth="1.4">
            <circle cx="6" cy="6" r="4.5" />
            <path d="M9.5 9.5L13 13" />
          </svg>
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Search"
            className="flex-1 bg-transparent border-0 outline-none font-sans text-[13.5px] text-text placeholder:text-text-3"
          />
          <div className="flex items-center gap-1.5 ml-2">
            {CATEGORIES.map(c => (
              <button
                key={c.id}
                onClick={() => setTopTab(c.id)}
                className={[
                  'h-[26px] px-3 rounded-full font-sans text-[12px] transition-colors',
                  topTab === c.id ? 'bg-bg-3 text-text border border-line-3' : 'text-text-2 hover:text-text border border-transparent'
                ].join(' ')}
              >{c.label}</button>
            ))}
          </div>
        </div>

        {/* Sub-cat row */}
        <div className="h-[40px] px-4 flex items-center gap-4 hl-b shrink-0 overflow-x-auto">
          <span className="font-sans text-[12.5px] text-emerald inline-flex items-center gap-1.5 shrink-0">
            Upcoming Earnings <span className="text-amber">📣</span>
          </span>
          <span className="text-line-3">·</span>
          {SUBCATS.map(s => (
            <button
              key={s.id}
              onClick={() => setSubTab(s.id)}
              className={[
                'font-sans text-[12.5px] shrink-0 pb-0.5',
                subTab === s.id ? 'text-text border-b border-text' : 'text-text-2 hover:text-text'
              ].join(' ')}
            >{s.label}</button>
          ))}
          <span className="text-line-3">·</span>
          <span className="font-sans text-[12.5px] text-text-2 shrink-0">AI</span>
          <span className="font-sans text-[12.5px] text-text-2 shrink-0">Equities</span>
          <span className="font-sans text-[12.5px] text-text-2 shrink-0">ETF/Index</span>
          <span className="font-sans text-[12.5px] text-text-2 shrink-0">FX</span>
        </div>

        {/* Column headers */}
        <div className="grid grid-cols-[20px_minmax(140px,1.5fr)_1fr_88px_1fr_1fr_1fr] items-center gap-3 px-5 h-[32px] hl-b shrink-0 font-sans text-[11px] text-text-3">
          <div />
          <div>Market</div>
          <div className="text-right">Last Price</div>
          <div className="text-right">24h</div>
          <div className="text-right">Volume</div>
          <div className="text-right inline-flex items-center gap-1 justify-end">Open Interest <span className="text-text-3">▾</span></div>
          <div className="text-right">8hr Funding</div>
        </div>

        {/* Rows */}
        <div className="flex-1 min-h-0 overflow-y-auto">
          {filtered.length === 0 ? (
            <div className="h-[120px] flex items-center justify-center font-sans text-[12.5px] text-text-3">No markets match "{q}"</div>
          ) : (
            filtered.map(c => (
              <PickerRow
                key={c.sym}
                coin={c}
                isFav={favs.has(c.sym)}
                onFav={toggleFav}
                onPick={(coin) => { onPick(coin); onClose(); }}
              />
            ))
          )}
        </div>

        {/* Footer — keyboard hints */}
        <div className="h-[40px] px-5 flex items-center gap-5 hl-t shrink-0 bg-bg-2">
          <span className="font-sans text-[11.5px] text-text-3">
            Open <kbd className="ml-1 inline-block px-1.5 py-0.5 font-mono text-[10.5px] bg-bg-3 border border-line-3 rounded text-text-2">⌘K</kbd>
          </span>
          <span className="font-sans text-[11.5px] text-text-3 inline-flex items-center gap-1.5">
            Navigate
            <kbd className="inline-block px-1.5 py-0.5 font-mono text-[10.5px] bg-bg-3 border border-line-3 rounded text-text-2">↑</kbd>
            <kbd className="inline-block px-1.5 py-0.5 font-mono text-[10.5px] bg-bg-3 border border-line-3 rounded text-text-2">↓</kbd>
          </span>
          <span className="font-sans text-[11.5px] text-text-3 inline-flex items-center gap-1.5">
            Select Market
            <kbd className="inline-block px-1.5 py-0.5 font-mono text-[10.5px] bg-bg-3 border border-line-3 rounded text-text-2">Enter</kbd>
            <kbd className="inline-block px-1.5 py-0.5 font-mono text-[10.5px] bg-bg-3 border border-line-3 rounded text-text-2">Space</kbd>
          </span>
          <span className="font-sans text-[11.5px] text-text-3 inline-flex items-center gap-1.5">
            Add to favorites
            <kbd className="inline-block px-1.5 py-0.5 font-mono text-[10.5px] bg-bg-3 border border-line-3 rounded text-text-2">F</kbd>
          </span>
          <span className="ml-auto font-sans text-[11.5px] text-text-3 inline-flex items-center gap-1.5">
            Close
            <kbd className="inline-block px-1.5 py-0.5 font-mono text-[10.5px] bg-bg-3 border border-line-3 rounded text-text-2">Esc</kbd>
          </span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MarketPicker });
