// Roadmap, FAQ, contributing, footer, tweaks panel

const { useState: uE, useEffect: eE } = React;

function Roadmap({ theme }) {
  const items = [
    { when: 'now',  tag: 'v0.3', status: 'shipped', title: 'Calibration optimizer suite',
      desc: '9 optimizers: GEPA, APE, OPRO, EvoPrompt, TextGrad, MIPROv2, PromptBreeder, active learning, ensemble fusion.' },
    { when: 'now',  tag: 'v0.3', status: 'shipped', title: 'Claude Code skills',
      desc: 'evalyn-setup / eval / analyze / calibrate — Claude drives the pipeline end to end.' },
    { when: 'next', tag: 'v0.4', status: 'building', title: 'Multimodal eval (audio · image · video)',
      desc: 'First-class metrics for speech agents, vision models, and video generators.' },
    { when: 'next', tag: 'v0.4', status: 'building', title: 'Regression gates for CI',
      desc: 'GitHub Action + --gate flag that fails a PR if any metric regresses beyond a threshold.' },
    { when: 'soon', tag: 'v0.5', status: 'planned',  title: 'Dataset versioning',
      desc: 'Diff and branch your eval set the way you diff code. Reproducible runs across dataset revisions.' },
    { when: 'soon', tag: 'v0.5', status: 'planned',  title: 'Cohort A/B eval',
      desc: 'Compare two agent versions head-to-head on a shared dataset with significance testing.' },
    { when: 'later', tag: 'v1.0', status: 'planned', title: 'First stable release',
      desc: 'API freeze, long-term schema compatibility, 1.x upgrade guarantee.' },
  ];
  return (
    <Section theme={theme} id="roadmap"
             eyebrow="roadmap"
             title="What's shipped. What's next."
             sub="Open roadmap. Open issue tracker. Open governance.">
      <div style={{ border: `1px solid ${theme.border}`, background: theme.panel }}>
        {items.map((it, i) => (
          <div key={i} style={{
            display: 'grid',
            gridTemplateColumns: '80px 120px 100px 1fr auto',
            gap: 24, alignItems: 'flex-start',
            padding: '22px 28px',
            borderBottom: i < items.length - 1 ? `1px solid ${theme.border}` : 'none',
          }}>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 11,
              color: theme.accent, letterSpacing: '0.18em', textTransform: 'uppercase',
            }}>{it.when}</div>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 12,
              color: theme.text,
              padding: '3px 10px',
              border: `1px solid ${theme.borderStrong}`,
              width: 'fit-content',
            }}>{it.tag}</div>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 10,
              color: it.status === 'shipped' ? theme.accent : theme.textMute,
              letterSpacing: '0.1em', textTransform: 'uppercase',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <span style={{
                width: 8, height: 8,
                background: it.status === 'shipped' ? theme.accent : 'transparent',
                border: `1px solid ${it.status === 'shipped' ? theme.accent : theme.borderStrong}`,
                animation: it.status === 'building' ? 'pulse 1.6s ease-in-out infinite' : 'none',
              }} />
              {it.status}
            </div>
            <div>
              <div style={{ fontFamily: 'var(--display)', fontSize: 22, color: theme.text, fontWeight: 500, letterSpacing: '-0.01em', marginBottom: 4 }}>
                {it.title}
              </div>
              <div style={{ fontFamily: 'var(--body)', fontSize: 14, color: theme.textDim, lineHeight: 1.55 }}>
                {it.desc}
              </div>
            </div>
            <span style={{ color: theme.textMute }}><Icon.arrow /></span>
          </div>
        ))}
      </div>
    </Section>
  );
}

function Contributing({ theme }) {
  return (
    <Section theme={theme} id="contribute"
             eyebrow="open source"
             title="Bring a metric. Leave a better eval bank."
             sub="Every metric is a small Python file. Objective metrics are a function; subjective metrics are a rubric + prompt. Both become a searchable entry in the bank.">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
        <div style={{
          border: `1px solid ${theme.border}`, background: theme.panel,
          padding: 28, fontFamily: 'var(--mono)', fontSize: 12.5, lineHeight: 1.65,
        }}>
          <div style={{ color: theme.accent, marginBottom: 14, letterSpacing: '0.15em' }}>
            OBJECTIVE METRIC · sdk/evalyn_sdk/metrics/objective.py
          </div>
          <pre style={{ margin: 0, color: theme.text, whiteSpace: 'pre-wrap' }}>
            <span style={{ color: theme.textMute }}>{'# 1. define'}</span>{'\n'}
            <span style={{ color: theme.accent }}>{`{`}</span>{`
  "id": "yours",
  "type": "objective",
  "category": "structure",
  "scope": "overall",
  "config": {},
`}<span style={{ color: theme.accent }}>{`}`}</span>
          </pre>
          <div style={{ color: theme.textMute, margin: '12px 0 6px' }}>{'# 2. implement'}</div>
          <pre style={{ margin: 0, color: theme.text, whiteSpace: 'pre-wrap' }}>{`def compute_yours(output, config, **kw):
    return {"score": 1.0, "passed": True, "reason": "..."}`}</pre>
        </div>
        <div style={{
          border: `1px solid ${theme.border}`, background: theme.panel,
          padding: 28, fontFamily: 'var(--mono)', fontSize: 12.5, lineHeight: 1.65,
        }}>
          <div style={{ color: theme.accent, marginBottom: 14, letterSpacing: '0.15em' }}>
            LLM JUDGE METRIC · sdk/evalyn_sdk/metrics/subjective.py
          </div>
          <pre style={{ margin: 0, color: theme.text, whiteSpace: 'pre-wrap' }}>{`{
  "id": "yours",
  "type": "subjective",
  "category": "correctness",
  "scope": "overall",
  "prompt": "You are a judge for X. Evaluate whether...",
  "config": {
    "rubric": [
      "Criterion 1: what to check.",
      "Criterion 2: what to check.",
      "If ANY issue is found, FAIL.",
    ],
    "threshold": 0.5,
  }
}`}</pre>
        </div>
      </div>
      <div style={{
        marginTop: 20, display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center',
      }}>
        <Button theme={theme} kind="primary" icon={<Icon.github />}>fork the repo</Button>
        <Button theme={theme} kind="ghost" icon={<Icon.arrow />}>contribution guide</Button>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 12, color: theme.textMute }}>
          17,400+ tests · 460 files · MIT licensed
        </span>
      </div>
    </Section>
  );
}

function FAQ({ theme }) {
  const qs = [
    { q: 'Is evalyn actually local-only? What about LLM judges?',
      a: 'Everything except the LLM-judge calls stays on your machine. Judges need a model — use Gemini, OpenAI, or a local Ollama endpoint. You control the provider with --provider and your own key.' },
    { q: 'Do I have to use the CLI?',
      a: 'No. evalyn_sdk exposes a Python API: everything the CLI does, you can do from a Jupyter notebook or a Python script. The CLI is a convenience layer.' },
    { q: 'What\'s the difference between evalyn and my observability tool?',
      a: 'Observability tools tell you what happened in production. Evalyn tells you whether what happened was good. They complement each other — most teams run both.' },
    { q: 'How do I evaluate RAG grounding?',
      a: 'Built-in metrics: groundedness_in_context, citation_faithfulness, hallucination, citation_present, url_count. Use --mode llm-registry and they\'ll be recommended automatically.' },
    { q: 'Can I add my own metrics?',
      a: 'Yes, that\'s the whole point of the metric bank. See the Contributing section — objective metrics are Python functions; subjective metrics are rubrics + prompts. PR welcome.' },
    { q: 'Does evalyn work with multi-agent systems?',
      a: 'Yes. CrewAI, AutoGen, LangGraph, and Claude Agent SDK are auto-instrumented. Each agent step is captured as a span; metric scope can target individual llm_calls, tool_calls, or the overall trace.' },
    { q: 'What about production monitoring?',
      a: 'Run evalyn in CI after every deploy with --gate to fail the build on regression. For live monitoring, flip EVALYN_OTEL=on and pipe spans into your existing OTEL collector.' },
  ];
  const [open, setOpen] = useState(0);
  return (
    <Section theme={theme} id="faq" eyebrow="faq" title="Questions, answered.">
      <div style={{ border: `1px solid ${theme.border}`, background: theme.panel }}>
        {qs.map((it, i) => (
          <div key={i} style={{
            borderBottom: i < qs.length - 1 ? `1px solid ${theme.border}` : 'none',
          }}>
            <button onClick={() => setOpen(open === i ? -1 : i)} style={{
              width: '100%',
              background: 'transparent', border: 'none',
              padding: '22px 28px',
              display: 'flex', alignItems: 'center', gap: 20,
              cursor: 'pointer', textAlign: 'left',
              color: theme.text,
            }}>
              <span style={{
                fontFamily: 'var(--mono)', fontSize: 11,
                color: theme.accent, letterSpacing: '0.15em',
                width: 40,
              }}>{String(i + 1).padStart(2, '0')}</span>
              <span style={{
                flex: 1, fontFamily: 'var(--display)', fontSize: 20,
                fontWeight: 500, letterSpacing: '-0.01em',
              }}>{it.q}</span>
              <span style={{
                color: theme.accent, fontFamily: 'var(--mono)',
                fontSize: 18, transform: open === i ? 'rotate(45deg)' : 'none', transition: 'transform 0.2s',
              }}>+</span>
            </button>
            {open === i && (
              <div style={{
                padding: '0 28px 24px 88px',
                fontFamily: 'var(--body)', fontSize: 15, lineHeight: 1.6,
                color: theme.textDim, maxWidth: 820,
              }}>{it.a}</div>
            )}
          </div>
        ))}
      </div>
    </Section>
  );
}

function FinalCTA({ theme }) {
  return (
    <Section theme={theme} tight id="cta" style={{ paddingBottom: 40 }}>
      <div style={{
        position: 'relative',
        padding: '64px 48px',
        border: `1px solid ${theme.borderStrong}`,
        overflow: 'hidden',
        background: theme.panel,
      }}>
        {/* pixel grid bg */}
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `radial-gradient(circle at 1px 1px, ${theme.accentHair} 1px, transparent 0)`,
          backgroundSize: '14px 14px',
          maskImage: 'radial-gradient(ellipse at 80% 50%, rgba(0,0,0,0.6), transparent 70%)',
          WebkitMaskImage: 'radial-gradient(ellipse at 80% 50%, rgba(0,0,0,0.6), transparent 70%)',
        }} />
        <div style={{ position: 'relative', maxWidth: 720 }}>
          <Eyebrow theme={theme}>ship eval like code</Eyebrow>
          <h2 style={{
            fontFamily: 'var(--display)', fontSize: 'clamp(36px, 5vw, 64px)',
            lineHeight: 1.0, letterSpacing: '-0.025em',
            fontWeight: 500, color: theme.text, margin: '20px 0 16px', textWrap: 'balance',
          }}>
            Three commands from{' '}
            <span style={{ color: theme.textDim }}>import</span>{' '}
            to{' '}
            <span style={{ color: theme.accent }}>insight</span>.
          </h2>
          <p style={{
            fontFamily: 'var(--body)', fontSize: 18,
            color: theme.textDim, lineHeight: 1.55, margin: '0 0 28px', maxWidth: 560,
          }}>
            Install. Decorate. One-click. That's evalyn.
          </p>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Button theme={theme} kind="primary" icon={<Icon.arrow />}
              href="https://github.com/shihongDev/evalyn#install" target="_blank" rel="noopener">install the sdk</Button>
          </div>
        </div>
      </div>
    </Section>
  );
}

function Footer({ theme }) {
  return (
    <footer style={{
      borderTop: `1px solid ${theme.border}`,
      padding: '48px 0 32px',
      marginTop: 32,
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 32px' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr', gap: 40,
          marginBottom: 40,
        }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <MiniLogo theme={theme} />
              <span style={{ fontFamily: 'var(--mono)', fontSize: 14, color: theme.text, letterSpacing: '0.14em', fontWeight: 500 }}>EVALYN</span>
            </div>
            <p style={{ fontFamily: 'var(--body)', fontSize: 13, color: theme.textDim, maxWidth: 320, lineHeight: 1.5 }}>
              Local-first evaluation framework for LLM agents. MIT-licensed. Built by a small team that believes your evals shouldn't live in someone else's cloud.
            </p>
          </div>
          <FootCol theme={theme} title="docs" links={[
            ['readme',             'https://github.com/shihongDev/evalyn#readme'],
            ['technical manual',   'https://github.com/shihongDev/evalyn/blob/main/docs/technical-manual.md'],
            ['cli reference',      'https://github.com/shihongDev/evalyn/tree/main/docs/clis'],
            ['optimizers',         'https://github.com/shihongDev/evalyn/tree/main/docs/optimizers'],
          ]} />
          <FootCol theme={theme} title="repo" links={[
            ['github',    'https://github.com/shihongDev/evalyn'],
            ['issues',    'https://github.com/shihongDev/evalyn/issues'],
            ['pull requests', 'https://github.com/shihongDev/evalyn/pulls'],
            ['license',   'https://github.com/shihongDev/evalyn/blob/main/LICENSE'],
          ]} />
          <FootCol theme={theme} title="community" links={[
            ['contributing',    'https://github.com/shihongDev/evalyn/blob/main/CONTRIBUTING.md'],
            ['code of conduct', 'https://github.com/shihongDev/evalyn/blob/main/CODE_OF_CONDUCT.md'],
            ['dev guide',       'https://github.com/shihongDev/evalyn/tree/main/docs/dev'],
            ['contact',         'mailto:lsh98dev@gmail.com'],
          ]} />
        </div>
        <div style={{
          paddingTop: 20, borderTop: `1px solid ${theme.border}`,
          display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16,
          fontFamily: 'var(--mono)', fontSize: 11, color: theme.textMute,
        }}>
          <span>© 2026 evalyn · MIT · lsh98dev@gmail.com</span>
          <span>made with sqlite, python, and stubborn optimism</span>
        </div>
      </div>
    </footer>
  );
}

function FootCol({ theme, title, links }) {
  return (
    <div>
      <div style={{
        fontFamily: 'var(--body)', fontSize: 12,
        letterSpacing: '0.2em', color: theme.accent, marginBottom: 14, textTransform: 'uppercase',
        fontWeight: 500,
      }}>{title}</div>
      <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {links.map(entry => {
          const [label, href] = Array.isArray(entry) ? entry : [entry, '#'];
          const external = href.startsWith('http');
          return (
            <li key={label}>
              <a href={href}
                target={external ? '_blank' : undefined}
                rel={external ? 'noopener noreferrer' : undefined}
                style={{
                  fontFamily: 'var(--body)', fontSize: 15, color: theme.textDim,
                  textDecoration: 'none', transition: 'color 0.15s',
                }}
                onMouseEnter={e => e.currentTarget.style.color = theme.text}
                onMouseLeave={e => e.currentTarget.style.color = theme.textDim}
              >{label}</a>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

// ---------- Tweaks panel ----------

function TweaksPanel({ state, setState, theme, visible }) {
  if (!visible) return null;
  return (
    <div style={{
      position: 'fixed', right: 20, bottom: 20, zIndex: 100,
      width: 300,
      background: theme.panel,
      border: `1px solid ${theme.borderStrong}`,
      boxShadow: `0 20px 60px -20px rgba(0,0,0,0.5)`,
      fontFamily: 'var(--mono)', fontSize: 11, color: theme.text,
    }}>
      <div style={{
        padding: '12px 16px', borderBottom: `1px solid ${theme.border}`,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: theme.scheme === 'dark' ? 'rgba(0,0,0,0.2)' : 'rgba(255,255,255,0.3)',
      }}>
        <span style={{ color: theme.accent, letterSpacing: '0.18em' }}>TWEAKS</span>
        <span style={{ color: theme.textMute, fontSize: 10 }}>live</span>
      </div>
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
        <TweakRow label="background">
          <TweakChips theme={theme} value={state.bgTone} onChange={v => setState({ bgTone: v })}
            options={[['pure-black', 'black'], ['warm-dark', 'warm'], ['off-white', 'light']]} />
        </TweakRow>
        <TweakRow label="accent">
          <TweakChips theme={theme} value={state.accent} onChange={v => setState({ accent: v })}
            options={[['orange','orange'],['amber','amber'],['green','green'],['cool','cool']]}
            swatch />
        </TweakRow>
        <TweakRow label="density">
          <TweakChips theme={theme} value={state.density} onChange={v => setState({ density: v })}
            options={[['roomy','roomy'],['packed','packed']]} />
        </TweakRow>
        <TweakRow label="hero">
          <TweakChips theme={theme} value={state.heroVariant} onChange={v => setState({ heroVariant: v })}
            options={[['banner','banner'],['terminal','terminal'],['diagram','diagram']]} />
        </TweakRow>
        <TweakRow label="body text">
          <TweakChips theme={theme} value={state.typography} onChange={v => setState({ typography: v })}
            options={[
              ['editorial', 'serif'],
              ['modern',    'sans'],
              ['humanist',  'humanist'],
              ['geometric', 'grotesk'],
              ['contrast',  'fraunces'],
              ['terminal',  'mono'],
            ]} />
        </TweakRow>
      </div>
    </div>
  );
}

function TweakRow({ label, children }) {
  return (
    <div>
      <div style={{ opacity: 0.6, marginBottom: 6, letterSpacing: '0.12em', textTransform: 'uppercase', fontSize: 10 }}>
        {label}
      </div>
      {children}
    </div>
  );
}

function TweakChips({ theme, value, onChange, options, swatch = false }) {
  return (
    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
      {options.map(([v, label]) => {
        const active = value === v;
        const hue = swatch ? (ACCENT_MAP[v]?.hue ?? 32) : null;
        return (
          <button key={v} onClick={() => onChange(v)} style={{
            background: active ? theme.accentSoft : 'transparent',
            border: `1px solid ${active ? theme.accent : theme.border}`,
            color: active ? theme.accent : theme.textDim,
            padding: '6px 10px',
            fontFamily: 'var(--mono)', fontSize: 10,
            letterSpacing: '0.08em', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            {swatch && (
              <span style={{ width: 8, height: 8, background: `oklch(0.74 0.16 ${hue})` }} />
            )}
            {label}
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { Roadmap, Contributing, FAQ, FinalCTA, Footer, TweaksPanel });
