// Stock detail page — wired to live Stacks JSE API
window.StockPage = ({ currency, symbol, setPage, livePrices }) => {
  const { bySym, dividends } = JASTOCKS_DATA;
  const stockBase = bySym[symbol];

  const [range, setRange] = React.useState('3M');
  const chartMode = 'line'; // candles removed — API only provides closing prices
  const [tab, setTab] = React.useState('overview');

  // Per-stock data (fetched on mount / symbol change)
  const [stockDetail, setStockDetail] = React.useState(null);
  const [history, setHistory] = React.useState([]);
  const [orderBook, setOrderBook] = React.useState(null);
  const [obAnalysis, setObAnalysis] = React.useState(null);
  const [stockDivs, setStockDivs] = React.useState([]);
  const [financials, setFinancials] = React.useState(null);
  const [directors, setDirectors] = React.useState([]);

  const [loadingHistory, setLoadingHistory] = React.useState(true);
  const [loadingOB, setLoadingOB] = React.useState(true);
  const [loadingDetail, setLoadingDetail] = React.useState(true);

  // Income calculator state
  const [calcShares, setCalcShares] = React.useState('');
  const [calcCost, setCalcCost] = React.useState(''); // optional avg cost per share

  // Fetch stock detail + dividends + directors in parallel on mount
  React.useEffect(() => {
    setLoadingDetail(true);
    setStockDetail(null);
    setStockDivs([]);
    setDirectors([]);
    setFinancials(null);

    Promise.allSettled([
      JaAPI.stock(symbol),
      JaAPI.stockDividends(symbol, 12),
      JaAPI.directors(symbol),
      JaAPI.financials(symbol),
    ]).then(([detailRes, divsRes, dirsRes, finRes]) => {
      if (detailRes.status === 'fulfilled' && detailRes.value) {
        const peMap = {};
        const d = detailRes.value;
        setStockDetail(JaAPI.transformStock(d, peMap));
      }
      if (divsRes.status === 'fulfilled') {
        setStockDivs((divsRes.value.dividends || []).map(d => JaAPI.transformDiv(d)).filter(Boolean));
      }
      if (dirsRes.status === 'fulfilled') {
        setDirectors(dirsRes.value.directors || []);
      }
      if (finRes.status === 'fulfilled') {
        setFinancials(finRes.value);
      }
      setLoadingDetail(false);
    });
  }, [symbol]);

  // Fetch history whenever range changes
  React.useEffect(() => {
    setLoadingHistory(true);
    setHistory([]);
    const days = range === '1W' ? 7 : range === '1M' ? 30 : range === '3M' ? 90 : range === '6M' ? 180 : 365;
    JaAPI.history(symbol, days).then(res => {
      setHistory(JaAPI.transformHistory(res));
      setLoadingHistory(false);
    }).catch(() => setLoadingHistory(false));
  }, [symbol, range]);

  // Fetch order book once
  React.useEffect(() => {
    setLoadingOB(true);
    setOrderBook(null);
    setObAnalysis(null);
    Promise.allSettled([
      JaAPI.orderbook(symbol),
      JaAPI.orderbookAnalysis(symbol),
    ]).then(([obRes, anaRes]) => {
      if (obRes.status === 'fulfilled') setOrderBook(obRes.value);
      if (anaRes.status === 'fulfilled') setObAnalysis(anaRes.value.analysis);
      setLoadingOB(false);
    });
  }, [symbol]);

  // Use live price if available, fall back to stockDetail, then bySym
  const liveData = livePrices[symbol];
  const stock = React.useMemo(() => {
    const base = stockDetail || stockBase || {};
    if (liveData) {
      return { ...base, price: liveData.price, change: liveData.change, changePct: liveData.changePct };
    }
    return base;
  }, [stockDetail, stockBase, liveData]);

  if (!stock || !stock.sym) {
    return (
      <div className="page" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 400 }}>
        <div style={{ color: 'var(--text-3)' }}>Stock not found: {symbol}</div>
      </div>
    );
  }

  const up = (stock.change || 0) >= 0;

  // Order book stats
  const buyPct = obAnalysis?.pressure?.buy_pct
    ?? (orderBook?.summary ? orderBook.summary.buy_percentage : null)
    ?? 50;
  const sellPct = 100 - buyPct;

  // Next dividend from global dividends list
  const nextDiv = dividends.filter(d => d.sym === symbol).sort((a, b) => a.exDate - b.exDate)[0];

  return (
    <div className="page">
      {/* Header */}
      <div className="page-header">
        <div className="flex items-center gap-4">
          <button className="btn ghost sm" onClick={() => setPage('stocks')}>‹ Stocks</button>
          <SymBadge sym={symbol} size={44}/>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="page-title" style={{ margin: 0 }}>{symbol}</h1>
              <span className={`tag ${stock.market === 'Junior' ? 'junior' : 'main'}`}>{stock.market}</span>
              <span className="tag">{stock.sector}</span>
            </div>
            <div className="page-subtitle">{stock.name}</div>
          </div>
        </div>
        <div className="flex gap-2 items-center">
          <button className="btn ghost"><Icons.Star/> Watchlist</button>
          <button className="btn"><Icons.Bell/> Alert</button>
        </div>
      </div>

      {/* Price header */}
      {loadingDetail ? (
        <div className="flex items-end gap-4 mb-4" style={{ padding: '0 4px' }}>
          <Skeleton h={48} w={180}/>
          <Skeleton h={24} w={140}/>
        </div>
      ) : (
        <div className="flex items-end gap-4 mb-4" style={{ padding: '0 4px' }}>
          <div className="mono" style={{ fontSize: 40, fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1 }}>
            {fmtPrice(stock.price || 0, currency)}
          </div>
          <div style={{ paddingBottom: 6 }}>
            <div className={`mono ${up ? 'up' : 'down'}`} style={{ fontSize: 16, fontWeight: 600 }}>
              {up ? '▲' : '▼'} {fmtPrice(Math.abs(stock.change || 0), currency)} ({fmtPct(stock.changePct || 0)})
            </div>
            <div className="text-3" style={{ fontSize: 11.5, marginTop: 2 }}>
              {stock.dataType === 'intraday' ? 'Live intraday' : 'Last close'} · {stock.lastUpdated ? new Date(stock.lastUpdated).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }) : ''}
            </div>
          </div>
          <div style={{ flex: 1 }}/>
          {stock.prev > 0 && (
            <div className="text-3 mono" style={{ fontSize: 11.5 }}>
              Prev close {fmtPrice(stock.prev, currency)}
              {stock.bid > 0 && ` · Bid ${fmtPrice(stock.bid, currency)}`}
              {stock.ask > 0 && ` · Ask ${fmtPrice(stock.ask, currency)}`}
            </div>
          )}
        </div>
      )}

      {/* Price chart */}
      <div className="card mb-4">
        <div className="card-header">
          <div className="flex items-center gap-3">
            <div className="seg">
              {['1W', '1M', '3M', '6M', '1Y'].map(r => (
                <button key={r} className={range === r ? 'active' : ''} onClick={() => setRange(r)}>{r}</button>
              ))}
            </div>
          </div>
          <div className="text-3 mono" style={{ fontSize: 11 }}>
            {loadingHistory ? 'Loading…' : `${history.length} trading days`}
          </div>
        </div>
        <div style={{ padding: '8px 8px 0' }}>
          {loadingHistory ? (
            <div style={{ height: 420, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <span style={{ color: 'var(--text-3)', fontSize: 13 }}>Loading chart data…</span>
            </div>
          ) : (
            <Candlestick data={history} height={420} mode={chartMode}/>
          )}
        </div>
      </div>

      {/* Dividend Income Calculator */}
      {(() => {
        const SPECIAL_TYPES = ['special', 'return of capital', 'bonus'];
        const oneYearAgo = new Date(JASTOCKS_DATA.today); oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
        const regularDivs = stockDivs.filter(d => !SPECIAL_TYPES.includes(d.type.toLowerCase()) && d.exDate >= oneYearAgo);
        const ttmPerShare = regularDivs.reduce((s, d) => s + d.amount, 0);
        const shares = parseFloat(calcShares) || 0;
        const costPerShare = parseFloat(calcCost) || 0;
        const annualIncome = ttmPerShare * shares;
        const nextPayment = nextDiv ? nextDiv.amount * shares : 0;
        const yieldOnCost = costPerShare > 0 ? (ttmPerShare / costPerShare * 100) : null;
        const currentYield = stock.price > 0 && ttmPerShare > 0 ? (ttmPerShare / stock.price * 100) : null;

        return (
          <div className="calc-card mb-4">
            <div className="flex items-center justify-between" style={{ flexWrap: 'wrap', gap: 12 }}>
              <div>
                <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 2 }}>Income Calculator</div>
                <div className="text-3" style={{ fontSize: 12 }}>
                  {ttmPerShare > 0
                    ? `Based on J$${ttmPerShare.toFixed(4)}/share in regular dividends (TTM)`
                    : 'No regular dividend history available yet'}
                </div>
              </div>
              <div className="flex gap-2" style={{ flexWrap: 'wrap' }}>
                <div>
                  <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Shares held</div>
                  <input
                    type="number" min="0" placeholder="e.g. 1000"
                    value={calcShares}
                    onChange={e => setCalcShares(e.target.value)}
                    style={{
                      width: 130, padding: '7px 10px',
                      background: 'var(--bg-1)', border: '1px solid var(--border)',
                      borderRadius: 7, color: 'var(--text)', fontSize: 13,
                      fontFamily: 'Geist Mono, monospace',
                    }}
                  />
                </div>
                <div>
                  <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 4 }}>Avg cost/share (optional)</div>
                  <input
                    type="number" min="0" placeholder="e.g. 80.00"
                    value={calcCost}
                    onChange={e => setCalcCost(e.target.value)}
                    style={{
                      width: 150, padding: '7px 10px',
                      background: 'var(--bg-1)', border: '1px solid var(--border)',
                      borderRadius: 7, color: 'var(--text)', fontSize: 13,
                      fontFamily: 'Geist Mono, monospace',
                    }}
                  />
                </div>
              </div>
            </div>

            {shares > 0 && ttmPerShare > 0 && (
              <div className="calc-grid">
                <div className="calc-stat">
                  <div className="lbl">Annual income</div>
                  <div className="val">{fmtPrice(annualIncome, 'JMD')}</div>
                  <div className="sub">J${ttmPerShare.toFixed(4)}/share × {fmtNum(shares)} shares</div>
                </div>
                <div className="calc-stat">
                  <div className="lbl">Monthly (est.)</div>
                  <div className="val">{fmtPrice(annualIncome / 12, 'JMD')}</div>
                  <div className="sub">Based on TTM payments</div>
                </div>
                <div className="calc-stat">
                  <div className="lbl">Next payment</div>
                  <div className="val">{nextPayment > 0 ? fmtPrice(nextPayment, 'JMD') : '—'}</div>
                  <div className="sub">{nextDiv ? `Ex ${fmtDate(nextDiv.exDate)} · J$${nextDiv.amount.toFixed(4)}/sh` : 'No upcoming dividend declared'}</div>
                </div>
                <div className="calc-stat">
                  <div className="lbl">Current yield</div>
                  <div className="val">{currentYield ? `${currentYield.toFixed(2)}%` : '—'}</div>
                  <div className="sub">Based on today's price</div>
                </div>
                {yieldOnCost !== null && (
                  <div className="calc-stat">
                    <div className="lbl">Yield on cost</div>
                    <div className="val" style={{ color: yieldOnCost >= (currentYield || 0) ? 'var(--up)' : 'var(--down)' }}>
                      {yieldOnCost.toFixed(2)}%
                    </div>
                    <div className="sub">Based on J${costPerShare.toFixed(2)} avg cost</div>
                  </div>
                )}
                <div className="calc-stat">
                  <div className="lbl">Holdings value</div>
                  <div className="val">{fmtPrice(stock.price * shares, 'JMD')}</div>
                  <div className="sub">At current price J${stock.price.toFixed(2)}</div>
                </div>
              </div>
            )}

            {shares > 0 && ttmPerShare === 0 && (
              <div style={{ marginTop: 14, color: 'var(--text-3)', fontSize: 13 }}>
                No regular dividend history found for {symbol} — calculator unavailable.
              </div>
            )}
          </div>
        );
      })()}

      {/* Stats + Order book */}
      <div className="grid mb-4" style={{ gridTemplateColumns: '2fr 1fr', gap: 16 }}>
        <div className="card">
          <div className="card-header">
            <div className="card-title">Key statistics</div>
            <div className="seg">
              {['overview', 'financials', 'directors'].map(t => (
                <button key={t} className={tab === t ? 'active' : ''} onClick={() => setTab(t)}
                        style={{ textTransform: 'capitalize' }}>{t}</button>
              ))}
            </div>
          </div>
          <div style={{ padding: 4 }}>
            {tab === 'overview' && (
              <div className="grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)', gap: 1, background: 'var(--border)' }}>
                {[
                  ['P/E ratio', stock.pe ? stock.pe.toFixed(1) : '—'],
                  ['Div yield', stock.yield > 0 ? <span style={{color:'var(--accent)'}}>{stock.yield.toFixed(2)}%</span> : '—'],
                  ['52-wk range', stock.range52?.[1] > 0
                    ? <Range52 low={stock.range52[0]} high={stock.range52[1]} current={stock.price} currency={currency}/>
                    : stock.week52 || '—'],
                  ['Volume', fmtNum(stock.volume)],
                  ['Bid', stock.bid > 0 ? fmtPrice(stock.bid, currency) : '—'],
                  ['Ask', stock.ask > 0 ? fmtPrice(stock.ask, currency) : '—'],
                  ['Today\'s range', stock.todayRange || '—'],
                  ['Prev close', stock.prev > 0 ? fmtPrice(stock.prev, currency) : '—'],
                  ['Div/share (TTM)', stock.divPerShare > 0 ? fmtPrice(stock.divPerShare, currency) : '—'],
                ].map(([label, val], i) => (
                  <div key={i} style={{ background: 'var(--bg-1)', padding: '14px 18px' }}>
                    <div className="text-3" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</div>
                    <div className="mono" style={{ fontSize: 15, marginTop: 4, fontWeight: 500 }}>{val}</div>
                  </div>
                ))}
              </div>
            )}

            {tab === 'financials' && (
              <div style={{ padding: 18 }}>
                {financials ? (
                  <FinancialsView data={financials} currency={currency}/>
                ) : (
                  <div className="text-3" style={{ textAlign: 'center', padding: 30 }}>
                    {loadingDetail ? 'Loading financials…' : 'No financial data available'}
                  </div>
                )}
              </div>
            )}

            {tab === 'directors' && (
              <div>
                {directors.length > 0 ? directors.map((d, i) => (
                  <div key={i} style={{ padding: '12px 16px', borderBottom: i < directors.length - 1 ? '1px solid var(--border)' : 'none' }}>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{d.name}</div>
                    <div className="text-3" style={{ fontSize: 11.5, marginTop: 2 }}>{d.title}</div>
                  </div>
                )) : (
                  <div className="text-3" style={{ textAlign: 'center', padding: 30 }}>
                    {loadingDetail ? 'Loading directors…' : 'No director data available'}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Order book */}
        <div className="card">
          <div className="card-header">
            <div className="card-title">Order book</div>
            <span className="text-3 mono" style={{ fontSize: 11 }}>
              {loadingOB ? 'Loading…' : 'Level 2'}
            </span>
          </div>
          <div style={{ padding: 14 }}>
            {loadingOB ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[...Array(5)].map((_, i) => <Skeleton key={i} h={24}/>)}
              </div>
            ) : orderBook ? (
              <>
                <div className="flex items-center justify-between mb-2">
                  <span className="up mono" style={{ fontSize: 12 }}>{buyPct.toFixed(0)}% buy</span>
                  <span className="down mono" style={{ fontSize: 12 }}>{sellPct.toFixed(0)}% sell</span>
                </div>
                <div className="pressure-bar mb-3">
                  <div className="p-buy" style={{ width: `${buyPct}%` }}/>
                  <div className="p-sell" style={{ flex: 1 }}/>
                </div>
                {obAnalysis && (
                  <div className="flex justify-between mb-3" style={{ fontSize: 11 }}>
                    <div>
                      <div className="text-3" style={{ fontSize: 10, textTransform: 'uppercase' }}>Best Bid</div>
                      <div className="mono up">{obAnalysis.spread?.best_bid?.toFixed(2) ?? '—'}</div>
                    </div>
                    <div style={{ textAlign: 'center' }}>
                      <div className="text-3" style={{ fontSize: 10, textTransform: 'uppercase' }}>Spread</div>
                      <div className="mono">{obAnalysis.spread?.spread_pct ? obAnalysis.spread.spread_pct.toFixed(2) + '%' : '—'}</div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div className="text-3" style={{ fontSize: 10, textTransform: 'uppercase' }}>Best Ask</div>
                      <div className="mono down">{obAnalysis.spread?.best_ask?.toFixed(2) ?? '—'}</div>
                    </div>
                  </div>
                )}
                <table className="data" style={{ fontSize: 11.5 }}>
                  <thead><tr>
                    <th>Bid</th><th style={{textAlign:'right'}}>Size</th>
                    <th style={{textAlign:'right'}}>Size</th><th style={{textAlign:'right'}}>Ask</th>
                  </tr></thead>
                  <tbody>
                    {(orderBook.buy_orders || []).slice(0, 6).map((b, i) => {
                      const a = (orderBook.sell_orders || [])[i];
                      return (
                        <tr key={i}>
                          <td className="mono up" style={{ padding: '6px 8px' }}>{b.price?.toFixed(2) ?? '—'}</td>
                          <td className="mono" style={{ textAlign: 'right', padding: '6px 8px' }}>{fmtNum(b.quantity || 0)}</td>
                          <td className="mono" style={{ textAlign: 'right', padding: '6px 8px' }}>{a ? fmtNum(a.quantity || 0) : '—'}</td>
                          <td className="mono down" style={{ textAlign: 'right', padding: '6px 8px' }}>{a ? a.price?.toFixed(2) : '—'}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
                {obAnalysis?.imbalance && (
                  <div className="flex items-center justify-between mt-3" style={{ padding: '10px 0', borderTop: '1px solid var(--border)', fontSize: 12 }}>
                    <span className="text-3">Imbalance</span>
                    <span className="mono" style={{ color: obAnalysis.imbalance.score > 0 ? 'var(--up)' : obAnalysis.imbalance.score < 0 ? 'var(--down)' : 'var(--text-2)' }}>
                      {obAnalysis.imbalance.label}
                    </span>
                  </div>
                )}
              </>
            ) : (
              <div className="text-3" style={{ textAlign: 'center', padding: 20, fontSize: 12 }}>
                No order book data for today
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Dividend history */}
      <div className="card">
        <div className="card-header">
          <div className="card-title">
            Dividend history
            {(() => {
              // Compute trailing yield from regular dividends only (exclude Special / Return of Capital)
              const SPECIAL_TYPES = ['special', 'return of capital', 'bonus'];
              const regularDivs = stockDivs.filter(d => !SPECIAL_TYPES.includes(d.type.toLowerCase()));
              const oneYearAgo = new Date(JASTOCKS_DATA.today); oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
              const ttmDivs = regularDivs.filter(d => d.exDate >= oneYearAgo);
              const ttmTotal = ttmDivs.reduce((s, d) => s + d.amount, 0);
              const price = stock.price;
              if (ttmTotal > 0 && price > 0) {
                const yld = (ttmTotal / price * 100).toFixed(2);
                const hasSpecial = stockDivs.some(d => SPECIAL_TYPES.includes(d.type.toLowerCase()));
                return (
                  <span className="hint">
                    Trailing yield {yld}% (regular divs only{hasSpecial ? ' · special dividends excluded' : ''})
                  </span>
                );
              }
              return null;
            })()}
          </div>
          {nextDiv && (
            <span className="tag ex">
              Next ex-date {fmtDate(nextDiv.exDate)} · {fmtPrice(nextDiv.amount, currency)}/share
            </span>
          )}
        </div>
        {stockDivs.length > 0 ? (
          <table className="data">
            <thead>
              <tr>
                <th>Ex-date</th>
                <th>Payment date</th>
                <th>Type</th>
                <th style={{textAlign:'right'}}>Per share</th>
                <th style={{textAlign:'right'}}>Growth YoY</th>
              </tr>
            </thead>
            <tbody>
              {stockDivs.map((d, i) => {
                const SPECIAL_TYPES = ['special', 'return of capital', 'bonus'];
                const isSpecial = SPECIAL_TYPES.includes(d.type.toLowerCase());
                // YoY growth only meaningful between same dividend types
                const prev = stockDivs.slice(i + 1).find(p => p.type === d.type);
                const growth = prev ? ((d.amount - prev.amount) / prev.amount * 100) : null;
                return (
                  <tr key={i} style={isSpecial ? { background: 'var(--bg-2)' } : {}}>
                    <td className="mono">{fmtDateFull(d.exDate)}</td>
                    <td className="mono text-2">{d.payDate ? fmtDateFull(d.payDate) : <span className="text-3">TBA</span>}</td>
                    <td>
                      <span className={`tag ${isSpecial ? 'ex' : ''}`}>{d.type}</span>
                      {isSpecial && <span className="text-3 mono" style={{ fontSize: 10, marginLeft: 6 }}>excl. from yield</span>}
                    </td>
                    <td className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>
                      {fmtPrice(d.amount, currency)}
                      {d.currency === 'USD' && <span className="text-3" style={{ fontSize: 10, marginLeft: 4 }}>USD</span>}
                    </td>
                    <td className="mono" style={{ textAlign: 'right' }}>
                      {isSpecial
                        ? <span className="text-3" style={{ fontSize: 11 }}>one-time</span>
                        : growth !== null
                          ? <span className={growth >= 0 ? 'up' : 'down'}>{growth >= 0 ? '+' : ''}{growth.toFixed(1)}%</span>
                          : <span className="text-3">—</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        ) : (
          <div className="text-3" style={{ textAlign: 'center', padding: 30, fontSize: 13 }}>
            {loadingDetail ? 'Loading dividend history…' : 'No dividend history on record'}
          </div>
        )}
      </div>
    </div>
  );
};

// 52-week range bar
function Range52({ low, high, current, currency }) {
  const pct = high > low ? ((current - low) / (high - low)) * 100 : 50;
  return (
    <div style={{ minWidth: 140 }}>
      <div style={{ position: 'relative', height: 4, background: 'var(--bg-3)', borderRadius: 2, marginBottom: 3 }}>
        <div style={{ position: 'absolute', left: `${Math.min(98, Math.max(2, pct))}%`, top: -3, width: 2, height: 10, background: 'var(--accent)' }}/>
      </div>
      <div className="flex justify-between text-3 mono" style={{ fontSize: 10 }}>
        <span>{low.toFixed(2)}</span><span>{high.toFixed(2)}</span>
      </div>
    </div>
  );
}

// Financial statements display
function FinancialsView({ data, currency }) {
  const { financials = [] } = data;
  if (!financials.length) return <div className="text-3" style={{ textAlign: 'center', padding: 20 }}>No financial data available</div>;

  const latest = financials[0];
  const curr = latest.periods?.current || {};
  const comp = latest.periods?.comparative || {};

  const fmt = (v) => v ? fmtMoney(v, currency) : '—';
  const delta = (a, b) => {
    if (!a || !b) return null;
    const pct = ((a - b) / Math.abs(b)) * 100;
    return <span className={pct >= 0 ? 'up' : 'down'}>{pct >= 0 ? '+' : ''}{pct.toFixed(1)}%</span>;
  };

  return (
    <>
      <div className="text-3 mb-3" style={{ fontSize: 12 }}>
        {latest.period_type} {latest.fiscal_year} · {latest.statement_type}
      </div>
      <div className="grid g-3" style={{ gap: 8 }}>
        {[
          ['Revenue', curr.revenue, comp.revenue],
          ['Net income', curr.net_income, comp.net_income],
          ['EPS (basic)', curr.eps_basic ? `$${curr.eps_basic.toFixed(2)}` : null, comp.eps_basic ? `$${comp.eps_basic.toFixed(2)}` : null],
          ['Total assets', curr.total_assets, comp.total_assets],
          ['Total equity', curr.total_equity, comp.total_equity],
          ['Cash & equiv', curr.cash_and_equivalents, comp.cash_and_equivalents],
        ].map(([label, val, compVal], i) => (
          <div key={i} style={{ padding: '10px 12px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 8 }}>
            <div className="text-3" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</div>
            <div className="mono" style={{ fontSize: 15, fontWeight: 600, marginTop: 3 }}>
              {typeof val === 'string' ? val : fmt(val)}
            </div>
            {delta(val, compVal) && (
              <div className="mono" style={{ fontSize: 11, marginTop: 2 }}>
                {delta(val, compVal)} YoY
              </div>
            )}
          </div>
        ))}
      </div>
    </>
  );
}
