/* Company Stock Price — US ETFs & mutual funds via Finnhub (live API only). */
function RetCell({ v }) {
  if (v == null) return <span className="muted">—</span>;
  return <span className="mono-num" style={{ color: v >= 0 ? 'var(--up)' : 'var(--down)' }}>{fmt.pct(v)}</span>;
}

function FundsScreen() {
  const L = useLive();
  const MD = useMarketData();
  const [cat, setCat] = useState('All');
  const [sort, setSort] = useState('nav');
  const [region, setRegion] = useState('US');
  const [globalFunds, setGlobalFunds] = useState([]);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState('');
  const [sel, setSel] = useState(null);
  const [detail, setDetail] = useState(null);
  const [detailBusy, setDetailBusy] = useState(false);

  const funds = region === 'US' ? globalFunds : [];
  const categories = ['All', ...[...new Set(globalFunds.map((f) => f.category))].sort()];

  async function loadGlobal() {
    if (!L.hasKey) return;
    setLoading(true); setErr('');
    try {
      setGlobalFunds(await L.market.getGlobalFunds());
      L.refreshRateLimit();
    } catch (e) {
      setErr(apiErrorMessage(e));
      setGlobalFunds([]);
    } finally { setLoading(false); }
  }

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

  async function openFund(f) {
    if (!f.live || !L.hasKey) { setSel(f); setDetail(null); return; }
    setSel(f);
    setDetailBusy(true);
    try {
      setDetail(await L.market.getFundDetails(f.symbol));
    } catch (e) {
      setDetail(null);
    } finally { setDetailBusy(false); }
  }

  if (region === 'IN') {
    return (
      <div>
        <h1 className="h1" style={{ marginBottom: 4 }}>Mutual Funds</h1>
        <EmptyState icon="funds" title="India mutual fund API unavailable" sub="Live Indian scheme data requires a dedicated fund data provider. US ETFs and mutual funds are available via Finnhub."
          action={<button className="pill active" onClick={() => setRegion('US')}>View US funds</button>} />
      </div>
    );
  }
  if (loading && !funds.length) return <SkeletonFunds />;
  if (!L.hasKey) {
    return (
      <div>
        <h1 className="h1" style={{ marginBottom: 4 }}>Mutual Funds</h1>
        <EmptyState icon="funds" title="Finnhub API key required" sub="Add your API key to load live US ETF and mutual fund data."
          action={<button className="pill active" onClick={L.openSettings}>Connect API</button>} />
      </div>
    );
  }
  if (!funds.length) {
    return <EmptyState icon="funds" title="No fund data" sub={err || 'Fund catalogue unavailable.'}
      action={<button className="pill" onClick={loadGlobal}>Retry</button>} />;
  }

  let rows = cat === 'All' ? funds : funds.filter((f) => f.category === cat);
  rows = [...rows].sort((a, b) => (b[sort] || b.nav || 0) - (a[sort] || a.nav || 0));

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <h1 className="h1">Mutual Funds</h1>
            {region === 'US' && <LiveBadge live />}
          </div>
          <div className="muted" style={{ marginTop: 2 }}>
            US ETFs &amp; mutual funds · Finnhub profile, holdings &amp; sector data
          </div>
        </div>
        <div className="pill-row">
          <button className={`pill ${region === 'IN' ? 'active' : ''}`} onClick={() => { setRegion('IN'); setSel(null); }}>India</button>
          <button className={`pill ${region === 'US' ? 'active' : ''}`} onClick={() => { setRegion('US'); setSel(null); }}>US (Global)</button>
          {region === 'US' && <button className="pill" onClick={loadGlobal} disabled={loading}>{loading ? '…' : 'Refresh'}</button>}
        </div>
      </div>

      {err && <div className="banner err section">{err}</div>}

      <div className="filter-bar">
        <div className="pill-row">
          {categories.map((c) => (
            <button key={c} className={`pill ${cat === c ? 'active' : ''}`} onClick={() => setCat(c)}>{c}</button>
          ))}
        </div>
        <select className="select" value={sort} onChange={(e) => setSort(e.target.value)} style={{ marginLeft: 'auto' }}>
          <option value="nav">Sort: NAV / Price</option>
          <option value="ret1Y">Sort: 1D Change</option>
          <option value="aum">Sort: AUM</option>
        </select>
      </div>

      <div className="card section" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="data-table">
          <thead>
            <tr>
              <th>Fund</th><th>Category</th><th>{region === 'US' ? 'Price ($)' : 'NAV (₹)'}</th><th>1D</th>
              {region === 'IN' && <><th>1Y</th><th>3Y</th></>}
              <th>AUM</th><th>Expense</th><th>{region === 'IN' ? 'Rating' : 'Risk'}</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((f) => (
              <tr key={f.id} onClick={() => openFund(f)} style={{ cursor: region === 'US' ? 'pointer' : 'default' }}>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div className="stock-ava" style={{ background: `oklch(0.6 0.16 ${f.hue})`, width: 32, height: 32, fontSize: 11 }}>{f.initials}</div>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 13 }}>{f.name}</div>
                      <div className="muted" style={{ fontSize: 11 }}>{f.house}{f.symbol ? ' · ' + f.symbol : ''}</div>
                    </div>
                  </div>
                </td>
                <td><span className="chip">{f.category}</span></td>
                <td className="mono-num">{region === 'US' ? '$' : '₹'}{fmt.price(f.nav)}</td>
                <td><RetCell v={f.ret1Y != null ? f.ret1Y : f.chg} /></td>
                {region === 'IN' && <><td><RetCell v={f.ret1Y} /></td><td><RetCell v={f.ret3Y} /></td></>}
                <td className="mono-num">{f.aum != null ? (region === 'US' ? '$' + (f.aum >= 1e9 ? (f.aum / 1e9).toFixed(1) + 'B' : (f.aum / 1e6).toFixed(0) + 'M') : f.aum.toLocaleString('en-IN')) : '—'}</td>
                <td className="mono-num">{f.expense != null ? f.expense + '%' : '—'}</td>
                <td>{region === 'IN' ? (f.rating ? '★'.repeat(f.rating) : '—') : (f.risk || '—')}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {sel && region === 'US' && (
        <div className="card section" style={{ marginTop: 16 }}>
          <div className="card-head" style={{ marginBottom: 12 }}>
            <h3 className="h3">{sel.name} ({sel.symbol})</h3>
            <button className="icon-btn" onClick={() => setSel(null)}><Icon name="x" /></button>
          </div>
          {sel.description && <p className="muted" style={{ fontSize: 13, marginBottom: 12 }}>{sel.description}</p>}
          {detailBusy ? <div className="muted">Loading holdings…</div> : detail ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <div>
                <div className="label-up" style={{ marginBottom: 8 }}>
                  Holdings{detail.totalHoldings ? ` (${detail.totalHoldings})` : ''}
                </div>
                {detail.holdings.length ? detail.holdings.map((h) => (
                  <div key={h.symbol} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--border)', fontSize: 13 }}>
                    <span>{h.name}</span>
                    <span className="mono-num">{h.percent != null ? h.percent.toFixed(2) + '%' : '—'}</span>
                  </div>
                )) : <div className="muted">No holdings data</div>}
              </div>
              <div>
                <div className="label-up" style={{ marginBottom: 8 }}>Sector exposure</div>
                {detail.sectors.length ? detail.sectors.map((s) => (
                  <div key={s.name} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--border)', fontSize: 13 }}>
                    <span>{s.name}</span>
                    <span className="mono-num">{s.pct != null ? (+s.pct).toFixed(1) + '%' : '—'}</span>
                  </div>
                )) : <div className="muted">No sector data</div>}
              </div>
            </div>
          ) : <div className="muted">Holdings unavailable for this symbol.</div>}
        </div>
      )}
    </div>
  );
}
Object.assign(window, { FundsScreen });
