/* Admin: the benchmark panel for one lead.

   Prompt library (edit, lock, rewrite with Claude), the competitor list,
   a cost estimate before a run, the run itself driven from this page
   (tick after tick while it is open), then results, raw answers, CSV and
   the run history. Everything goes through POST /api/engines with the
   session token; the client never sees any of this. */

async function engineCall(token, body) {
  return apiCall('/api/engines', {
    method: 'POST',
    headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

const STAGES = ['awareness', 'consideration', 'decision'];

const tinyInput = {
  padding: '7px 9px', borderRadius: 'var(--r-sm, 6px)', fontSize: 13, fontFamily: 'var(--font-sans)',
  color: 'var(--fg)', background: 'var(--navy)', border: '1px solid var(--line-strong)', outline: 'none',
  boxSizing: 'border-box', width: '100%',
};

function SubHead({ children, right }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, margin: '18px 0 10px', flexWrap: 'wrap' }}>
      <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--fg-subtle)' }}>{children}</div>
      {right}
    </div>);
}

function LibraryEditor({ library, busy, onSave, onLock, onGenerate }) {
  const [prompts, setPrompts] = React.useState(library.prompts || []);
  const [dirty, setDirty] = React.useState(false);
  React.useEffect(() => { setPrompts(library.prompts || []); setDirty(false); }, [library.version, library.updated_at]);
  const locked = !!library.locked;
  const edit = (i, key, value) => {
    setPrompts((ps) => ps.map((p, j) => (j === i ? { ...p, [key]: value } : p)));
    setDirty(true);
  };
  const remove = (i) => { setPrompts((ps) => ps.filter((_, j) => j !== i)); setDirty(true); };
  const add = () => { setPrompts((ps) => [...ps, { text: '', stage: 'consideration', cluster: 'general' }]); setDirty(true); };
  const counts = STAGES.map((s) => prompts.filter((p) => p.stage === s).length);
  return (
    <div>
      <SubHead right={
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button style={smallBtn()} disabled={busy || locked} onClick={onGenerate}>{busy === 'library-generate' ? 'Writing…' : 'Rewrite with Claude'}</button>
          <button style={smallBtn(locked ? 'warn' : undefined)} disabled={busy} onClick={() => onLock(!locked)}>{locked ? 'Unlock' : 'Lock'}</button>
          <button style={smallBtn('accent')} disabled={busy || locked || !dirty} onClick={() => onSave(prompts)}>Save library</button>
        </div>}>
        Prompt library · {prompts.length} prompts · {counts[0]} awareness / {counts[1]} consideration / {counts[2]} decision
        {library.written_by ? ` · written by ${library.written_by}` : ''}{locked ? ' · locked' : ''}
      </SubHead>
      <div style={{ fontSize: 12.5, color: 'var(--fg-subtle)', marginBottom: 10, lineHeight: 1.6 }}>
        The questions a buyer types before choosing in this category. A run uses the library as saved;
        lock it once you are happy so nobody edits it between runs. Aim for 30–60.
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 420, overflowY: 'auto', paddingRight: 4 }}>
        {prompts.map((p, i) =>
        <div key={p.id || i} style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 120px 130px 28px', gap: 6, alignItems: 'center' }}>
          <input value={p.text} disabled={locked} onChange={(e) => edit(i, 'text', e.target.value)} style={tinyInput} placeholder="what a buyer would type" />
          <select value={p.stage} disabled={locked} onChange={(e) => edit(i, 'stage', e.target.value)} style={tinyInput}>
            {STAGES.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
          <input value={p.cluster || ''} disabled={locked} onChange={(e) => edit(i, 'cluster', e.target.value)} style={tinyInput} placeholder="cluster" />
          <button disabled={locked} onClick={() => remove(i)} title="Remove" style={{ background: 'transparent', border: 'none', color: 'var(--fg-subtle)', cursor: 'pointer', fontSize: 16 }}>×</button>
        </div>)}
      </div>
      {!locked && <button style={{ ...smallBtn(), marginTop: 8 }} onClick={add}>+ Add a prompt</button>}
    </div>);
}

function CompetitorsEditor({ report, busy, onSave }) {
  const toText = (list) => (list || []).map((c) => [c.name, c.domain, (c.aliases || []).join(' | ')].filter(Boolean).join(', ')).join('\n');
  const [text, setText] = React.useState(toText(report.competitors));
  const [aliases, setAliases] = React.useState((report.brand_aliases || []).join(', '));
  React.useEffect(() => { setText(toText(report.competitors)); setAliases((report.brand_aliases || []).join(', ')); }, [report.updated_at]);
  const parse = () => text.split('\n').map((l) => l.trim()).filter(Boolean).map((l) => {
    const [name, domain, al] = l.split(',').map((x) => x.trim());
    return { name, domain: domain || '', aliases: (al || '').split('|').map((x) => x.trim()).filter(Boolean) };
  });
  return (
    <div>
      <SubHead right={<button style={smallBtn('accent')} disabled={busy} onClick={() => onSave(parse(), aliases.split(',').map((x) => x.trim()).filter(Boolean))}>Save competitors</button>}>
        Competitors · {(report.competitors || []).length}
      </SubHead>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 10 }}>
        <div>
          <textarea value={text} onChange={(e) => setText(e.target.value)} rows={5} style={{ ...tinyInput, resize: 'vertical' }}
            placeholder={'One per line: Name, domain.com, alias one | alias two\nRival One, rivalone.com\nRival Two'} />
          <div style={{ fontSize: 12, color: 'var(--fg-subtle)', marginTop: 4 }}>Name, then optionally the domain and aliases. The run reports how often each is named.</div>
        </div>
        <div>
          <input value={aliases} onChange={(e) => setAliases(e.target.value)} style={tinyInput}
            placeholder="Other names for the client, comma-separated (e.g. 120Life, 120/Life)" />
          <div style={{ fontSize: 12, color: 'var(--fg-subtle)', marginTop: 4 }}>Also counted as the client: the company name and the domain label are already included.</div>
        </div>
      </div>
    </div>);
}

function ProgressBar({ run }) {
  const total = run.units_total || 1;
  const done = (run.units_done || 0) + (run.units_failed || 0);
  return (
    <div>
      <div style={{ height: 8, borderRadius: 4, background: 'var(--navy)', border: '1px solid var(--line)', overflow: 'hidden' }}>
        <div style={{ width: `${Math.min(100, Math.round(100 * done / total))}%`, height: '100%', background: 'var(--accent)', transition: 'width .4s' }} />
      </div>
      <div className="mono" style={{ fontSize: 11.5, color: 'var(--fg-subtle)', marginTop: 6 }}>
        {done} of {run.units_total} answers · {run.units_failed || 0} errors · ${(run.cost_actual_usd || 0).toFixed(2)} spent of ~${run.cost_estimate_usd} estimated · tick {run.ticks || 0}
      </div>
    </div>);
}

function RawAnswers({ token, slug, run, onExpired }) {
  const prompts = run.prompts || [];
  const [pid, setPid] = React.useState(prompts[0] ? prompts[0].id : '');
  const [units, setUnits] = React.useState(null);
  React.useEffect(() => {
    if (!pid) return;
    setUnits(null);
    engineCall(token, { action: 'units', slug, run_id: run.id, prompt_id: pid })
      .then((d) => { if (d.status === 401) onExpired(); else setUnits(d.units || []); });
  }, [pid, run.id]);
  return (
    <div>
      <select value={pid} onChange={(e) => setPid(e.target.value)} style={{ ...tinyInput, marginBottom: 10 }}>
        {prompts.map((p) => <option key={p.id} value={p.id}>[{p.stage}] {p.text}</option>)}
      </select>
      {units === null && <div style={{ color: 'var(--fg-subtle)', fontSize: 13 }}>Loading…</div>}
      {units && units.length === 0 && <div style={{ color: 'var(--fg-subtle)', fontSize: 13 }}>No answers stored for this prompt yet.</div>}
      {units && units.map((u) => {
        const a = u.analysis || {}; const r = u.result || {};
        return (
          <div key={u.id} style={{ padding: '12px 14px', borderRadius: 'var(--r-md)', background: 'var(--navy)', border: '1px solid var(--line)', marginBottom: 8 }}>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', marginBottom: 6 }}>
              <span style={{ fontSize: 13, fontWeight: 600 }}>{ENGINE_SHORT[u.engine] || u.engine}</span>
              <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)' }}>{r.model} · run {u.rep} · {String(r.timestamp || '').slice(0, 16).replace('T', ' ')} · {r.latency_ms} ms</span>
              {r.error ? <Pill tone="crit">error</Pill>
                : <React.Fragment>
                    <Pill tone={a.brand_mentioned ? 'good' : 'warn'}>{a.brand_mentioned ? `named #${a.position || '?'}` : 'not named'}</Pill>
                    <Pill tone={a.brand_cited ? 'good' : 'fg-subtle'}>{a.brand_cited ? 'cited' : 'not cited'}</Pill>
                    {a.sentiment && <Pill tone="fg-subtle">{a.sentiment}</Pill>}
                    {(a.competitors_mentioned || []).map((c) => <Pill key={c.name} tone="accent">{c.name}</Pill>)}
                  </React.Fragment>}
            </div>
            {r.error
              ? <div className="mono" style={{ fontSize: 12, color: 'var(--crit)', whiteSpace: 'pre-wrap' }}>{r.error}</div>
              : <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>{r.answer || '(empty answer)'}</div>}
            {(a.cited_domains || []).length > 0 &&
            <div className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)', marginTop: 6 }}>cites: {a.cited_domains.join(', ')}</div>}
            <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-subtle)', marginTop: 4 }}>analysis: {a.method}</div>
          </div>);
      })}
    </div>);
}

function BenchmarkPanel({ slug, token, report, onExpired, onReportChanged }) {
  const [status, setStatus] = React.useState(null);
  const [library, setLibrary] = React.useState(null);
  const [runs, setRuns] = React.useState([]);
  const [run, setRun] = React.useState(null);
  const [engines, setEngines] = React.useState(null);
  const [reps, setReps] = React.useState(3);
  const [estimate, setEstimate] = React.useState(null);
  const [busy, setBusy] = React.useState('');
  const [flash, setFlash] = React.useState('');
  const [ticking, setTicking] = React.useState(false);
  const [showRaw, setShowRaw] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const tickingRef = React.useRef(false);

  const call = async (body) => {
    const d = await engineCall(token, body);
    if (d.status === 401) { onExpired(); throw new Error('expired'); }
    return d;
  };

  const loadAll = React.useCallback(async () => {
    try {
      const [s, l, r] = await Promise.all([
        call({ action: 'status', slug }), call({ action: 'library', slug }), call({ action: 'runs', slug })]);
      if (s.error === 'feature-off') { setStatus({ off: true }); return; }
      setStatus(s); setLibrary(l.library || null); setRuns(r.runs || []);
      if (engines === null && s.engines) { setEngines(s.engines.filter((e) => e.configured).map((e) => e.id)); setReps(s.reps_default || 3); }
      const latest = (r.benchmark || {}).latest_run_id;
      if (latest) {
        const d = await call({ action: 'run', slug, run_id: latest });
        if (d.ok) setRun(d.run);
      }
    } catch (e) { /* expired or offline */ }
  }, [slug, token]);

  React.useEffect(() => { loadAll(); }, [loadAll]);

  // Keep ticking while a run is active and this page is open.
  const tickLoop = React.useCallback(async (runId) => {
    if (tickingRef.current) return;
    tickingRef.current = true; setTicking(true);
    try {
      for (let i = 0; i < 400; i++) {
        const d = await call({ action: 'tick', slug, run_id: runId, owner: 'admin-page' });
        if (!d.ok) { setFlash(d.message || d.detail || 'Tick failed.'); break; }
        setRun((prev) => ({ ...(prev || {}), ...d.run, prompts: (prev && prev.prompts) || d.run.prompts }));
        if (d.busy) { await new Promise((res) => setTimeout(res, 8000)); continue; }
        if (d.remaining === 0 || ['done', 'partial', 'failed', 'cancelled'].includes(d.run.status)) break;
      }
    } catch (e) { /* expired */ }
    tickingRef.current = false; setTicking(false);
    const full = await call({ action: 'run', slug, run_id: runId }).catch(() => null);
    if (full && full.ok) setRun(full.run);
    const r = await call({ action: 'runs', slug }).catch(() => null);
    if (r && r.ok) setRuns(r.runs || []);
    onReportChanged();
  }, [slug, token]);

  React.useEffect(() => {
    if (run && (run.status === 'running' || run.status === 'queued') && !tickingRef.current) tickLoop(run.id);
  }, [run && run.id, run && run.status]);

  const act = async (body, after) => {
    setBusy(body.action); setFlash('');
    try {
      const d = await call(body);
      if (!d.ok) setFlash(d.message || d.detail || `${body.action} failed (HTTP ${d.status}).`);
      else if (after) after(d);
    } catch (e) { setFlash('Could not reach the server.'); }
    setBusy('');
  };

  if (!status) return <Panel title="Benchmark"><div style={{ color: 'var(--fg-subtle)', fontSize: 13 }}>Loading…</div></Panel>;
  if (status.off) return null;

  const configured = (status.engines || []).filter((e) => e.configured);
  const estimateNow = () => act({ action: 'estimate', slug, engines, reps }, (d) => { setEstimate(d.estimate); setStatus((s) => ({ ...s, ...d.status })); });
  const startNow = () => {
    const est = estimate;
    const msg = est ? `Start a run of ${est.calls} engine calls, estimated $${est.total_usd}? Today's spend so far: $${est.spent_today_usd} of a $${est.daily_cap_usd} daily cap.` : 'Start the run?';
    if (!window.confirm(msg)) return;
    act({ action: 'start', slug, engines, reps }, (d) => { setRun(d.run); setEstimate(null); });
  };
  const downloadCsv = () => act({ action: 'export', slug, run_id: run.id }, (d) => {
    const a = document.createElement('a');
    a.href = URL.createObjectURL(new Blob([d.csv], { type: 'text/csv' }));
    a.download = d.filename; a.click();
  });
  const active = run && (run.status === 'running' || run.status === 'queued');

  return (
    <Panel title={`Benchmark${run ? ` · latest run ${run.status}` : ' · not run yet'}`} tone={active ? 'accent' : undefined}>
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center', fontSize: 13, color: 'var(--fg-muted)' }}>
        <span>Engines: {configured.length ? configured.map((e) => `${ENGINE_SHORT[e.id]} (${e.model}${e.source && e.source !== 'lojo' ? `, ${e.source === 'agency' ? "the agency's key" : "this client's key"}` : ''})`).join(', ') : 'none — add an API key'}</span>
        {(status.engines || []).some((e) => !e.configured) && <span style={{ color: 'var(--fg-subtle)' }}>· {(status.engines || []).filter((e) => !e.configured).map((e) => ENGINE_SHORT[e.id]).join(', ')} need a key (an agency adds its own under Settings & keys; the Lojo team can add one for a single client)</span>}
        <span>·</span>
        <span>spent today ${Number(status.spent_today_usd || 0).toFixed(2)} of ${status.daily_cap_usd}; per-lead cap ${status.per_lead_cap_usd}</span>
        <span>·</span>
        <span>classifier {status.classifier ? 'on' : 'off'}</span>
        <button style={smallBtn()} onClick={() => setOpen((o) => !o)}>{open ? 'Hide setup' : 'Set up & run'}</button>
      </div>
      {flash && <div style={{ marginTop: 10, fontSize: 13.5, color: 'var(--warn)' }}>{flash}</div>}

      {open && library &&
      <React.Fragment>
        <LibraryEditor library={library} busy={busy}
          onSave={(prompts) => act({ action: 'library-save', slug, prompts }, (d) => setLibrary(d.library))}
          onLock={(locked) => act({ action: 'library-lock', slug, locked }, (d) => setLibrary(d.library))}
          onGenerate={() => act({ action: 'library-generate', slug }, (d) => setLibrary(d.library))} />
        <CompetitorsEditor report={report} busy={busy}
          onSave={(competitors, brand_aliases) => act({ action: 'competitors', slug, competitors, brand_aliases }, () => onReportChanged())} />
        <SubHead>Run</SubHead>
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'center', fontSize: 13.5 }}>
          {(status.engines || []).map((e) =>
          <label key={e.id} style={{ display: 'flex', gap: 6, alignItems: 'center', color: e.configured ? 'var(--fg)' : 'var(--fg-subtle)' }}>
            <input type="checkbox" disabled={!e.configured} checked={(engines || []).includes(e.id)}
              onChange={(ev) => setEngines((list) => ev.target.checked ? [...(list || []), e.id] : (list || []).filter((x) => x !== e.id))} />
            {ENGINE_SHORT[e.id]}{e.configured ? '' : ' (no key)'}
          </label>)}
          <label style={{ display: 'flex', gap: 6, alignItems: 'center' }}>runs per prompt
            <input type="number" min={1} max={10} value={reps} onChange={(e) => setReps(Math.max(1, Math.min(10, Number(e.target.value) || 1)))} style={{ ...tinyInput, width: 64 }} />
          </label>
          <button style={smallBtn()} disabled={!!busy || active} onClick={estimateNow}>Estimate cost</button>
          <button style={smallBtn('accent')} disabled={!!busy || active || !estimate || !estimate.within_caps} onClick={startNow}>Start run</button>
          {active && <button style={smallBtn('crit')} disabled={!!busy} onClick={() => act({ action: 'cancel', slug, run_id: run.id }, (d) => setRun((r) => ({ ...r, ...d.run })))}>Cancel run</button>}
        </div>
        {estimate &&
        <div style={{ marginTop: 10, fontSize: 13, color: estimate.within_caps ? 'var(--fg-muted)' : 'var(--crit)', lineHeight: 1.6 }}>
          {estimate.prompts} prompts × {estimate.engines.length} engines × {estimate.reps} runs = {estimate.calls} calls, about <b>${estimate.total_usd}</b>
          {estimate.classifier ? ` (incl. $${estimate.classifier_usd} classifier)` : ''} — {estimate.assumptions}.
          {!estimate.within_caps && ' Over a cap: lower the runs or engines, or raise BENCHMARK_MAX_COST_PER_LEAD_USD / BENCHMARK_DAILY_CAP_USD.'}
          {estimate.prompts < 5 && ' Save at least five prompts first.'}
        </div>}
      </React.Fragment>}

      {run &&
      <div style={{ marginTop: 16 }}>
        {active && <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginBottom: 8 }}>
          {ticking ? 'Running. Keep this page open; it processes the run in chunks and shows progress.' : 'Run is active; another page or the worker is processing it.'}
        </div>}
        <ProgressBar run={run} />
        {run.stopped_reason && <div style={{ fontSize: 13, color: 'var(--warn)', marginTop: 6 }}>Stopped: {run.stopped_reason}</div>}
        {run.metrics &&
        <div style={{ marginTop: 16 }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 12 }}>
            <button style={smallBtn()} disabled={!!busy} onClick={downloadCsv}>Download CSV</button>
            <button style={smallBtn()} onClick={() => setShowRaw((s) => !s)}>{showRaw ? 'Hide raw answers' : 'Raw answers'}</button>
          </div>
          {showRaw && <div style={{ marginBottom: 16 }}><RawAnswers token={token} slug={slug} run={run} onExpired={onExpired} /></div>}
          <BenchmarkResults b={{ ...run.metrics, run_id: run.id, finished_at: run.finished_at, status: run.status, methodology: run.methodology }} client={report.client} />
        </div>}
      </div>}

      {status.snapshots &&
      <div style={{ marginTop: 18 }}>
        <SubHead>Live snapshot · one question, every engine, now</SubHead>
        <SnapshotBox slug={slug} token={token} suggestions={(run && run.losses ? run.losses : []).map((l) => l.prompt)} />
      </div>}

      {run && run.metrics &&
      <div style={{ marginTop: 18 }}>
        <SubHead>Where competitors win · from this run</SubHead>
        <LossView losses={(run.losses || []).map((l) => ({ ...l, example: (l.examples || [])[0] }))} client={report.client} />
      </div>}

      {runs.length > 1 &&
      <div style={{ marginTop: 16 }}>
        <SubHead>Run history</SubHead>
        {runs.map((r) =>
        <div key={r.id} style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center', fontSize: 13, padding: '6px 0', borderBottom: '1px solid var(--line)' }}>
          <span className="mono" style={{ color: 'var(--fg-subtle)' }}>{String(r.started_at || '').slice(0, 16).replace('T', ' ')}</span>
          <Pill tone={r.status === 'done' ? 'good' : r.status === 'partial' ? 'warn' : 'fg-subtle'}>{r.status}</Pill>
          <span style={{ color: 'var(--fg-muted)' }}>{(r.engines || []).map((e) => ENGINE_SHORT[e] || e).join(', ')} · {r.units_done}/{r.units_total} answered · ${(r.cost_actual_usd || 0).toFixed(2)}</span>
          {run && run.id !== r.id && <button style={smallBtn()} onClick={() => act({ action: 'run', slug, run_id: r.id }, (d) => setRun(d.run))}>View</button>}
        </div>)}
      </div>}
    </Panel>);
}
