// Dashboard preview, annotation/calibration explainer, code samples, Claude skills

const { useState: uD, useEffect: eD, useMemo: mD } = React;

function DashboardPreview({ theme }) {
  return (
    <Section theme={theme} id="dashboard"
             eyebrow="run-eval --report html"
             title="Every run yields a report you can open offline."
             sub="A ready-to-hand-to-your-PM HTML dashboard is written to disk next to your eval run. No login, no seat, no sync.">
      <div style={{
        border: `1px solid ${theme.borderStrong}`,
        background: theme.panel,
        boxShadow: `0 30px 80px -40px rgba(0,0,0,0.6)`,
      }}>
        {/* Fake browser chrome */}
        <div style={{
          padding: '10px 14px',
          borderBottom: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', gap: 10,
          background: theme.scheme === 'dark' ? 'rgba(0,0,0,0.35)' : 'rgba(255,255,255,0.5)',
        }}>
          <span style={{ width: 9, height: 9, borderRadius: 9, background: '#ff5f57' }} />
          <span style={{ width: 9, height: 9, borderRadius: 9, background: '#ffbd2e' }} />
          <span style={{ width: 9, height: 9, borderRadius: 9, background: '#28ca41' }} />
          <div style={{
            flex: 1, margin: '0 10px',
            fontFamily: 'var(--mono)', fontSize: 11, color: theme.textMute,
            padding: '4px 10px', border: `1px solid ${theme.border}`,
            textAlign: 'center',
          }}>
            file://eval_runs/20260127-055659_220e8590/report.html
          </div>
        </div>
        <div style={{ padding: 28 }}>
          {/* Header row */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24 }}>
            <div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: theme.textMute, letterSpacing: '0.15em', marginBottom: 6 }}>
                EVAL RUN · 220e8590
              </div>
              <div style={{ fontFamily: 'var(--display)', fontSize: 30, color: theme.text, letterSpacing: '-0.01em', fontWeight: 500 }}>
                gemini-deep-research-agent
              </div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: theme.textDim, marginTop: 4 }}>
                137 items · 10 metrics · 2026-01-27 05:56:59
              </div>
            </div>
            <div style={{
              fontFamily: 'var(--display)', fontSize: 56, fontWeight: 500,
              letterSpacing: '-0.02em', color: theme.accent, lineHeight: 1,
            }}>
              85<span style={{ fontSize: 28, color: theme.textDim }}>%</span>
            </div>
          </div>
          {/* KPI row */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
            border: `1px solid ${theme.border}`, marginBottom: 24,
          }}>
            {[
              ['RUNTIME', '48.2s', theme.text],
              ['TOKENS', '10.1M', theme.text],
              ['COST', '$1.03', theme.accent],
              ['HEALTH', 'MODERATE', theme.accent],
            ].map(([k, v, c], i) => (
              <div key={k} style={{
                padding: 18, borderRight: i < 3 ? `1px solid ${theme.border}` : 'none',
              }}>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: theme.textMute, letterSpacing: '0.15em', marginBottom: 6 }}>{k}</div>
                <div style={{ fontFamily: 'var(--display)', fontSize: 24, color: c, fontWeight: 500 }}>{v}</div>
              </div>
            ))}
          </div>
          {/* Charts grid */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
            <ChartPanel title="METRIC PASS RATES" theme={theme}>
              {[
                ['output_nonempty', 1.0, 'obj'],
                ['url_count', 1.0, 'obj'],
                ['clarity_and_readability', 0.97, 'llm'],
                ['helpfulness_accuracy', 0.96, 'llm'],
                ['latency_ms', 0.93, 'obj'],
                ['groundedness_in_context', 0.91, 'llm'],
                ['conciseness', 0.91, 'llm'],
                ['factual_accuracy', 0.80, 'llm'],
              ].map(([name, val, type]) => (
                <div key={name} style={{ display: 'grid', gridTemplateColumns: '200px 1fr 44px', gap: 12, alignItems: 'center', margin: '6px 0' }}>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: theme.text, display: 'flex', gap: 6 }}>
                    <span style={{ color: type === 'llm' ? theme.accent : theme.textMute }}>{type === 'llm' ? '◆' : '○'}</span>
                    <span>{name}</span>
                  </div>
                  <div style={{ height: 8, background: theme.border, position: 'relative' }}>
                    <div style={{
                      position: 'absolute', inset: 0,
                      width: `${val * 100}%`,
                      background: val < 0.85 ? theme.accent : theme.textDim,
                    }} />
                  </div>
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: val < 0.85 ? theme.accent : theme.text, textAlign: 'right' }}>
                    {(val*100).toFixed(0)}%
                  </span>
                </div>
              ))}
            </ChartPanel>
            <ChartPanel title="CONFUSION MATRIX · factual_accuracy" theme={theme}>
              <ConfusionMatrix theme={theme} />
            </ChartPanel>
            <ChartPanel title="COST TREND · last 8 runs" theme={theme} span>
              <CostTrend theme={theme} />
            </ChartPanel>
          </div>
          <div style={{
            marginTop: 20, padding: 16,
            border: `1px dashed ${theme.accentHair}`,
            display: 'flex', alignItems: 'flex-start', gap: 14,
          }}>
            <span style={{ color: theme.accent, fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.15em', whiteSpace: 'nowrap' }}>INSIGHT →</span>
            <p style={{ margin: 0, fontFamily: 'var(--body)', fontSize: 14, color: theme.textDim, lineHeight: 1.55 }}>
              <span style={{ color: theme.text }}><code>factual_accuracy</code> is the weakest metric at 80% pass rate.</span>{' '}
              20 of 28 failures cluster around questions involving cited statistics. Consider running{' '}
              <code style={{ color: theme.accent, fontFamily: 'var(--mono)' }}>evalyn annotate --latest</code>
              {' '}on that cluster and re-calibrating the judge.
            </p>
          </div>
        </div>
      </div>
    </Section>
  );
}

function ChartPanel({ title, children, theme, span = false }) {
  return (
    <div style={{
      border: `1px solid ${theme.border}`,
      padding: 18,
      gridColumn: span ? '1 / -1' : 'auto',
      background: theme.scheme === 'dark' ? 'rgba(0,0,0,0.2)' : 'rgba(255,255,255,0.3)',
    }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.18em', color: theme.accent, marginBottom: 14 }}>
        {title}
      </div>
      {children}
    </div>
  );
}

function ConfusionMatrix({ theme }) {
  // human pass/fail vs judge pass/fail
  const cells = [
    [109, 0,  'TP'], [4, 0,  'FP'],
    [7,   1,  'FN'], [17, 1, 'TN'],
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '50px 1fr 1fr', gridTemplateRows: '20px 1fr 1fr', gap: 6, fontFamily: 'var(--mono)', fontSize: 11 }}>
      <div></div>
      <div style={{ color: theme.textMute, textAlign: 'center' }}>judge P</div>
      <div style={{ color: theme.textMute, textAlign: 'center' }}>judge F</div>
      <div style={{ color: theme.textMute, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 6 }}>hum P</div>
      <MatCell n={109} max={109} accent={theme.accent} textDim={theme.textDim} text={theme.text} border={theme.border} kind="TP" />
      <MatCell n={4}   max={109} accent={theme.accent} textDim={theme.textDim} text={theme.text} border={theme.border} kind="FN" />
      <div style={{ color: theme.textMute, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 6 }}>hum F</div>
      <MatCell n={7}   max={109} accent={theme.accent} textDim={theme.textDim} text={theme.text} border={theme.border} kind="FP" />
      <MatCell n={17}  max={109} accent={theme.accent} textDim={theme.textDim} text={theme.text} border={theme.border} kind="TN" />
    </div>
  );
}

function MatCell({ n, max, accent, textDim, text, border, kind }) {
  const intensity = Math.min(1, n / max);
  return (
    <div style={{
      padding: 12, border: `1px solid ${border}`,
      background: (kind === 'TP' || kind === 'TN') ? `oklch(0.74 0.16 32 / ${0.05 + intensity * 0.35})` : 'transparent',
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <span style={{ fontSize: 10, color: textDim, letterSpacing: '0.1em' }}>{kind}</span>
      <span style={{ fontSize: 22, color: text, fontFamily: 'var(--display)', fontWeight: 500 }}>{n}</span>
    </div>
  );
}

function CostTrend({ theme }) {
  const data = [0.42, 0.55, 0.61, 0.58, 0.74, 0.89, 0.95, 1.03];
  const max = Math.max(...data);
  const w = 100; const h = 80;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * w},${h - (v / max) * h * 0.85}`).join(' ');
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 110 }}>
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ flex: 1, height: '100%', width: 'auto' }}>
        <polyline points={pts} fill="none" stroke={theme.accent} strokeWidth="1" vectorEffect="non-scaling-stroke" />
        {data.map((v, i) => {
          const cx = (i / (data.length - 1)) * w;
          const cy = h - (v / max) * h * 0.85;
          return <circle key={i} cx={cx} cy={cy} r="1.4" fill={theme.accent} />;
        })}
      </svg>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: theme.textDim, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <span style={{ color: theme.accent, fontSize: 20, fontFamily: 'var(--display)' }}>$1.03</span>
        <span style={{ color: theme.textMute }}>latest run</span>
        <span style={{ color: '#ff8c5a' }}>▲ 8.4%</span>
      </div>
    </div>
  );
}

// ---------- Annotation + Calibration explainer ----------

function Calibrate({ theme }) {
  const [step, setStep] = useState(0);
  const steps = [
    { label: 'ANNOTATE', desc: 'human-in-the-loop labels' },
    { label: 'ALIGN', desc: 'measure judge vs human agreement' },
    { label: 'OPTIMIZE', desc: 'one of 9 optimizers retunes the rubric' },
    { label: 'VERIFY', desc: 're-run eval with --use-calibrated' },
  ];
  useEffect(() => {
    const t = setInterval(() => setStep(s => (s + 1) % steps.length), 2800);
    return () => clearInterval(t);
  }, []);

  return (
    <Section theme={theme} id="calibrate"
             eyebrow="annotate → calibrate"
             title="LLM judges that actually agree with your humans."
             sub="LLM judges are noisy. Evalyn treats judge calibration like model fine-tuning: collect labels, measure drift, optimize the rubric, re-evaluate.">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
        {/* Annotation TUI */}
        <div style={{
          border: `1px solid ${theme.border}`, background: theme.panel,
          fontFamily: 'var(--mono)', fontSize: 12,
          padding: 24, color: theme.text,
        }}>
          <div style={{ color: theme.accent, marginBottom: 12, letterSpacing: '0.15em' }}>
            ▸ INTERACTIVE ANNOTATION
          </div>
          <div style={{ color: theme.textMute, marginBottom: 4 }}>
            dataset: gemini-deep-research-agent
          </div>
          <div style={{ color: theme.textMute, marginBottom: 14 }}>
            item 37/137 [960912fa-637...]
          </div>
          <div style={{ marginBottom: 14 }}>
            <div style={{ color: theme.accent, marginBottom: 4 }}>INPUT</div>
            <div style={{ color: theme.textDim, paddingLeft: 12 }}>
              &#123;"question": "What is antimatter?"&#125;
            </div>
          </div>
          <div style={{ marginBottom: 14 }}>
            <div style={{ color: theme.accent, marginBottom: 4 }}>OUTPUT</div>
            <div style={{ color: theme.textDim, paddingLeft: 12 }}>
              Antimatter is matter composed of antiparticles; an antiproton has the same mass as a proton but opposite charge...
            </div>
          </div>
          <div style={{ marginBottom: 14 }}>
            <div style={{ color: theme.accent, marginBottom: 4 }}>JUDGE VERDICTS</div>
            <div style={{ paddingLeft: 12 }}>
              <div>factual_accuracy <span style={{ color: theme.accent }}>PASS</span></div>
              <div>helpfulness <span style={{ color: theme.accent }}>PASS</span></div>
              <div>clarity <span style={{ color: theme.accent }}>PASS</span></div>
            </div>
          </div>
          <div style={{ color: theme.textMute, marginBottom: 10, display: 'flex', gap: 14, flexWrap: 'wrap' }}>
            <span>[<span style={{ color: theme.accent }}>y</span>] pass</span>
            <span>[<span style={{ color: theme.accent }}>n</span>] fail</span>
            <span>[<span style={{ color: theme.accent }}>s</span>] skip</span>
            <span>[<span style={{ color: theme.accent }}>v</span>] view full</span>
            <span>[<span style={{ color: theme.accent }}>q</span>] quit</span>
          </div>
          <div>
            Pass? <span style={{
              display: 'inline-block', width: 7, height: 14,
              background: theme.accent,
              verticalAlign: 'middle',
              animation: 'blink 1s steps(2) infinite',
            }} />
          </div>
        </div>
        {/* Optimizer flow */}
        <div style={{
          border: `1px solid ${theme.border}`, background: theme.panel,
          padding: 24, display: 'flex', flexDirection: 'column', gap: 18,
        }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: theme.accent, letterSpacing: '0.18em' }}>
            CALIBRATION FLOW
          </div>
          {steps.map((s, i) => (
            <div key={s.label} style={{
              display: 'flex', gap: 18, alignItems: 'center',
              padding: 16,
              border: `1px solid ${step === i ? theme.accent : theme.border}`,
              background: step === i ? theme.accentSoft : 'transparent',
              transition: 'all 0.4s',
            }}>
              <div style={{
                width: 36, height: 36,
                border: `1px solid ${step === i ? theme.accent : theme.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--mono)', fontSize: 13,
                color: step === i ? theme.accent : theme.textDim,
              }}>{String(i + 1).padStart(2, '0')}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--display)', fontSize: 22, color: theme.text, fontWeight: 500, letterSpacing: '-0.01em' }}>
                  {s.label}
                </div>
                <div style={{ fontFamily: 'var(--body)', fontSize: 13, color: theme.textDim }}>
                  {s.desc}
                </div>
              </div>
              {step === i && (
                <span style={{ color: theme.accent, fontFamily: 'var(--mono)', fontSize: 18 }}>▸</span>
              )}
            </div>
          ))}
          <div style={{
            marginTop: 4, padding: 12,
            borderTop: `1px dashed ${theme.border}`,
            fontFamily: 'var(--mono)', fontSize: 11, color: theme.textDim,
            display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8,
          }}>
            <span style={{ color: theme.accent }}>9 optimizers:</span>
            <span>GEPA · APE · OPRO · EvoPrompt · TextGrad · MIPROv2 · PromptBreeder · Active · Ensemble</span>
          </div>
        </div>
      </div>
    </Section>
  );
}

Object.assign(window, { DashboardPreview, Calibrate });
