/* bigolab.jsx — BigOTutor: the Big-O growth bench. Built on window.BenchKit (harness) +
   window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.bigO — the SAME function server/benches/bigo.js calls, so
   client and server fields are identical by construction. Mirrors the gas-laws lab:
   controls → BenchFields.fn(state) → report + meters. */
(function () {
  const { useState, useMemo, useEffect } = React;
  const K = window.BenchKit, C = K.C, SVG_BG = K.SVG_BG, fmt = K.fmt;
  const TaskStrip = K.TaskStrip, StatMeter = K.StatMeter;
  const compute = (s) => window.BenchFields.bigO(s);
  const ALGOS = ["linear", "binary", "merge", "bubble"];
  const ALGO_COL = { linear: "#6cb6ff", binary: "#54f2b2", merge: "#ffce6b", bubble: "#ff7a6b" };

  function Slider({ label, value, set, min, max, step, color, onUp }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 9 }}>
        <span style={{ fontSize: 12, color: C.mute, width: 116 }}>{label}</span>
        <input type="range" min={min} max={max} step={step} value={value} onChange={(e) => set(parseInt(e.target.value, 10))} onPointerUp={onUp} style={{ flex: 1 }} />
        <span style={{ color: color || C.amber, width: 72, textAlign: "right", fontFamily: "monospace" }}>{value}</span>
      </div>
    );
  }

  function BigOFig({ task, setTask, tasks, report, event, done }) {
    const [n, setN] = useState(100);
    const [algorithm, setAlgorithm] = useState("bubble");
    const fld = useMemo(() => compute({ n, algorithm }), [n, algorithm]);
    useEffect(() => { report(fld); }, [n, algorithm]); // eslint-disable-line

    const t = tasks.find((x) => x.id === task) || tasks[0];
    // chart geometry — plot the four curves over n=1..N on a log-scaled y axis.
    const X0 = 60, X1 = 540, Y0 = 40, Y1 = 250, N = 100000;
    const opsOf = (algo, nn) => compute({ n: nn, algorithm: algo }).operations;
    const maxOps = N * N; // bubble at N — the curve ceiling
    const sx = (nn) => X0 + (Math.log10(Math.max(1, nn)) / Math.log10(N)) * (X1 - X0);
    const sy = (ops) => Y1 - (Math.log10(Math.max(1, ops)) / Math.log10(maxOps)) * (Y1 - Y0);
    const curve = (algo) => {
      const pts = [];
      for (let i = 0; i <= 40; i++) { const nn = Math.pow(N, i / 40); pts.push(`${sx(nn).toFixed(1)},${sy(opsOf(algo, nn)).toFixed(1)}`); }
      return pts.join(" ");
    };
    const px = sx(n), py = sy(fld.operations);

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={t && t.goal} />
        <svg viewBox="0 0 600 300" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          {/* axes */}
          <line x1={X0} y1={Y1} x2={X1} y2={Y1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={X0} y1={Y0} x2={X0} y2={Y1} stroke={C.faint} strokeWidth="1.5" />
          <text x={(X0 + X1) / 2} y={Y1 + 26} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">input size n (log)</text>
          <text x={X0 - 6} y={Y0 - 12} fill={C.mute} fontSize="11" fontFamily="monospace">operations (log)</text>
          {/* curves */}
          {ALGOS.map((a) => <polyline key={a} points={curve(a)} fill="none" stroke={ALGO_COL[a]} strokeWidth={a === algorithm ? 3 : 1.2} opacity={a === algorithm ? 1 : 0.45} />)}
          {/* current point */}
          <line x1={px} y1={Y0} x2={px} y2={Y1} stroke={C.line} strokeWidth="1" strokeDasharray="3 3" />
          <circle cx={px} cy={py} r={6} fill={ALGO_COL[algorithm]} stroke={C.ink} strokeWidth="1.5" />
          <text x={px} y={py - 12} textAnchor="middle" fill={C.ink} fontSize="11" fontFamily="monospace">{fmt(fld.operations, 0)} ops</text>
          {/* legend */}
          {ALGOS.map((a, i) => (
            <text key={a} x={X1 - 4} y={Y0 + 6 + i * 15} textAnchor="end" fill={ALGO_COL[a]} fontSize="10.5" fontFamily="monospace" fontWeight={a === algorithm ? 600 : 400}>{a}</text>
          ))}
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isQuadratic ? C.crimson : C.line}`, color: fld.isQuadratic ? C.crimson : C.mute, fontSize: 12.5, fontFamily: "monospace" }}>
          {algorithm} is {fld.complexityClass}: {fmt(fld.operations, 0)} ops at n = {n}. {fld.isQuadratic ? "⚠ quadratic — blows up fast." : "sub-quadratic — scales well."}
        </div>
        <Slider label="input size n" value={n} set={setN} min={1} max={100000} step={1} color={ALGO_COL[algorithm]} onUp={() => event("adjusted", `Set n = ${n}`, { response: `${fmt(fld.operations, 0)} ops` }, C.blue)} />
        <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
          {ALGOS.map((a) => (
            <button key={a} onClick={() => { setAlgorithm(a); event("selected", `Algorithm = ${a}`, { response: `${fmt(compute({ n, algorithm: a }).operations, 0)} ops` }, ALGO_COL[a]); }}
              style={{ flex: 1, padding: "8px 6px", borderRadius: 6, cursor: "pointer", fontFamily: "monospace", fontSize: 13,
                background: algorithm === a ? ALGO_COL[a] : C.panel2, color: algorithm === a ? "#0a1c2a" : C.mute, fontWeight: algorithm === a ? 600 : 400,
                border: `1px solid ${algorithm === a ? ALGO_COL[a] : C.line}` }}>{a}</button>
          ))}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="operations" v={fld.operations} d={0} color={fld.isQuadratic ? C.crimson : C.teal} />
          <StatMeter label="complexity" v={fld.complexityClass} color={C.amber} />
          <StatMeter label="n" v={fld.n} d={0} color={C.blue} />
          <StatMeter label="sub-quadratic" v={fld.subQuadratic ? "yes" : "no"} color={fld.subQuadratic ? C.teal : C.crimson} />
        </div>
      </>
    );
  }

  window.BigOTutor = K.makeTutor(BigOFig, { moduleLabel: "Big-O growth bench", benchId: "bigo" });
})();
