/* global React, OA, Tag, LivePill */

// =========================================================================
// TOP PICKS — ad-ready showcase. Pulls live from /api/top-picks (computed
// every few minutes from Polymarket's highest-volume markets across our 5
// categories), with consensus verdict + per-model predictions + ad copy.
// =========================================================================
function TopPicksPage({ navigate }) {
  const [picks, setPicks] = React.useState(null);
  const [prompt, setPrompt] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [refreshing, setRefreshing] = React.useState(false);
  const [tab, setTab] = React.useState('all');
  const load = React.useCallback(async () => {
    try {
      const [picksRes, promptRes] = await Promise.all([
        window.CloudLayerAPI.listTopPicks(24),
        window.CloudLayerAPI.getPrompt(),
      ]);
      setPicks(picksRes.items || []);
      setPrompt(promptRes);
      setError(null);
    } catch (e) {
      setError(e.message);
      setPicks([]);
    }
  }, []);

  React.useEffect(() => {
    load();
    const t = setInterval(load, 30_000);
    return () => clearInterval(t);
  }, [load]);

  async function refresh() {
    setRefreshing(true);
    try {
      await window.CloudLayerAPI.refreshTopPicks();
      await load();
    } catch (e) {
      setError(e.message);
    } finally {
      setRefreshing(false);
    }
  }

  const cats = React.useMemo(() => {
    const set = new Set((picks || []).map((p) => p.category).filter(Boolean));
    return ['all', ...set];
  }, [picks]);

  const visible = !picks
    ? []
    : tab === 'all'
    ? picks
    : picks.filter((p) => p.category === tab);

  return (
    <div data-screen-label="07 Top Picks">
      <section className="hero hero-compact">
        <div className="container">
          <div className="crumb" style={{ marginBottom: 14 }}>
            Top picks · highest volume · resolved by {prompt ? `${prompt.enabledCount} model${prompt.enabledCount === 1 ? '' : 's'}` : 'cloudlayer'}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) auto', gap: 32, alignItems: 'flex-end' }}>
            <h1 style={{ fontSize: 72, lineHeight: 1, margin: 0, fontWeight: 300, letterSpacing: '-0.03em' }}>
              The <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>loudest</em> markets to bet your ad spend on.
            </h1>
            <div className="row gap-12">
              <LivePill>{picks ? `${picks.length} live picks` : 'loading…'}</LivePill>
              <button className="btn" onClick={refresh} disabled={refreshing}>
                {refreshing ? 'Refreshing…' : 'Recompute now'}
              </button>
            </div>
          </div>
          <div className="dim" style={{ marginTop: 18, maxWidth: 760, fontSize: 15, lineHeight: 1.55 }}>
            Polled continuously from Polymarket across politics, geopolitics, sports, finance, and crypto.
            Each pick is resolved by every enabled model into a YES/NO verdict with a single percentage.
          </div>
        </div>
      </section>

      {/* THE COLD PROMPT — first-class object */}
      {prompt && <PromptPanel prompt={prompt} />}

      <section className="container" style={{ padding: '40px 32px 0' }}>
        <div className="cat-tabs" style={{ marginBottom: 24 }}>
          {cats.map((c) => (
            <button
              key={c}
              className={`cat-tab ${tab === c ? 'active' : ''}`}
              onClick={() => setTab(c)}
            >
              {c === 'all' ? 'All' : c.charAt(0).toUpperCase() + c.slice(1)}
              <span className="cat-tab-count">
                {c === 'all' ? (picks || []).length : (picks || []).filter((p) => p.category === c).length}
              </span>
            </button>
          ))}
        </div>

        {error && (
          <div className="panel" style={{ padding: 18, marginBottom: 24, borderColor: 'var(--neg)' }}>
            <div className="mono neg">API: {error}</div>
            <div className="dim" style={{ marginTop: 6, fontSize: 13 }}>
              Make sure MongoDB is running and the poller has had at least one tick.
            </div>
          </div>
        )}

        {picks && picks.length === 0 && !error && (
          <div className="panel" style={{ padding: 28, textAlign: 'center' }}>
            <div className="dim" style={{ marginBottom: 8 }}>No top picks yet.</div>
            <div className="mono faint" style={{ fontSize: 12 }}>
              The poller is warming up. First tick can take ~30s.
            </div>
          </div>
        )}

        <div className="mgrid">
          {visible.map((p, i) => (
            <TopPickCard
              key={p._id || p.polymarketId}
              pick={p}
              rank={i + 1}
              onOpen={() => navigate('market', { id: p.polymarketId })}
            />
          ))}
        </div>
      </section>

    </div>
  );
}

// =========================================================================
// PROMPT PANEL — the cold prompt every model sees, shown verbatim.
// =========================================================================
function PromptPanel({ prompt }) {
  const [copied, setCopied] = React.useState(null);
  function copy(label, text) {
    navigator.clipboard.writeText(text);
    setCopied(label);
    setTimeout(() => setCopied(null), 1200);
  }
  return (
    <section className="container" style={{ padding: '36px 32px 0' }}>
      <div className="between" style={{ marginBottom: 16 }}>
        <div>
          <div className="section-eyebrow" style={{ marginBottom: 6 }}>The prompt</div>
          <h2 style={{ fontFamily: 'var(--ff-display)', fontSize: 28, fontWeight: 300, margin: 0, letterSpacing: '-0.02em' }}>
            One <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>cold</em> prompt. Every model gets the same.
          </h2>
        </div>
        <div className="row gap-8" style={{ flexWrap: 'wrap' }}>
          {prompt.models.map((m) => (
            <span
              key={m.id}
              className="tag"
              style={{
                opacity: m.enabled ? 1 : 0.4,
                borderColor: m.enabled ? 'rgba(212,174,90,0.4)' : 'var(--border)',
                color: m.enabled ? 'var(--accent)' : 'var(--fg-faint)',
              }}
              title={`${m.provider} / ${m.model}${m.enabled ? '' : ' (no API key set)'}`}
            >
              {m.label} {m.enabled ? '·' : '×'} <span className="mono faint" style={{ marginLeft: 4 }}>{m.model}</span>
            </span>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div className="prompt-block">
          <div className="ph">
            <div className="ph-l">
              <span className="badge">system</span>
              <span>cold prompt · invariant</span>
            </div>
            <button
              className={`copy-btn ${copied === 'sys' ? 'copied' : ''}`}
              onClick={() => copy('sys', prompt.system)}
            >
              {copied === 'sys' ? 'copied' : 'copy'}
            </button>
          </div>
          <pre>{prompt.system}</pre>
        </div>
        <div className="prompt-block">
          <div className="ph">
            <div className="ph-l">
              <span className="badge">user</span>
              <span>rendered per market</span>
            </div>
            <button
              className={`copy-btn ${copied === 'user' ? 'copied' : ''}`}
              onClick={() => copy('user', prompt.userTemplate)}
            >
              {copied === 'user' ? 'copied' : 'copy'}
            </button>
          </div>
          <pre>{prompt.userTemplate}</pre>
        </div>
      </div>
    </section>
  );
}

function TopPickCard({ pick, rank, onOpen }) {
  const pct = Math.round((pick.yesProbability ?? 0.5) * 100);
  const isYes = pick.verdict === 'YES';
  const verdictColor = isYes ? 'var(--pos)' : 'var(--neg)';
  const edgePct = Math.round((pick.edge || 0) * 100);
  const days = pick.endDate ? Math.max(0, Math.round((new Date(pick.endDate).getTime() - Date.now()) / 86_400_000)) : null;
  const compactVol = formatMoney(pick.volume);
  const perModel = pick.perModel || [];

  return (
    <div className="mcard" style={{ position: 'relative' }}>
      <div className="mcard-top">
        <div className="mcard-meta">
          <span className="cat-pill">{pick.category || 'misc'}</span>
          <span className="mono faint">#{rank}</span>
        </div>
        <div className="mcard-end">{days == null ? '' : days === 0 ? 'resolves today' : `${days}d left`}</div>
      </div>

      <div className="mcard-q" title={pick.question} style={{ cursor: 'pointer' }} onClick={onOpen}>{pick.question}</div>

      <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
        <div className="mono tnum" style={{ fontSize: 44, fontWeight: 400, lineHeight: 1, color: verdictColor }}>
          {pct}<span style={{ fontSize: 18, color: 'var(--fg-faint)' }}>%</span>
        </div>
        <div>
          <div className="uppercase" style={{ color: verdictColor, letterSpacing: '0.12em', fontWeight: 600 }}>
            {isYes ? 'YES' : 'NO'}
          </div>
          <div className="mono faint" style={{ fontSize: 11, marginTop: 2 }}>
            consensus across {perModel.length || 1} model{perModel.length === 1 ? '' : 's'}
            {' · '}market {Math.round((pick.yesPrice ?? 0.5) * 100)}%
            {' · '}edge {edgePct >= 0 ? '+' : ''}{edgePct}pp
          </div>
        </div>
      </div>

      <div className="mcard-figures">
        <div>
          <div className="mcard-fig-val mono tnum">{compactVol}</div>
          <div className="mcard-fig-lbl">Volume</div>
        </div>
        <div>
          <div className="mcard-fig-val mono tnum">{Math.round((pick.yesPrice ?? 0.5) * 100)}%</div>
          <div className="mcard-fig-lbl">Market</div>
        </div>
        <div>
          <div className="mcard-fig-val mono tnum" style={{ color: verdictColor }}>{isYes ? 'YES' : 'NO'}</div>
          <div className="mcard-fig-lbl">Verdict</div>
        </div>
      </div>

      {/* Per-model breakdown */}
      {perModel.length > 0 && (
        <div className="mcard-models-grid" style={{ padding: '6px 0 2px' }}>
          {perModel.map((m) => {
            const mp = Math.round(m.yesProbability * 100);
            const mc = m.verdict === 'YES' ? 'var(--pos)' : 'var(--neg)';
            return (
              <div key={m.modelId} className="mcard-mrow" title={m.reasoning}>
                <span className="mdot" style={{ background: mc }} />
                <span className="mcard-mname">{m.modelLabel}</span>
                <span className="mcard-mp mono tnum">{mp}%</span>
                <span className="mcard-md mono" style={{ color: mc }}>{m.verdict}</span>
              </div>
            );
          })}
        </div>
      )}

    </div>
  );
}

function formatMoney(n) {
  if (!Number.isFinite(n)) return '$0';
  if (n >= 1e9) return `$${(n / 1e9).toFixed(1)}B`;
  if (n >= 1e6) return `$${(n / 1e6).toFixed(1)}M`;
  if (n >= 1e3) return `$${(n / 1e3).toFixed(0)}K`;
  return `$${Math.round(n)}`;
}

window.TopPicksPage = TopPicksPage;
window.TopPickCard = TopPickCard;
