/* hashinglab.jsx — HashingTutor: the hash-table load-factor bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.hashing — the SAME function server/benches/hashing.js calls, so
   client and server fields are identical by construction. Mirrors the networking lab: sliders →
   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.hashing(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: 140 }}><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: 70, textAlign: "right" }}>{value}{unit ? ` ${unit}` : ""}</span>
      </div>
    );
  }

  function HashingFig({ task, setTask, tasks, report, event, done }) {
    const [tableSize, setTableSize] = useState(32);
    const [itemsInserted, setItemsInserted] = useState(16);
    const fld = useMemo(() => compute({ tableSize, itemsInserted }), [tableSize, itemsInserted]);
    useEffect(() => { report(fld); }, [tableSize, itemsInserted]); // eslint-disable-line

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

    // Slot grid: up to 64 cells laid out in a 16-wide grid; each cell filled (teal) up to the
    // number of inserted items. When the table is bigger than 64 we draw a proportional sketch.
    const SHOWN = Math.min(tableSize, 64);
    const COLS = 16, CW = 30, CH = 18, GAP = 4, X0 = 40, Y0 = 56;
    const filledShown = Math.round((Math.min(itemsInserted, tableSize) / tableSize) * SHOWN);

    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 }}>
          <text x={40} y={36} fill={C.ink} fontSize="13" fontFamily="monospace">α = n/m = {itemsInserted}/{tableSize} = {fmt(fld.loadFactor)}{tableSize > 64 ? "  (showing a 64-slot sketch)" : ""}</text>
          {Array.from({ length: SHOWN }).map((_, i) => {
            const r = Math.floor(i / COLS), c = i % COLS;
            const x = X0 + c * (CW + GAP), y = Y0 + r * (CH + GAP);
            const on = i < filledShown;
            return <rect key={i} x={x} y={y} width={CW} height={CH} rx="3" fill={on ? (over ? C.crimson : C.teal) : C.panel} stroke={on ? (over ? C.crimson : C.teal) : C.line} strokeWidth="1" opacity={on ? 0.9 : 1} />;
          })}
          <text x={40} y={232} fill={over ? C.crimson : C.mute} fontSize="12" fontFamily="monospace">P(collision) ≈ {Math.round(fld.collisionProb * 100)}%   ·   avg probes ≈ {fmt(fld.expectedProbes)}   ·   {fld.emptySlots} empty</text>
          <text x={40} y={256} fill={C.faint} fontSize="11" fontFamily="monospace">birthday: P ≈ 1 − e^(−n(n−1)/2m)   ·   open addressing: probes ≈ 1/(1−α)</text>
          {over && <text x={40} y={280} fill={C.crimson} fontSize="11" fontFamily="monospace">⚠ overloaded (α &gt; 0.75) — resize or the table will thrash</text>}
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${over ? C.crimson : C.line}`, color: over ? C.crimson : C.mute, fontSize: 12.5 }}>
          {fld.isFull ? <>⚠ <K.T>the table is full — every open-addressing lookup probes the whole table.</K.T></> : over ? <><K.T>Overloaded: lookups now cost</K.T> {fmt(fld.expectedProbes)} <K.T>probes on average.</K.T></> : <K.T>Add items to raise α; enlarge the table to cut collisions and probes. Watch the birthday effect — collisions get likely while the table is still mostly empty.</K.T>}
        </div>
        <Slider label="table size m" value={tableSize} set={setTableSize} min={8} max={256} step={1} unit="slots" color={C.blue} onUp={() => event("resized", `Set table size = ${tableSize}`, { response: `α = ${fmt(fld.loadFactor)}` }, C.blue)} />
        <Slider label="items inserted n" value={itemsInserted} set={setItemsInserted} min={0} max={256} step={1} unit="" color={C.teal} onUp={() => event("inserted", `Set items = ${itemsInserted}`, { response: `α = ${fmt(fld.loadFactor)}, probes ≈ ${fmt(fld.expectedProbes)}` }, C.teal)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="load factor α" v={fld.loadFactor} d={2} color={over ? C.crimson : C.teal} />
          <StatMeter label="collision prob" v={fld.collisionProb} d={3} color={C.amber} />
          <StatMeter label="avg probes" v={fld.expectedProbes} d={2} color={over ? C.crimson : C.blue} />
          <StatMeter label="empty slots" v={fld.emptySlots} d={0} color={C.gold} />
        </div>
      </>
    );
  }

  window.HashingTutor = K.makeTutor(HashingFig, { moduleLabel: "Hash-table bench", benchId: "hashing" });
})();
