// terminal-markets.jsx — Markets Overview screen.
// Categorized cards (Stocks · Commodities · Forex · Bonds · Crypto · ETFs).
// Each category has 3 tiles: price, delta, sparkline. Templated directly
// from the user's second screenshot.

function MarketTile({ tile, onClick }) {
  const color = tile.up ? TM.green : TM.red;
  return (
    <button onClick={onClick} style={{
      flex: 1, minWidth: 0, textAlign: 'left',
      padding: '12px 12px 6px',
      background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 10,
      display: 'flex', flexDirection: 'column', gap: 6, position: 'relative',
    }}>
      <div style={{
        fontFamily: GE, fontSize: 13, color: TM.muted,
        fontWeight: 500, letterSpacing: -0.1,
        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
      }}>{tile.name}</div>
      <div style={{
        fontFamily: GM, fontSize: 18, fontWeight: 600, color, letterSpacing: -0.3,
        lineHeight: 1.1,
      }}>{tile.base < 10 ? tile.price.toFixed(4) : tile.price.toLocaleString(undefined, { minimumFractionDigits: tile.base < 100 ? 2 : 2, maximumFractionDigits: 2 })}</div>
      <div style={{
        display: 'flex', gap: 8, alignItems: 'baseline',
        fontFamily: GM, fontSize: 11, color,
      }}>
        <span>{tile.up ? '+' : ''}{tile.delta}</span>
        <span>{tile.up ? '+' : ''}{tile.pct.toFixed(2)}%</span>
      </div>
      <div style={{ marginTop: 4 }}>
        <MiniSpark data={tile.spark} color={color} height={28}/>
      </div>
    </button>
  );
}

function MarketsScreen({ onOpenDetail }) {
  const [active, setActive] = React.useState('overview');
  const tabs = [
    { key: 'crypto',    label: 'Crypto' },
    { key: 'stocks',    label: 'Stocks' },
    { key: 'etfs',      label: 'ETFs' },
    { key: 'overview',  label: 'Overview' },
    { key: 'more',      label: 'More' },
  ];

  const filteredCategories = active === 'overview' || active === 'more'
    ? MARKET_CATEGORIES
    : MARKET_CATEGORIES.filter(c => c.key === active);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'auto' }} className="tx-scroll">
      {/* Top bar with AI chip */}
      <TopBar
        title="Markets"
        right={<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <AIButton/>
          <SearchButton/>
          <AccountButton/>
        </div>}
      />

      {/* Market holiday banner */}
      <div style={{
        margin: '10px 12px 0', padding: '10px 12px', borderRadius: 8,
        background: TM.orangeSoft, border: `1px solid rgba(255,106,26,0.30)`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontFamily: GE, fontSize: 13, color: TM.text, letterSpacing: -0.1,
      }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            width: 16, height: 16, borderRadius: 8,
            border: `1.4px solid ${TM.orange}`, color: TM.orange,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: GM, fontSize: 10, fontWeight: 600,
          }}>i</span>
          Market Holiday Schedule
        </span>
        <span style={{ color: TM.muted, fontSize: 16 }}>×</span>
      </div>

      {/* Pill scroller — category tabs */}
      <div style={{
        display: 'flex', gap: 4, padding: '14px 12px 4px',
        overflowX: 'auto', whiteSpace: 'nowrap',
      }} className="tx-scroll">
        {tabs.map(t => {
          const isActive = active === t.key;
          return (
            <button key={t.key} onClick={() => setActive(t.key)} style={{
              padding: '8px 14px',
              fontFamily: GE, fontSize: 16, fontWeight: isActive ? 600 : 400,
              color: isActive ? TM.text : TM.muted,
              borderBottom: isActive ? `2px solid ${TM.orange}` : '2px solid transparent',
              letterSpacing: -0.2,
            }}>{t.label}</button>
          );
        })}
      </div>

      {/* Category sections */}
      {filteredCategories.map(cat => (
        <div key={cat.key}>
          <SectionHeader title={cat.label} action="See all" onAction={() => {}}/>
          <div style={{ padding: '0 12px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {cat.items.map(item => {
              const tile = marketTileFor(item.sym);
              return <MarketTile key={item.sym} tile={tile} onClick={() => onOpenDetail && onOpenDetail(item.sym)}/>;
            })}
          </div>
        </div>
      ))}

      <div style={{ height: 16 }}/>
    </div>
  );
}

Object.assign(window, { MarketsScreen, MarketTile });
