/* FinPulse — Indices: India (default) + Global US (Finnhub, on tab switch) */
function IndicesScreen({ onOpenStock, initialRegion, initialSel }) {
  const L = useLive();
  const MD = useMarketData();
  const [region, setRegion] = useState(initialRegion || 'IN');
  const india = MD.indices || [];
  const global = MD.globalIndices || [];
  const indices = region === 'US' ? global : india;
  const [sel, setSel] = useState(initialSel || (indices[0] && indices[0].label));

  useEffect(() => {
    if (initialRegion) setRegion(initialRegion);
  }, [initialRegion]);

  useEffect(() => {
    if (initialSel) setSel(initialSel);
  }, [initialSel]);

  useEffect(() => {
    if (region === 'US' && L.hasKey && !global.length && !MD.globalLoading) {
      MD.loadGlobal();
    }
  }, [region, L.hasKey]);

  useEffect(() => {
    if (indices.length && !indices.find((i) => i.label === sel)) setSel(indices[0].label);
  }, [indices.length, region]);

  if ((MD.loading && !india.length && region === 'IN') || (region === 'US' && MD.globalLoading && !global.length)) {
    return <SkeletonIndices showTabs />;
  }

  if (region === 'US' && !L.hasKey) {
    return (
      <div>
        <div style={{ marginBottom: 14 }}>
          <h1 className="h1">Indices</h1>
          <div className="muted" style={{ marginTop: 2 }}>India benchmarks · switch to Global for US markets</div>
        </div>
        <EmptyState icon="indices" title="Finnhub key required for US indices" sub="India indices load automatically. Add API key for S&amp;P 500, Nasdaq &amp; more."
          action={<button className="pill active" onClick={L.openSettings}>Connect API</button>} />
      </div>
    );
  }

  if (!indices.length) {
    return <EmptyState icon="indices" title="No index data" sub={MD.error || (region === 'US' ? 'Loading US benchmarks…' : 'Quotes unavailable.')}
      action={<button className="pill" onClick={region === 'US' ? MD.loadGlobal : MD.reload}>Retry</button>} />;
  }

  const ix = indices.find((i) => i.label === sel) || indices[0];
  const meta = region === 'US'
    ? (MD.globalIndexMeta[sel] || { desc: ix.desc })
    : (MD.indexMeta[sel] || { desc: ix.desc });
  const members = MD.indexMembers(sel, region);
  const cur = ix.cur === 'INR' ? '₹' : '$';

  return (
    <div>
      <div style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <h1 className="h1">Indices</h1>
          <LiveBadge live={region === 'IN' || L.live} />
        </div>
        <div className="muted" style={{ marginTop: 2 }}>
          {region === 'IN' ? 'NSE & BSE benchmarks' : 'US benchmark ETFs · Finnhub live'}
        </div>
        <div className="pill-row" style={{ marginTop: 10 }}>
          <button className={`pill ${region === 'IN' ? 'active' : ''}`} onClick={() => setRegion('IN')}>India</button>
          <button className={`pill ${region === 'US' ? 'active' : ''}`} onClick={() => setRegion('US')}>Global (US)</button>
        </div>
      </div>

      <div className="idx-grid section">
        {indices.map((i) => {
          const up = i.chg >= 0;
          const sym = i.cur === 'INR' ? '₹' : '$';
          return (
            <button key={i.symbol + i.label} className={`idx-card ${sel === i.label ? 'sel' : ''}`} onClick={() => setSel(i.label)}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span className="it-label" style={{ fontSize: 12 }}>{i.label}</span>
                <ChangeChip value={i.chg} sm showArrow={false} />
              </div>
              <div className="price-big" style={{ fontSize: 24, margin: '8px 0 6px' }}>{sym}{fmt.price(i.value)}</div>
              <Sparkline data={i.spark} up={up} width={150} height={34} />
            </button>
          );
        })}
      </div>

      <div className="detail-grid">
        <div className="card">
          <div className="card-head">
            <div>
              <div className="label-up">{ix.label} · {ix.symbol}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 4 }}>
                <span className="price-big">{cur}{fmt.price(ix.value)}</span>
                <ChangeChip value={ix.chg} />
              </div>
            </div>
          </div>
          <AreaChart key={sel + region} data={ix.spark} color={ix.chg >= 0 ? 'var(--up)' : 'var(--down)'} height={240}
            labels={['Open', '', 'Mid', '', 'Now']} />
          <div className="muted" style={{ marginTop: 10 }}>{meta.desc}</div>
        </div>

        <div className="card">
          <h3 className="h3" style={{ marginBottom: 10 }}>{members.length ? 'Top Constituents' : 'About'}</h3>
          {members.length ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {members.map((s, i) => (
                <div key={s.id} onClick={() => onOpenStock(s)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 0', cursor: 'pointer', borderBottom: i < members.length - 1 ? '1px solid var(--border)' : 'none' }}>
                  <StockAvatar stock={s} size={28} />
                  <span style={{ flex: 1, fontSize: 13, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</span>
                  <span className="mono" style={{ fontSize: 12 }}>{fmt.stockPrice(s)}</span>
                  <ChangeChip value={s.chg} sm showArrow={false} />
                </div>
              ))}
            </div>
          ) : (
            <p style={{ fontSize: 13, color: 'var(--text-secondary)', margin: 0 }}>{meta.desc}</p>
          )}
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { IndicesScreen });
