// AsymmetricTheses — surface the highest-asymmetry investment ideas
// the team has scored, plus the graveyard of names that aged out
// (preserved per the user's directive — never deleted, just rotated).
//
// Pulls from /api/theses/ranked which walks every memo with
// asymmetry_score in its frontmatter (Growth Arbitrage Analyst is the
// primary producer; any persona can write the field). Click a ticker
// to drill into TickerContext for full team view.
//
// The point of this panel: the user trades on asymmetric information.
// This is the at-a-glance "what's the highest-edge idea on the board
// right now" surface — distilled from every memo the team has filed.

const { useState: aUseState, useEffect: aUseEffect, useCallback: aUseCallback,
        useMemo: aUseMemo } = React;

function AsymmetricTheses({ open, onClose }) {
  if (!open) return null;
  const [data, setData] = aUseState(null);
  const [loading, setLoading] = aUseState(true);
  const [err, setErr] = aUseState('');
  const [view, setView] = aUseState('top');  // 'top' | 'graveyard'

  const load = aUseCallback(async () => {
    setLoading(true);
    setErr('');
    try {
      const r = await fetch('/api/theses/ranked?limit_top=15&limit_graveyard=15');
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const j = await r.json();
      setData(j);
    } catch (e) {
      setErr(String(e.message || e));
    } finally {
      setLoading(false);
    }
  }, []);

  aUseEffect(() => { if (open) load(); }, [open, load]);

  const list = view === 'top' ? (data?.top || []) : (data?.graveyard || []);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 105,
      background: 'rgba(10,10,12,0.85)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      padding: '40px 20px',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 820, maxHeight: 'calc(100vh - 80px)', overflowY: 'auto',
        background: 'var(--bg)', border: '1px solid var(--line-2)',
        borderRadius: 6, padding: 20, fontFamily: 'var(--font-body)',
      }}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'baseline', gap: 12,
          paddingBottom: 12, marginBottom: 14, borderBottom: '1px solid var(--line)',
        }}>
          <h1 style={{
            fontFamily: 'Instrument Serif, serif', fontStyle: 'italic',
            fontSize: 24, margin: 0, color: 'var(--text)',
          }}>Asymmetric theses</h1>
          <span style={{
            fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
            color: 'var(--text-dim)',
          }}>
            EV/GP/RG · ranked by asymmetry
            {data?.median != null && (
              <span style={{ marginLeft: 8 }}>· median {data.median}</span>
            )}
          </span>
          <button onClick={load} disabled={loading} style={{
            marginLeft: 'auto',
            padding: '4px 10px', fontSize: 10, fontFamily: "'JetBrains Mono', monospace",
            background: 'transparent', color: 'var(--text-2)',
            border: '1px solid var(--line)', borderRadius: 3, cursor: 'pointer',
          }}>↻</button>
          <button onClick={onClose} style={{
            padding: '4px 10px', fontSize: 10, fontFamily: "'JetBrains Mono', monospace",
            background: 'transparent', color: 'var(--text-dim)',
            border: '1px solid var(--line)', borderRadius: 3, cursor: 'pointer',
          }}>close</button>
        </div>

        {err && (
          <div style={{
            padding: 10, marginBottom: 12, fontSize: 11,
            background: 'rgba(217,106,106,0.12)', color: '#d96a6a',
            border: '1px solid rgba(217,106,106,0.4)', borderRadius: 4,
          }}>{err}</div>
        )}

        {/* View toggle */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
          {[
            { id: 'top',       label: 'Top tier',  count: data?.top?.length || 0,
              hint: 'Asymmetry score ≥ 70 — verified high-edge ideas' },
            { id: 'graveyard', label: 'Graveyard', count: data?.graveyard?.length || 0,
              hint: 'Sustained weakness (2+ memos < 50). Preserved — info is never thrown away.' },
          ].map(t => (
            <button
              key={t.id}
              onClick={() => setView(t.id)}
              title={t.hint}
              style={{
                padding: '6px 12px', fontSize: 11,
                fontFamily: 'var(--font-body)',
                background: view === t.id
                  ? (t.id === 'top' ? 'rgba(95,179,124,0.14)' : 'rgba(217,168,95,0.14)')
                  : 'transparent',
                color: view === t.id
                  ? (t.id === 'top' ? '#5fb37c' : '#d9a85f')
                  : 'var(--text-dim)',
                border: '1px solid ' + (view === t.id
                  ? (t.id === 'top' ? '#5fb37c' : '#d9a85f')
                  : 'var(--line)'),
                borderRadius: 3,
                cursor: 'pointer',
                fontWeight: view === t.id ? 600 : 400,
              }}
            >
              {t.label} · {t.count}
            </button>
          ))}
          <span style={{
            marginLeft: 'auto', fontSize: 10, color: 'var(--text-dim)',
            fontFamily: "'JetBrains Mono', monospace",
            alignSelf: 'center',
          }}>
            n={data?.n_scored || 0} scored
          </span>
        </div>

        {loading && !data && (
          <div style={{ padding: 30, textAlign: 'center', color: 'var(--text-dim)' }}>
            Loading rankings…
          </div>
        )}

        {!loading && list.length === 0 && (
          <div style={{ padding: 30, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>
            {view === 'top' ? (
              <>
                No top-tier theses yet. The Growth Arbitrage Analyst fires
                weekdays at 04:30 ET — first run will populate this list.
                Or fire it manually via Memos panel → filter to
                "growth-arbitrage-analyst" → Fire now.
              </>
            ) : (
              <>No graveyard entries — every scored thesis is currently in good standing.</>
            )}
          </div>
        )}

        {/* Ranking list */}
        {list.map((row, i) => {
          const isTop = view === 'top';
          const accent = isTop ? '#5fb37c' : '#d9a85f';
          return (
            <div key={row.ticker} style={{
              marginBottom: 8, padding: '12px 14px',
              background: 'var(--bg-2)',
              borderLeft: `3px solid ${accent}`,
              border: '1px solid var(--line)',
              borderRadius: 3,
            }}>
              <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
                <span style={{
                  fontSize: 12, color: 'var(--text-dim)',
                  fontFamily: "'JetBrains Mono', monospace",
                  fontWeight: 700, minWidth: 24,
                }}>#{i + 1}</span>
                <button
                  onClick={() => window.openTickerContext?.(row.ticker)}
                  title={`Click for team context — every memo + signal mentioning $${row.ticker}`}
                  style={{
                    fontFamily: "'JetBrains Mono', monospace",
                    fontSize: 16, fontWeight: 700, color: 'var(--accent)',
                    background: 'transparent', border: 'none',
                    padding: 0, cursor: 'pointer',
                    textDecoration: 'underline', textDecorationColor: 'rgba(255,255,255,0.15)',
                    textUnderlineOffset: '3px',
                  }}
                >${row.ticker}</button>
                <span style={{
                  padding: '2px 8px', fontSize: 11,
                  background: accent + '22', color: accent,
                  border: `1px solid ${accent}55`,
                  borderRadius: 3,
                  fontFamily: "'JetBrains Mono', monospace",
                  fontWeight: 700,
                }}>{row.score}</span>
                {row.evgprg != null && (
                  <span style={{
                    fontSize: 10, color: 'var(--text-2)',
                    fontFamily: "'JetBrains Mono', monospace",
                  }}>EV/GP/RG {row.evgprg.toFixed(2)}</span>
                )}
                <span style={{
                  marginLeft: 'auto', fontSize: 9, color: 'var(--text-dim)',
                  fontFamily: "'JetBrains Mono', monospace",
                }}>
                  {new Date(row.ts).toLocaleDateString(undefined, {
                    month: 'short', day: 'numeric',
                  })}
                  {row.history_count > 1 && ` · ${row.history_count} memos`}
                </span>
              </div>
              {row.topic && (
                <div style={{
                  marginTop: 4, fontSize: 11, color: 'var(--text)',
                  lineHeight: 1.4,
                }}>
                  {row.topic}
                </div>
              )}
              <div style={{
                marginTop: 4, fontSize: 9, color: 'var(--text-dim)',
                fontFamily: "'JetBrains Mono', monospace",
              }}>
                <em>{row.role}</em>
                {!isTop && row.last_strong_ts && (
                  <span style={{ marginLeft: 8 }}>
                    last strong: {new Date(row.last_strong_ts).toLocaleDateString()}
                  </span>
                )}
                <span style={{ marginLeft: 8 }}>· {row.path}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.AsymmetricTheses = AsymmetricTheses;
