/* FinPulse — Markets (India default + Global US toggle) */
function MoverRow({ stock, onOpen }) {
  const C = stock.live ? curSym(stock.cur) : '$';
  return (
    <div onClick={() => onOpen(stock)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--border)', cursor: 'pointer' }}>
      <StockAvatar stock={stock} size={32} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="qc-name" style={{ fontSize: 13 }}>{stock.name}</div>
        <div className="qc-ticker">{stock.ticker}</div>
      </div>
      <Sparkline data={stock.spark} up={stock.chg >= 0} width={72} height={28} />
      <div style={{ textAlign: 'right', minWidth: 84 }}>
        <div className="mono" style={{ fontSize: 13, fontWeight: 500 }}>{C}{fmt.price(stock.price)}</div>
        <ChangeChip value={stock.chg} sm showArrow={false} />
      </div>
    </div>
  );
}

const MARKETS_STOCK_PAGE = 15;

function MarketsScreen({ onOpenStock, onOpenArticle, onOpenIndices, initialRegion, onRegionChange }) {
  const L = useLive();
  const MD = useMarketData();
  const [region, setRegion] = useState(initialRegion || 'IN');

  function setMarketRegion(next) {
    setRegion(next);
    if (onRegionChange) onRegionChange(next);
  }

  useEffect(() => {
    if (initialRegion && initialRegion !== region) setRegion(initialRegion);
  }, [initialRegion]);
  const [selIndex, setSelIndex] = useState(null);
  const [stockPage, setStockPage] = useState(1);

  const isUS = region === 'US';
  const indiaIndices = MD.indices || [];
  const globalIndices = MD.globalIndices || [];
  const indices = isUS ? globalIndices : indiaIndices;
  const stocks = isUS ? (MD.globalStocks || []) : MD.stocks;
  const news = MD.news;
  const status = MD.status;

  useEffect(() => {
    if (isUS && L.hasKey && !globalIndices.length && !MD.globalLoading) {
      MD.loadGlobal();
    }
  }, [isUS, L.hasKey, globalIndices.length, MD.globalLoading, MD.loadGlobal]);

  useEffect(() => {
    setSelIndex(null);
    setStockPage(1);
  }, [region]);

  useEffect(() => {
    if (indices.length && selIndex && !indices.find((i) => i.label === selIndex)) {
      setSelIndex(null);
    }
  }, [indices, selIndex]);

  if (!isUS && MD.loading && !MD.ready) return <SkeletonMarkets />;
  if (!isUS && MD.error) return <EmptyState icon="markets" title="Could not load markets" sub={MD.error} action={<button className="pill" onClick={MD.reload}>Retry</button>} />;
  if (!isUS && !MD.stocks.length) return <EmptyState icon="markets" title="No market data" sub="Could not load NSE quotes." action={<button className="pill" onClick={MD.reload}>Retry</button>} />;

  if (isUS && !L.hasKey) {
    return (
      <div>
        <MarketsHeader region={region} onRegionChange={setMarketRegion} isUS={isUS} live={false} sessionLabel="US Markets" dateStr="" updated={null} />
        <EmptyState icon="markets" title="Finnhub key required for US markets" sub="India markets load automatically. Add your API key for S&amp;P 500, Nasdaq, and US stock movers."
          action={<button className="pill active" onClick={L.openSettings}>Connect API</button>} />
      </div>
    );
  }

  if (isUS && MD.globalLoading && !indices.length) return <SkeletonMarkets />;

  if (isUS && !indices.length) {
    return (
      <div>
        <MarketsHeader region={region} onRegionChange={setMarketRegion} isUS={isUS} live={false} sessionLabel="US Markets" dateStr="" updated={null} />
        <EmptyState icon="markets" title="US market data unavailable" sub="Could not load US benchmark quotes."
          action={<button className="pill" onClick={MD.loadGlobal}>Retry</button>} />
      </div>
    );
  }

  const lead = indices.find((i) => i.label === selIndex) || indices[0];
  const cur = lead.cur === 'INR' ? '₹' : '$';
  const sorted = [...stocks].sort((a, b) => b.chg - a.chg);
  const gainers = sorted.filter((s) => s.chg > 0).slice(0, 5);
  const losers = sorted.filter((s) => s.chg < 0).slice(-5).reverse();
  const upCount = stocks.filter((s) => s.chg > 0).length;
  const downCount = stocks.filter((s) => s.chg < 0).length;
  const flatCount = stocks.length - upCount - downCount;
  const breadth = [
    { k: 'Advances', v: String(upCount), c: 'var(--up)' },
    { k: 'Declines', v: String(downCount), c: 'var(--down)' },
    { k: 'Unchanged', v: String(flatCount), c: 'var(--text-muted)' },
    { k: 'Tracked', v: String(stocks.length), c: 'var(--accent)' },
  ];
  const sessionLabel = isUS
    ? 'US Markets · Live'
    : (status ? (status.isOpen ? 'NSE Open' : (status.session === 'pre-market' ? 'Pre-market' : 'Closed')) : 'NSE');
  const dateStr = new Date().toLocaleDateString('en-IN', {
    weekday: 'long', day: 'numeric', month: 'long', year: 'numeric',
    timeZone: isUS ? 'America/New_York' : 'Asia/Kolkata',
  });
  const updated = MD.lastUpdated
    ? new Date(MD.lastUpdated).toLocaleTimeString('en-IN', {
      hour: '2-digit', minute: '2-digit',
      timeZone: isUS ? 'America/New_York' : 'Asia/Kolkata',
    })
    : null;
  const stockPages = Math.max(1, Math.ceil(stocks.length / MARKETS_STOCK_PAGE));
  const stockSlice = stocks.slice((stockPage - 1) * MARKETS_STOCK_PAGE, stockPage * MARKETS_STOCK_PAGE);

  function openIndicesDetail() {
    if (onOpenIndices) onOpenIndices(region, lead.label);
  }

  return (
    <div>
      <MarketsHeader
        region={region}
        onRegionChange={setMarketRegion}
        isUS={isUS}
        live={isUS ? L.live : MD.ready}
        sessionLabel={sessionLabel}
        dateStr={dateStr}
        updated={updated}
        timezoneLabel={isUS ? 'ET' : 'IST'}
      />

      <div className="index-strip section">
        {indices.map((ix) => (
          <IndexTile
            key={ix.symbol + ix.label}
            ix={{ label: ix.label, value: ix.value, chg: ix.chg, cur: ix.cur }}
            selected={selIndex ? selIndex === ix.label : lead.label === ix.label}
            onClick={() => setSelIndex(ix.label)}
          />
        ))}
      </div>

      <div className="section" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 300px', gap: 14 }}>
        <div className="card hoverable" style={{ display: 'flex', flexDirection: 'column' }} role="button" tabIndex={0}
          onClick={openIndicesDetail}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openIndicesDetail(); } }}>
          <div className="card-head" style={{ marginBottom: 6 }}>
            <div>
              <div className="label-up">{lead.label} · Intraday</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 4 }}>
                <span className="price-big">{cur}{fmt.price(lead.value)}</span>
                <ChangeChip value={lead.chg} />
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {onOpenIndices && (
                <button className="pill" type="button" style={{ fontSize: 12, padding: '6px 12px' }} onClick={(e) => { e.stopPropagation(); openIndicesDetail(); }}>
                  Indices →
                </button>
              )}
              <Icon name="trend" size={22} style={{ color: 'var(--accent)' }} />
            </div>
          </div>
          <AreaChart data={lead.spark} color={lead.chg >= 0 ? 'var(--up)' : 'var(--down)'} height={220} />
        </div>
        <div className="card" style={{ display: 'flex', flexDirection: 'column' }}>
          <div className="label-up" style={{ marginBottom: 4 }}>{isUS ? 'US Watchlist Breadth' : 'Watchlist Breadth'}</div>
          {breadth.map((b, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '11px 0', borderBottom: i < 3 ? '1px solid var(--border)' : 'none' }}>
              <span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>{b.k}</span>
              <span className="mono" style={{ fontWeight: 600, color: b.c, fontSize: 14 }}>{b.v}</span>
            </div>
          ))}
          {stocks.length > 0 && (
            <div style={{ marginTop: 'auto', paddingTop: 12 }}>
              <div className="muted" style={{ marginBottom: 6 }}>Adv / Dec ratio</div>
              <div style={{ height: 8, borderRadius: 6, overflow: 'hidden', display: 'flex', background: 'var(--down-bg)' }}>
                <div style={{ width: (upCount / stocks.length * 100) + '%', background: 'var(--up)' }}></div>
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="section grid-2">
        <div className="card">
          <div className="card-head"><h2 className="h2">Top Gainers</h2></div>
          {gainers.length ? gainers.map((s) => <MoverRow key={s.id} stock={s} onOpen={onOpenStock} />) : <div className="muted">No gainers today.</div>}
        </div>
        <div className="card">
          <div className="card-head"><h2 className="h2">Top Losers</h2></div>
          {losers.length ? losers.map((s) => <MoverRow key={s.id} stock={s} onOpen={onOpenStock} />) : <div className="muted">No losers today.</div>}
        </div>
      </div>

      <div className="section">
        <div className="section-head">
          <h2 className="h2">{isUS ? 'US Watchlist' : 'Nifty 50 Watchlist'}</h2>
          <span className="muted">
            {stocks.length}{!isUS && MD.stocksTotal ? '/' + MD.stocksTotal : ''} stocks · {isUS ? 'Finnhub live' : 'live NSE quotes'}
            {!isUS && MD.stocksLoadingMore ? ' · loading…' : ''}
          </span>
        </div>
        <div className="grid-3">
          {stockSlice.map((s) => <StockQuoteCard key={s.id} stock={s} onOpen={onOpenStock} />)}
        </div>
        {stocks.length > MARKETS_STOCK_PAGE && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14, gap: 12, flexWrap: 'wrap' }}>
            <span className="muted" style={{ fontSize: 13 }}>
              Page {stockPage} of {stockPages} · showing {(stockPage - 1) * MARKETS_STOCK_PAGE + 1}–{(stockPage - 1) * MARKETS_STOCK_PAGE + stockSlice.length}
            </span>
            <div className="pill-row">
              <button className="pill" disabled={stockPage <= 1} onClick={() => setStockPage((p) => p - 1)}>Previous</button>
              <button className="pill" disabled={stockPage >= stockPages} onClick={() => setStockPage((p) => p + 1)}>Next</button>
            </div>
          </div>
        )}
      </div>

      {!isUS && news.length > 0 && (
        <div className="section">
          <div className="section-head"><h2 className="h2">Top Stories</h2></div>
          <div className="grid-2" style={{ alignItems: 'start' }}>
            <NewsFeatured item={news[0]} onOpen={onOpenArticle} />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {news.slice(1, 5).map((n) => <NewsStandard key={n.id} item={n} onOpen={onOpenArticle} />)}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function MarketsHeader({ region, onRegionChange, isUS, live, sessionLabel, dateStr, updated, timezoneLabel }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 18, flexWrap: 'wrap' }}>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <h1 className="h1">Markets</h1>
          <LiveBadge live={live} />
        </div>
        <div className="muted" style={{ marginTop: 2 }}>
          {dateStr ? dateStr + ' · ' : ''}{isUS ? 'US benchmarks & large caps' : 'NSE/BSE'}{updated ? ' · updated ' + updated + ' ' + timezoneLabel : ''}
        </div>
        <div className="pill-row" style={{ marginTop: 10 }}>
          <button className={`pill ${region === 'IN' ? 'active' : ''}`} onClick={() => onRegionChange('IN')}>India</button>
          <button className={`pill ${region === 'US' ? 'active' : ''}`} onClick={() => onRegionChange('US')}>Global (US)</button>
        </div>
      </div>
      <span className={`chip ${!isUS && sessionLabel === 'NSE Open' ? 'up' : ''}`} style={{ height: 32 }}>
        <span style={{ width: 7, height: 7, borderRadius: '50%', background: !isUS && sessionLabel === 'NSE Open' ? 'var(--up)' : 'var(--text-muted)' }}></span>
        {sessionLabel}
      </span>
    </div>
  );
}

Object.assign(window, { MarketsScreen });
