/* improperlab.jsx — ImproperTutor: the improper-integrals bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just the
   FIGURE. computeFields = window.BenchFields.improper — the SAME function
   server/benches/improper.js calls, so client and server fields are identical by construction.
   The learner sets the exponent p and the upper limit b; the area under y = x⁻ᵖ on [1,b] makes
   the partial integral ∫₁ᵇ x⁻ᵖ dx visible as it converges (p>1) onto the limit 1/(p−1) or grows
   without bound (p≤1). */
(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.improper(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 ImproperFig({ task, setTask, tasks, report, event, done }) {
    const [p, setP] = useState(2);
    const [b, setB] = useState(10);
    const fld = useMemo(() => compute({ p, b }), [p, b]);
    useEffect(() => { report(fld); }, [p, b]); // eslint-disable-line

    // plot y = x⁻ᵖ over [1, bScaled] with the area under the curve shaded.
    const X0 = 60, X1 = 380, baseY = 250, topY = 40, plotW = X1 - X0, plotH = baseY - topY;
    const pe = Math.max(0.5, p);
    const bb = Math.max(1.1, b);
    const xR = Math.min(bb, 60);                 // cap the visible right edge of the x-window
    const f = (x) => Math.pow(x, -pe);
    const yMax = f(1) || 1;                       // y = x⁻ᵖ peaks at x = 1
    const xScale = plotW / (xR - 1 || 1);
    const yScale = plotH / (yMax || 1);
    const px = (x) => X0 + (x - 1) * xScale;
    const py = (y) => baseY - y * yScale;
    const N = 80;
    let curve = `M ${px(1).toFixed(1)} ${py(f(1)).toFixed(1)}`;
    let area = `M ${px(1).toFixed(1)} ${baseY.toFixed(1)} L ${px(1).toFixed(1)} ${py(f(1)).toFixed(1)}`;
    for (let i = 1; i <= N; i++) {
      const x = 1 + (xR - 1) * (i / N), Y = py(f(x)).toFixed(1), X = px(x).toFixed(1);
      curve += ` L ${X} ${Y}`;
      area += ` L ${X} ${Y}`;
    }
    area += ` L ${px(xR).toFixed(1)} ${baseY.toFixed(1)} Z`;

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const limY = (fld.converges && fld.limitValue * yScale < plotH) ? py(fld.limitValue) : null; // dashed limit line (height of the limit area is hard to draw; mark the limit value)

    const okColor = fld.approachesLimit ? C.teal : (fld.converges ? C.amber : C.amber);
    const statusColor = fld.approachesLimit ? C.teal : C.amber;

    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 = the partial integral ∫₁ᵇ x⁻ᵖ */}
          <path d={area} fill={C.blue} fillOpacity="0.22" stroke="none" />
          {/* the curve y = x⁻ᵖ */}
          <path d={curve} fill="none" stroke={C.gold} strokeWidth="2" />
          {/* 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={topY} stroke={C.faint} strokeWidth="1.2" />
          {/* dashed line at the limit value when convergent */}
          {fld.converges && limY != null && <line x1={X0} y1={limY} x2={X1 + 4} y2={limY} stroke={C.teal} strokeWidth="1" strokeDasharray="4 3" />}
          {fld.converges && limY != null && <text x={X1 + 6} y={limY - 3} fill={C.teal} fontSize="9" fontFamily="monospace">limit 1/(p−1)</text>}
          {/* b→∞ arrow toward the right edge */}
          <line x1={px(Math.min(xR, bb))} y1={topY + 8} x2={X1 + 2} y2={topY + 8} stroke={C.mute} strokeWidth="1" strokeDasharray="3 2" />
          <text x={X1 + 6} y={topY + 11} fill={C.mute} fontSize="9" fontFamily="monospace">b→∞</text>
          {/* bound labels */}
          <text x={X0} y={baseY + 16} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">1</text>
          <text x={px(xR)} y={baseY + 16} 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">∫₁ᵇ x⁻ᵖ dx, p = {fmt(pe)}</text>
          <text x={X1 + 36} y={66} fill={C.blue} fontSize="13" fontFamily="monospace">partial = {fmt(fld.partial)}</text>
          <text x={X1 + 36} y={88} fill={C.teal} fontSize="13" fontFamily="monospace">limit = {fld.converges ? fmt(fld.limitValue) : "∞"}</text>
          <text x={X1 + 36} y={110} fill={okColor} fontSize="13" fontFamily="monospace">gap = {fmt(fld.gap)}</text>
          <text x={X1 + 36} y={132} fill={C.mute} fontSize="12" fontFamily="monospace">{fld.converges ? "converges (p>1)" : "diverges (p≤1)"}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${statusColor}`, color: statusColor, fontSize: 12.5 }}>
          Partial integral ∫₁ᵇ x⁻ᵖ dx = {fmt(fld.partial)}. {fld.approachesLimit ? <>⚑ <K.T>Approaching the limit — the tail gap has shrunk below 0.05.</K.T></> : (fld.converges ? <K.T>Converges (p &gt; 1) — push b out to shrink the tail gap onto the limit.</K.T> : <K.T>Diverges (p ≤ 1) — at or below the 1/x boundary the area grows without bound.</K.T>)}
        </div>
        <Slider label="exponent p" value={p} set={setP} min={0.5} max={3} step={0.1} unit="" color={C.gold} onUp={() => event("adjusted", `Set p = ${fmt(p)}`, { response: fld.converges ? `converges, limit ${fmt(fld.limitValue)}` : "diverges" }, C.gold)} />
        <Slider label="upper limit b" value={b} set={setB} min={2} max={200} step={2} unit="" color={C.blue} onUp={() => event("adjusted", `Set b = ${fmt(b)}`, { response: `gap ${fmt(fld.gap)}` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="partial" v={fld.partial} d={3} color={C.blue} />
          <StatMeter label="limit" v={fld.limitValue} d={3} color={C.teal} />
          <StatMeter label="gap" v={fld.gap} d={3} color={okColor} />
          <StatMeter label="p" v={fld.pValue} d={2} color={C.gold} />
        </div>
      </>
    );
  }

  window.ImproperTutor = K.makeTutor(ImproperFig, { moduleLabel: "Improper Integrals bench", benchId: "improper" });
})();
