/* avgvaluelab.jsx — AvgValueTutor: the average-value-of-a-function bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just the
   FIGURE. computeFields = window.BenchFields.avgvalue — the SAME function
   server/benches/avgvalue.js calls, so client and server fields are identical by construction.
   The learner slides the interval [a,b]; the average value f̄ of f(x)=x² is drawn as the height of
   the rectangle on [a,b] with the same area as the region under the curve, and the point c where
   f(c)=f̄ (the MVT-for-integrals point, c=√f̄) is marked where the curve crosses the average. */
(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.avgvalue(s);

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

  function AvgValueFig({ task, setTask, tasks, report, event, done }) {
    const [a, setA] = useState(0);
    const [b, setB] = useState(3);
    const fld = useMemo(() => compute({ a, b }), [a, b]);
    useEffect(() => { report(fld); }, [a, b]); // eslint-disable-line

    // plot y = x² over the visible x-range, shade the region under the curve on [a,b],
    // draw a horizontal line at the average value forming the equal-area rectangle,
    // and mark the point c = √f̄ where the curve crosses the average.
    const X0 = 60, X1 = 380, baseY = 250, plotTop = 30, plotH = baseY - plotTop;
    const aa = Math.max(0, a), bb = Math.max(aa + 0.1, b);
    const xMax = 5;                                  // slider b max
    const yMax = xMax * xMax;                         // f(xMax) = 25, the tallest plottable value
    const xScale = (X1 - X0) / xMax;
    const yScale = plotH / yMax;
    const px = (x) => X0 + x * xScale;
    const py = (y) => baseY - y * yScale;
    // the full curve y = x² across the visible range
    const STEPS = 60;
    let curve = "";
    for (let i = 0; i <= STEPS; i++) { const x = (i / STEPS) * xMax; curve += `${i ? "L" : "M"} ${px(x).toFixed(1)} ${py(x * x).toFixed(1)} `; }
    // shaded region under the curve on [a,b]
    let region = `M ${px(aa).toFixed(1)} ${baseY.toFixed(1)} `;
    for (let i = 0; i <= STEPS; i++) { const x = aa + (i / STEPS) * (bb - aa); region += `L ${px(x).toFixed(1)} ${py(x * x).toFixed(1)} `; }
    region += `L ${px(bb).toFixed(1)} ${baseY.toFixed(1)} Z`;
    const avgY = py(fld.average);
    const cx = px(fld.cPoint), cy = py(fld.average);

    const t = tasks.find((x) => x.id === task) || tasks[0];

    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 }}>
          {/* shaded area under the curve on [a,b] */}
          <path d={region} fill={C.blue} fillOpacity="0.18" stroke="none" />
          {/* the equal-area rectangle on [a,b] at height f̄ */}
          <rect x={px(aa).toFixed(1)} y={avgY.toFixed(1)} width={Math.max(0.6, (px(bb) - px(aa))).toFixed(1)} height={Math.max(0, baseY - avgY).toFixed(1)} fill={C.teal} fillOpacity="0.12" stroke={C.teal} strokeWidth="1" strokeDasharray="4 3" />
          {/* axes */}
          <line x1={X0} y1={baseY} x2={X1 + 4} y2={baseY} stroke={C.faint} strokeWidth="1.2" />
          <line x1={X0} y1={baseY} x2={X0} y2={plotTop} stroke={C.faint} strokeWidth="1.2" />
          {/* the curve y = x² */}
          <path d={curve} fill="none" stroke={C.gold} strokeWidth="2" />
          {/* horizontal line at the average value f̄ */}
          <line x1={X0} y1={avgY.toFixed(1)} x2={X1 + 4} y2={avgY.toFixed(1)} stroke={C.teal} strokeWidth="1.6" />
          {/* marker at the MVT point c where f(c)=f̄ */}
          <line x1={cx.toFixed(1)} y1={cy.toFixed(1)} x2={cx.toFixed(1)} y2={baseY.toFixed(1)} stroke={C.amber} strokeWidth="1" strokeDasharray="3 3" />
          <circle cx={cx.toFixed(1)} cy={cy.toFixed(1)} r="4.5" fill={C.amber} stroke={C.line} strokeWidth="0.8" />
          <text x={cx.toFixed(1)} y={baseY + 14} fill={C.amber} fontSize="10" fontFamily="monospace" textAnchor="middle">c = {fmt(fld.cPoint)}</text>
          {/* bound labels */}
          <text x={px(aa).toFixed(1)} y={baseY + 26} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">a = {fmt(aa)}</text>
          <text x={px(bb).toFixed(1)} y={baseY + 26} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">b = {fmt(bb)}</text>
          {/* readout panel on the right */}
          <text x={X1 + 36} y={40} fill={C.mute} fontSize="12" fontFamily="monospace">f(x) = x² on [a,b]</text>
          <text x={X1 + 36} y={66} fill={C.teal} fontSize="13" fontFamily="monospace">average f̄ = {fmt(fld.average)}</text>
          <text x={X1 + 36} y={88} fill={C.blue} fontSize="13" fontFamily="monospace">∫ = {fmt(fld.integral)}</text>
          <text x={X1 + 36} y={110} fill={C.amber} fontSize="13" fontFamily="monospace">c = √f̄ = {fmt(fld.cPoint)}</text>
          <text x={X1 + 36} y={132} fill={C.mute} fontSize="12" fontFamily="monospace">width = {fmt(fld.width)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${C.teal}`, color: C.mute, fontSize: 12.5 }}>
          Average value f̄ = (1/(b−a))∫_a^b x² dx = {fmt(fld.average)} — the height of the equal-area rectangle. <K.T>The curve attains its average at c = √f̄ =</K.T> {fmt(fld.cPoint)} <K.T>(MVT for integrals).</K.T>
        </div>
        <Slider label="left a" value={a} set={setA} min={0} max={3} step={0.5} unit="" color={C.teal} onUp={() => event("adjusted", `Set a = ${fmt(a)}`, { response: `average ${fmt(fld.average)}` }, C.teal)} />
        <Slider label="right b" value={b} set={setB} min={1} max={5} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set b = ${fmt(b)}`, { response: `average ${fmt(fld.average)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="average f̄" v={fld.average} d={2} color={C.teal} />
          <StatMeter label="integral" v={fld.integral} d={2} color={C.blue} />
          <StatMeter label="MVT point c" v={fld.cPoint} d={3} color={C.amber} />
          <StatMeter label="width" v={fld.width} d={2} color={C.gold} />
        </div>
      </>
    );
  }

  window.AvgValueTutor = K.makeTutor(AvgValueFig, { moduleLabel: "Average Value of a Function bench", benchId: "avgvalue" });
})();
