/* FinPulse — Stock detail (demo + live via MarketService). */
const TIME_TABS = ['1D', '5D', '1M', '3M', '6M', '1Y', '5Y'];

function AnalystBar({ rec }) {
  if (!rec || !rec.total) return null;
  const segments = [
    { k: 'strongBuy', label: 'Strong Buy', c: 'var(--up)' },
    { k: 'buy', label: 'Buy', c: '#22c55e' },
    { k: 'hold', label: 'Hold', c: 'var(--cat-economy)' },
    { k: 'sell', label: 'Sell', c: '#f97316' },
    { k: 'strongSell', label: 'Strong Sell', c: 'var(--down)' },
  ];
  return (
    <div className="card">
      <div className="card-head" style={{ marginBottom: 10 }}>
        <h3 className="h3">Analyst Consensus</h3>
        <span className="muted">{rec.total} analysts · {rec.period || 'latest'}</span>
      </div>
      <div style={{ display: 'flex', height: 10, borderRadius: 6, overflow: 'hidden', marginBottom: 12 }}>
        {segments.map((s) => rec[s.k] > 0 && (
          <div key={s.k} style={{ width: (rec[s.k] / rec.total * 100) + '%', background: s.c }} title={s.label + ': ' + rec[s.k]} />
        ))}
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {segments.filter((s) => rec[s.k] > 0).map((s) => (
          <span key={s.k} className="chip" style={{ fontSize: 12 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: s.c }}></span>{s.label} {rec[s.k]}</span>
        ))}
      </div>
    </div>
  );
}

function StockScreen({ stock, onOpenStock, onBack, onOpenArticle }) {
  const L = useLive();
  const [s, setS] = useState(stock);
  const [range, setRange] = useState('1D');
  const [refreshing, setRefreshing] = useState(false);
  const [liveNews, setLiveNews] = useState(null);
  const [rec, setRec] = useState(null);
  const [peers, setPeers] = useState([]);
  const [insights, setInsights] = useState(null);
  useEffect(() => {
    setS(stock); setRange(stock && stock.live ? 'LIVE' : '1D');
    setLiveNews(null); setRec(null); setPeers([]); setInsights(null);
  }, [stock]);

  useEffect(() => {
    if (!s || !s.live) return;
    const isUS = s.market !== 'IN' && !/\.NS$/i.test(s.symbol);
    if (isUS && L.hasKey) {
      L.market.getCompanyNews(s.symbol).then((items) => {
        if (window.NewsCache) window.NewsCache.putMany(items);
        setLiveNews(items);
      }).catch(() => setLiveNews([]));
      L.market.getRecommendations(s.symbol).then(setRec).catch(() => setRec(null));
      L.market.getPeers(s.symbol).then(setPeers).catch(() => setPeers([]));
      L.market.getStockInsights(s.symbol).then(setInsights).catch(() => setInsights(null));
    } else if (isUS) {
      setLiveNews([]); setRec(null); setPeers([]); setInsights(null);
    } else if (L.hasKey) {
      const sym = s.symbol || (s.ticker + '.NS');
      L.market.getCompanyNews(sym).then((items) => {
        if (window.NewsCache) window.NewsCache.putMany(items);
        setLiveNews(items);
      }).catch(() => setLiveNews([]));
    }
  }, [s && s.id, L.hasKey]);

  if (!s) return null;
  if (!s.live) return <EmptyState icon="stocks" title="Live data required" sub="Open a symbol from search or screener to load live quotes." />;
  const live = s.live;
  const C = curSym(s.cur);
  const up = s.chg >= 0;
  const data = live ? s.history.LIVE : s.history[range];

  async function refresh() {
    if (!live) return;
    setRefreshing(true);
    try {
      setS(await L.market.refreshStock(s));
      L.refreshRateLimit();
    } catch (e) {} finally { setRefreshing(false); }
  }

  const dash = (v) => (v == null || v === 0 || Number.isNaN(v) ? '—' : v);
  const metrics = [
    { label: 'Market Cap', value: s.mcap != null ? mcapM(s.mcap, s.cur) : '—', sub: s.sector || s.exchange || '—', color: s.sectorColor },
    { label: 'P/E Ratio', value: s.pe != null ? Number(s.pe).toFixed(1) : '—', sub: 'TTM', color: 'var(--accent)' },
    { label: '52W High', value: s.hi52 != null ? C + fmt.price(s.hi52) : '—', sub: s.hi52 ? ((1 - s.price / s.hi52) * 100).toFixed(1) + '% below' : '', color: 'var(--up)' },
    { label: '52W Low', value: s.lo52 != null ? C + fmt.price(s.lo52) : '—', sub: s.lo52 ? ((s.price / s.lo52 - 1) * 100).toFixed(1) + '% above' : '', color: 'var(--down)' },
  ];
  const stats = [
    ['Open', s.open != null ? C + fmt.price(s.open) : '—'], ['Prev Close', s.prevClose != null ? C + fmt.price(s.prevClose) : '—'],
    ['Day High', s.dayHigh != null ? C + fmt.price(s.dayHigh) : '—'], ['Day Low', s.dayLow != null ? C + fmt.price(s.dayLow) : '—'],
    ['Volume', s.vol != null ? fmt.vol(s.vol) + (s.market === 'IN' ? ' sh' : '') : '—'],
    ['52W Range', s.lo52 != null && s.hi52 != null ? C + fmt.price(s.lo52) + ' – ' + C + fmt.price(s.hi52) : '—'],
    ['Dividend Yld', s.div != null ? Number(s.div).toFixed(2) + '%' : '—'], ['Beta', s.beta != null ? Number(s.beta).toFixed(2) : '—'],
    ['Exchange', s.exchange || '—'], ['Currency', s.cur || '—'],
  ];
  const related = liveNews || [];
  const similar = peers;

  return (
    <div>
      <button className="link-btn" onClick={onBack} style={{ marginBottom: 12, background: 'none', border: 'none', padding: 0 }}>
        <span style={{ transform: 'scaleX(-1)', display: 'inline-flex' }}><Icon name="chevright" size={14} /></span> Back
      </button>

      <div className="detail-head">
        {live && s.logo ? <img src={s.logo} alt="" width={52} height={52} style={{ width: 52, height: 52, borderRadius: 12, objectFit: 'contain', background: '#fff', border: '1px solid var(--border)', padding: 4 }} onError={(e) => { e.target.style.display = 'none'; }} /> : <StockAvatar stock={s} size={52} />}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <h1 className="h1" style={{ fontSize: 26 }}>{s.name}</h1>
            {s.sector && <span className="cat-pill" style={{ background: s.sectorColor }}>{s.sector}</span>}
            <LiveBadge live={live} small />
          </div>
          <div className="ticker" style={{ marginTop: 2 }}>{live ? `${s.exchange || 'Listed'} · ${s.ticker}` : `NSE: ${s.ticker} · BSE: ${500000 + s.id * 13}`}</div>
          <div className="detail-price">
            <span className="price-big">{C}{fmt.price(s.price)}</span>
            <span className={`mono ${up ? 'up' : 'down'}`} style={{ fontSize: 15, fontWeight: 600 }}>{(s.change >= 0 ? '+' : '') + fmt.price(s.change)} ({fmt.pct(s.chg)})</span>
            {live && <button className="pill" style={{ height: 32, marginLeft: 4 }} onClick={refresh} disabled={refreshing}><Icon name="refresh" size={14} /> {refreshing ? '…' : 'Refresh'}</button>}
          </div>
        </div>
      </div>

      <div className="detail-grid">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20, minWidth: 0 }}>
          <div className="card">
            <div className="time-tabs" style={{ marginBottom: 8 }}>
              {live ? <button className="time-tab active">TODAY</button>
                : TIME_TABS.map((t) => (
                  <button key={t} className={`time-tab ${range === t ? 'active' : ''}`} onClick={() => setRange(t)}>{t}</button>
                ))}
            </div>
            <AreaChart key={range + (live ? 'L' : '')} data={data} color={up ? 'var(--up)' : 'var(--accent)'} height={260}
              labels={live ? ['Open', '', 'Mid-day', '', 'Now'] : (range === '1D' ? ['9:15', '11:00', '12:45', '14:30', '15:30'] : ['Start', '', 'Mid', '', 'Now'])} />
            {live && <div className="muted" style={{ marginTop: 8, fontSize: 11 }}>Indicative line from live OHLC. Intraday candle history requires a premium Finnhub plan.</div>}
          </div>

          <div className="metric-grid">
            {metrics.map((m, i) => <MetricCard key={i} {...m} />)}
          </div>

          {live && rec && <AnalystBar rec={rec} />}

          {live && insights && insights.priceTarget && (
            <div className="card">
              <div className="card-head" style={{ marginBottom: 8 }}>
                <h3 className="h3">Analyst Price Target</h3>
                <span className="muted">{insights.priceTarget.analysts || '—'} analysts</span>
              </div>
              <div className="metric-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
                <MetricCard label="Mean" value={C + fmt.price(insights.priceTarget.mean)} sub="consensus" color="var(--accent)" />
                <MetricCard label="High" value={C + fmt.price(insights.priceTarget.high)} sub="upside case" color="var(--up)" />
                <MetricCard label="Low" value={C + fmt.price(insights.priceTarget.low)} sub="downside case" color="var(--down)" />
              </div>
            </div>
          )}

          {live && insights && insights.earnings && insights.earnings.length > 0 && (
            <div className="card">
              <h3 className="h3" style={{ marginBottom: 10 }}>Earnings Surprises</h3>
              <div className="table-wrap">
                <table className="data-table">
                  <thead><tr><th>Period</th><th>Actual</th><th>Estimate</th><th>Surprise</th></tr></thead>
                  <tbody>
                    {insights.earnings.map((e) => (
                      <tr key={e.period}>
                        <td>{e.period}</td>
                        <td className="mono-num">{e.actual != null ? e.actual : '—'}</td>
                        <td className="mono-num">{e.estimate != null ? e.estimate : '—'}</td>
                        <td className="mono-num" style={{ color: (e.surprisePct || 0) >= 0 ? 'var(--up)' : 'var(--down)' }}>
                          {e.surprisePct != null ? fmt.pct(e.surprisePct) : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {live && insights && insights.upgrades && insights.upgrades.length > 0 && (
            <div className="card">
              <h3 className="h3" style={{ marginBottom: 10 }}>Upgrades &amp; Downgrades</h3>
              {insights.upgrades.map((u) => (
                <div key={u.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--border)', fontSize: 13 }}>
                  <span><strong>{u.company}</strong> · {u.fromGrade || '—'} → {u.toGrade || u.action}</span>
                  <span className="muted">{u.date}</span>
                </div>
              ))}
            </div>
          )}

          {!live && (
            <div className="card">
              <div className="card-head" style={{ marginBottom: 8 }}><h3 className="h3">Volume · 22 sessions</h3><span className="muted">in lakh shares</span></div>
              <BarChart data={s.volBars} height={120} color="#3b82f6" />
            </div>
          )}

          <div className="card">
            <h3 className="h3" style={{ marginBottom: 6 }}>Key Statistics</h3>
            <div className="kv-list">
              {stats.map((kv, i) => (
                <div key={i} className="kv" style={{ marginRight: i % 2 === 0 ? 16 : 0 }}>
                  <span className="k">{kv[0]}</span><span className="v">{dash(kv[1])}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div className="card">
            <h3 className="h3" style={{ marginBottom: 10 }}>About</h3>
            <p style={{ fontSize: 13, color: 'var(--text-secondary)', margin: 0 }}>
              {live
                ? `${s.name} (${s.ticker}) is listed on ${s.exchange || 'a major exchange'} in the ${s.sector} sector. Live data via Finnhub.`
                : `${s.name} is a leading ${s.sector.toLowerCase()} company listed on the NSE and BSE, part of India's benchmark indices and tracked closely by institutional and retail investors.`}
            </p>
            {insights && insights.sentiment && (
              <div style={{ marginTop: 10 }}>
                <span className={`sentiment ${insights.sentiment.sentiment === 'bull' ? 'bull' : 'bear'}`}>
                  News sentiment: {insights.sentiment.sentiment === 'bull' ? 'Bullish' : 'Bearish'}
                  {insights.sentiment.bullish != null ? ` (${insights.sentiment.bullish}% bull / ${insights.sentiment.bearish}% bear)` : ''}
                </span>
              </div>
            )}
            <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
              <button className="pill active" style={{ flex: 1, justifyContent: 'center', height: 40, whiteSpace: 'nowrap' }}>+ Watchlist</button>
              {live && s.web
                ? <a className="pill" href={s.web} target="_blank" rel="noopener" style={{ flex: 1, justifyContent: 'center', height: 40, whiteSpace: 'nowrap' }}><Icon name="link" size={14} /> Website</a>
                : <button className="pill" style={{ flex: 1, justifyContent: 'center', height: 40, whiteSpace: 'nowrap' }}>Set Alert</button>}
            </div>
          </div>

          <div className="card">
            <h3 className="h3" style={{ marginBottom: 4 }}>{live ? 'Company News' : 'Related News'}</h3>
            {related.length ? <NewsCompact items={related} onOpen={onOpenArticle} /> : <div className="muted" style={{ padding: '8px 0' }}>No recent news.</div>}
            {insights && insights.press && insights.press.length > 0 && (
              <>
                <h3 className="h3" style={{ margin: '16px 0 8px' }}>Press Releases</h3>
                <NewsCompact items={insights.press} onOpen={onOpenArticle} />
              </>
            )}
            {insights && insights.dividends && insights.dividends.length > 0 && (
              <>
                <h3 className="h3" style={{ margin: '16px 0 8px' }}>Recent Dividends</h3>
                {insights.dividends.map((d) => (
                  <div key={d.date} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 13, borderBottom: '1px solid var(--border)' }}>
                    <span>{d.date}</span>
                    <span className="mono-num">{d.currency || '$'}{d.amount}</span>
                  </div>
                ))}
              </>
            )}
          </div>

          {similar.length > 0 && (
            <div className="card">
              <h3 className="h3" style={{ marginBottom: 10 }}>Peers in {s.sector}</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {similar.map((x) => (
                  <div key={x.id} onClick={() => onOpenStock(x)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', cursor: 'pointer', borderBottom: '1px solid var(--border)' }}>
                    <StockAvatar stock={x} size={28} />
                    <span style={{ flex: 1, fontSize: 13, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.name}</span>
                    <ChangeChip value={x.chg} sm showArrow={false} />
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { StockScreen });
