/* FinPulse — IPO tracker (Indian IPOs + optional Finnhub global calendar). */
const IPO_TABS = [
  { key: 'open', label: 'Open' },
  { key: 'upcoming', label: 'Upcoming' },
  { key: 'listed', label: 'Listed' },
];

function IpoCard({ ipo }) {
  const cur = ipo.currency || '₹';
  const isListed = ipo.status === 'listed';
  const isOpen = ipo.status === 'open';
  return (
    <div className="card hoverable" style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <div className="stock-ava" style={{ background: `oklch(0.6 0.16 ${ipo.hue})`, width: 44, height: 44, fontSize: 14 }}>{ipo.initials}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="h3">{ipo.name}</div>
          <div className="muted">{ipo.sector}{ipo.symbol ? ' · ' + ipo.symbol : ''}</div>
        </div>
        {ipo.live && <LiveBadge live small />}
        {isOpen && <span className="ipo-status open">● Open</span>}
        {ipo.status === 'upcoming' && <span className="ipo-status up">Upcoming</span>}
        {isListed && ipo.listGain != null && <span className={`ipo-status ${ipo.listGain >= 0 ? 'gain' : 'loss'}`}>{ipo.listGain >= 0 ? '▲' : '▼'} {fmt.pct(ipo.listGain)}</span>}
      </div>

      <div className="ipo-stats">
        <div><div className="k">Price Band</div><div className="v">{cur}{ipo.bandLo}{ipo.bandHi !== ipo.bandLo ? '–' + cur + ipo.bandHi : ''}</div></div>
        <div><div className="k">Lot Size</div><div className="v">{ipo.lot} sh</div></div>
        <div><div className="k">Issue Size</div><div className="v">{ipo.issueLabel || (cur + ipo.issueCr + ' Cr')}</div></div>
        {isOpen && ipo.subscription != null && <div><div className="k">Subscribed</div><div className="v" style={{ color: 'var(--up)' }}>{ipo.subscription}x</div></div>}
        {isOpen && ipo.gmp != null && <div><div className="k">GMP</div><div className="v" style={{ color: 'var(--up)' }}>+{cur}{ipo.gmp}</div></div>}
        {!isOpen && <div><div className="k">Min. Invest</div><div className="v">{cur}{(ipo.bandHi * ipo.lot).toLocaleString('en-IN')}</div></div>}
      </div>

      <div className="ipo-foot">
        <span className="muted"><Icon name="clock" size={13} style={{ verticalAlign: -2, marginRight: 4 }} />{ipo.note}</span>
        {isOpen
          ? <button className="pill active" style={{ height: 34 }}>Apply</button>
          : <button className="pill" style={{ height: 34 }}>{isListed ? 'View' : 'Notify me'}</button>}
      </div>
    </div>
  );
}

function EarningsRow({ e }) {
  return (
    <div className="card" style={{ padding: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
        <div>
          <div className="h3 mono" style={{ color: 'var(--accent)' }}>{e.symbol}</div>
          <div className="muted" style={{ fontSize: 12 }}>{e.date}{e.hour ? ' · ' + e.hour : ''}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          {e.epsEstimate != null && <div className="mono-num" style={{ fontSize: 13 }}>EPS est. {e.epsEstimate}</div>}
          {e.quarter != null && <div className="muted" style={{ fontSize: 11 }}>Q{e.quarter} {e.year || ''}</div>}
        </div>
      </div>
    </div>
  );
}

function IpoScreen() {
  const L = useLive();
  const [tab, setTab] = useState('open');
  const [globalIpos, setGlobalIpos] = useState([]);
  const [earnings, setEarnings] = useState([]);
  const [view, setView] = useState('ipo');
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState('');

  async function loadGlobal() {
    if (!L.hasKey) return;
    setLoading(true); setErr('');
    try {
      const [ipos, earn] = await Promise.all([
        L.market.getIpoCalendar(),
        L.market.getEarningsCalendar(2, 0).catch(() => []),
      ]);
      setGlobalIpos(ipos);
      setEarnings(earn);
      L.refreshRateLimit();
    } catch (e) {
      setErr(apiErrorMessage(e));
      setGlobalIpos([]);
      setEarnings([]);
    } finally { setLoading(false); }
  }

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

  const source = globalIpos;
  const filtered = source.filter((i) => i.status === tab);

  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">IPO Tracker</h1>
          </div>
          <div className="muted" style={{ marginTop: 2 }}>
            {view === 'earnings' ? 'Earnings calendar via Finnhub' : 'IPO calendar via Finnhub'}
          </div>
        </div>
      </div>

      {!L.hasKey && (
        <EmptyState icon="ipo" title="Finnhub key required" sub="Add API key for global IPO calendar."
          action={<button className="pill active" onClick={L.openSettings}>Connect API</button>} />
      )}

      {L.hasKey && (
        <>
          <div className="pill-row section" style={{ marginBottom: 10 }}>
            <button className={`pill ${view === 'ipo' ? 'active' : ''}`} onClick={() => setView('ipo')}>IPO Calendar</button>
            <button className={`pill ${view === 'earnings' ? 'active' : ''}`} onClick={() => setView('earnings')}>Earnings ({earnings.length})</button>
            <button className="pill" style={{ marginLeft: 'auto' }} onClick={loadGlobal} disabled={loading}>{loading ? 'Loading…' : 'Refresh'}</button>
          </div>

          {view === 'ipo' && (
            <div className="pill-row section" style={{ marginBottom: 14 }}>
              {IPO_TABS.map((t) => (
                <button key={t.key} className={`pill ${tab === t.key ? 'active' : ''}`} onClick={() => setTab(t.key)}>
                  {t.label} ({source.filter((i) => i.status === t.key).length})
                </button>
              ))}
            </div>
          )}

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

          {loading ? (
            <SkeletonIpo />
          ) : view === 'earnings' ? (
            earnings.length ? (
              <div className="section" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {earnings.map((e) => <EarningsRow key={e.id} e={e} />)}
              </div>
            ) : (
              <EmptyState icon="ipo" title="No upcoming earnings" sub="Try refreshing the earnings calendar." />
            )
          ) : filtered.length ? (
            <div className="ipo-grid section">{filtered.map((ipo) => <IpoCard key={ipo.id} ipo={ipo} />)}</div>
          ) : (
            <EmptyState icon="ipo" title={'No ' + tab + ' IPOs'} sub="Try refreshing the IPO calendar." />
          )}
        </>
      )}
    </div>
  );
}
Object.assign(window, { IpoScreen });
