/* global React, useApi, useMeta, useAuth, Loading, ApiError, Tag, MDot, CopyButton, formatMoney */

// =========================================================================
// MARKET DETAIL — dynamic by polymarketId.
// =========================================================================
function MarketPage({ navigate, polymarketId }) {
  const { models, modelById } = useMeta();
  const detail = useApi(
    () => polymarketId ? window.CloudLayerAPI.getMarket(polymarketId) : Promise.resolve(null),
    [polymarketId],
  );
  const renderedPrompt = useApi(
    () => polymarketId ? window.CloudLayerAPI.renderPrompt(polymarketId) : Promise.resolve(null),
    [polymarketId],
  );

  React.useEffect(() => {
    if (!polymarketId) return;
    const t = setInterval(detail.refresh, 60_000);
    return () => clearInterval(t);
  }, [polymarketId, detail.refresh]);

  const [tab, setTab] = React.useState('predictions');

  if (!polymarketId) {
    return (
      <div className="container" style={{ padding: '80px 32px' }}>
        <h1 style={{ fontFamily: 'var(--ff-display)', fontSize: 48, fontWeight: 300 }}>No market selected</h1>
        <button className="btn" onClick={() => navigate('home')}>← Back</button>
      </div>
    );
  }
  if (detail.loading && !detail.data) return <Loading label="Loading market…" height={400} />;
  if (detail.error)  return <div style={{ padding: 32 }}><ApiError error={detail.error} /></div>;

  const m     = detail.data?.market;
  const preds = detail.data?.predictions || [];
  if (!m) return <div style={{ padding: 32 }}><ApiError error={{ message: 'Market not found' }} /></div>;

  // Latest prediction per model (preds is newest-first).
  const latestByModel = {};
  for (const p of preds) {
    if (!latestByModel[p.modelId]) latestByModel[p.modelId] = p;
  }

  const consensus = Object.values(latestByModel).length
    ? Object.values(latestByModel).reduce((s, p) => s + p.yesProbability, 0) / Object.values(latestByModel).length
    : null;
  const consensusVerdict = consensus == null ? null : consensus >= 0.5 ? 'YES' : 'NO';
  const yesPct = Math.round((m.yesPrice ?? 0.5) * 100);
  const consensusPct = consensus == null ? null : Math.round(consensus * 100);
  const days = m.endDate ? Math.max(0, Math.round((new Date(m.endDate).getTime() - Date.now()) / 86_400_000)) : null;

  return (
    <div data-screen-label="03 Market detail">
      <div className="page-head">
        <div className="container">
          <div className="crumb" style={{ marginBottom: 18 }}>
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('home')}>Benchmark</span>
            <span style={{ margin: '0 8px' }}>/</span>
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('category', { slug: m.category })}>
              {m.category}
            </span>
            <span style={{ margin: '0 8px' }}>/</span>
            <span style={{ color: 'var(--fg-dim)' }}>market</span>
          </div>
          <div className="row gap-8" style={{ marginBottom: 14 }}>
            <Tag tone={m.closed ? 'resolved' : 'live'}>{m.closed ? 'Closed' : 'Live'}</Tag>
            <Tag>Polymarket · {m.category}</Tag>
            <Tag gold>Cold prompt</Tag>
            {days != null && <Tag>{days === 0 ? 'Resolves today' : `${days}d to resolution`}</Tag>}
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 32 }}>
            <h1 style={{ fontFamily: 'var(--ff-display)', fontWeight: 400, fontSize: 44, lineHeight: 1.04, letterSpacing: '-0.02em', margin: 0, maxWidth: 1100 }}>
              {m.question}
            </h1>
            <div className="row gap-12">
              {(m.eventSlug || m.slug) && (
                <a
                  className="btn"
                  href={`https://polymarket.com/event/${encodeURIComponent(m.eventSlug || m.slug)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  title="Open this market on Polymarket in a new tab"
                  style={{ textDecoration: 'none' }}
                >View on Polymarket ↗</a>
              )}
              <button className="btn" onClick={() => navigate('share', { id: m.polymarketId })}>Share ↗</button>
              <button className="btn btn-accent" onClick={() => navigate('profile')}>Track your prompt →</button>
            </div>
          </div>
          <div className="stat-strip">
            <div className="stat">
              <div className="label">Market YES</div>
              <div className="value mono">{yesPct}%</div>
            </div>
            <div className="stat">
              <div className="label">CloudLayer consensus</div>
              <div className="value mono" style={{ color: consensusVerdict === 'YES' ? 'var(--pos)' : consensusVerdict === 'NO' ? 'var(--neg)' : undefined }}>
                {consensusPct == null ? '—' : `${consensusPct}%`}
                {consensusVerdict && (
                  <span className="mono" style={{ fontSize: 14, marginLeft: 8, color: 'var(--fg-faint)' }}>
                    · {consensusVerdict}
                  </span>
                )}
              </div>
            </div>
            <div className="stat">
              <div className="label">Volume</div>
              <div className="value mono">{formatMoney(m.volume || 0)}</div>
            </div>
            <div className="stat">
              <div className="label">24h volume</div>
              <div className="value mono">{formatMoney(m.volume24h || 0)}</div>
            </div>
          </div>
        </div>
      </div>

      <section className="container" style={{ padding: '40px 32px 0' }}>
        <div className="tabs">
          <button className={`tab ${tab === 'predictions' ? 'active' : ''}`} onClick={() => setTab('predictions')}>Predictions · {Object.keys(latestByModel).length}/{models.length}</button>
          <button className={`tab ${tab === 'prompt' ? 'active' : ''}`} onClick={() => setTab('prompt')}>The prompt</button>
          <button className={`tab ${tab === 'criteria' ? 'active' : ''}`} onClick={() => setTab('criteria')}>Resolution</button>
        </div>

        <div className="two-col">
          <div>
            {tab === 'predictions' && (
              <div className="col gap-12">
                {models.map((mm) => {
                  const p = latestByModel[mm.id];
                  const pPct = p ? Math.round(p.yesProbability * 100) : null;
                  const verdictColor = p?.verdict === 'YES' ? 'var(--pos)' : p?.verdict === 'NO' ? 'var(--neg)' : 'var(--fg-faint)';
                  // A row is only expandable if there's real reasoning text to show.
                  // Without it we render a static row — same hit area, no chevron.
                  const hasReasoning = !!(p && p.reasoning && p.reasoning.trim());
                  return (
                    <div key={mm.id} className="panel">
                      <div
                        style={{
                          width: '100%', display: 'flex', alignItems: 'center',
                          gap: 18, padding: '14px 18px',
                        }}
                      >
                        <span style={{ width: 11, height: 11, borderRadius: '50%', background: mm.color, opacity: p ? 1 : 0.3 }} />
                        <span style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 400, flex: 1 }}>
                          {mm.label}
                        </span>
                        {p ? (
                          <>
                            <span className="mono tnum" style={{ fontSize: 22, color: verdictColor, fontWeight: 500 }}>
                              {pPct}%
                            </span>
                            <span className="mono" style={{ color: verdictColor, fontSize: 11, letterSpacing: '0.12em' }}>
                              {p.verdict}
                            </span>
                            <span className={`mono ${p.edge > 0 ? 'pos' : p.edge < 0 ? 'neg' : 'faint'}`}
                                  style={{ fontSize: 11, width: 56, textAlign: 'right' }}>
                              {p.edge > 0 ? '+' : ''}{Math.round(p.edge * 100)}pp
                            </span>
                          </>
                        ) : (
                          <span className="mono faint" style={{ fontSize: 11 }}>
                            {mm.enabled ? 'awaiting prediction' : 'no API key set'}
                          </span>
                        )}
                      </div>
                      {hasReasoning && (
                        <div style={{ padding: '0 18px 18px' }}>
                          <div className="reasoning" style={{ borderLeftColor: verdictColor }}>
                            {p.reasoning}
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}

            {tab === 'prompt' && (
              <div className="col gap-12">
                <div className="dim" style={{ fontSize: 14, lineHeight: 1.6 }}>
                  This is the rendered prompt every enabled model sees for this exact market.
                </div>
                {renderedPrompt.loading && <Loading label="Rendering prompt…" />}
                {renderedPrompt.error && <ApiError error={renderedPrompt.error} />}
                {renderedPrompt.data && (
                  <>
                    <div className="prompt-block">
                      <div className="ph">
                        <div className="ph-l">
                          <span className="badge">system</span>
                          <span>cold prompt</span>
                        </div>
                        <CopyButton text={renderedPrompt.data.prompt.system} />
                      </div>
                      <pre>{renderedPrompt.data.prompt.system}</pre>
                    </div>
                    <div className="prompt-block">
                      <div className="ph">
                        <div className="ph-l">
                          <span className="badge">user</span>
                          <span>rendered for this market</span>
                        </div>
                        <CopyButton text={renderedPrompt.data.prompt.user} />
                      </div>
                      <pre>{renderedPrompt.data.prompt.user}</pre>
                    </div>
                  </>
                )}
              </div>
            )}

            {tab === 'criteria' && (
              <div className="panel" style={{ padding: 28 }}>
                <h3 style={{ fontFamily: 'var(--ff-display)', fontWeight: 400, fontSize: 22, marginTop: 0 }}>Resolution criteria</h3>
                <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--fg-dim)', whiteSpace: 'pre-wrap' }}>
                  {m.description || 'No resolution criteria description provided by the source market.'}
                </div>
                <div className="method-line" style={{ marginTop: 20 }}>
                  <span className="k">Source</span>
                  <span>Polymarket{m.slug && (<span className="mono faint"> · /event/{m.slug}</span>)}</span>
                </div>
                {m.endDate && (
                  <div className="method-line">
                    <span className="k">End date</span>
                    <span className="mono">{new Date(m.endDate).toLocaleString()}</span>
                  </div>
                )}
                <div className="method-line">
                  <span className="k">Status</span>
                  <span>{m.closed ? 'Closed' : 'Active'}{m.resolved ? ' · Resolved' : ''}</span>
                </div>
              </div>
            )}
          </div>

          {/* RIGHT RAIL */}
          <aside className="col gap-12">
            <div className="panel">
              <div className="panel-header"><h3>All models, one prompt</h3></div>
              <div className="panel-body">
                {models.map((mm) => {
                  const p = latestByModel[mm.id];
                  const pPct = p ? Math.round(p.yesProbability * 100) : null;
                  const color = p?.verdict === 'YES' ? 'var(--pos)' : p?.verdict === 'NO' ? 'var(--neg)' : 'var(--fg-faint)';
                  return (
                    <div key={mm.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--border)' }}>
                      <span style={{ width: 8, height: 8, borderRadius: '50%', background: mm.color, opacity: p ? 1 : 0.3 }} />
                      <span className="mono" style={{ fontSize: 12, color: 'var(--fg)', flex: 1 }}>{mm.short}</span>
                      <span className="mono tnum" style={{ fontSize: 13, color }}>{pPct == null ? '—' : pPct + '%'}</span>
                      <span className="mono" style={{ fontSize: 10.5, color, letterSpacing: '0.1em', width: 22, textAlign: 'right' }}>
                        {p ? p.verdict : ''}
                      </span>
                    </div>
                  );
                })}
                <div className="dim" style={{ fontSize: 12, marginTop: 14, lineHeight: 1.5 }}>
                  Consensus = mean across enabled models. ≥ 50% reads as YES, otherwise NO.
                </div>
              </div>
            </div>
          </aside>
        </div>
      </section>
    </div>
  );
}

window.MarketPage = MarketPage;
