/* eslint-disable */
// useLivePnl — generates a jittering "live" PnL delta per driver.
// Returns an object { [code]: deltaPoints } that updates every 1.8s.
// Components compose a driver's display PnL as:
//     base (realized + unrealized) + delta
// We deliberately keep deltas small (±2pt random walk, bounded) so the
// numbers feel alive without becoming silly.

function useLivePnl(drivers) {
  const [deltas, setDeltas] = React.useState(() => {
    const init = {};
    drivers.forEach(d => { init[d.code] = 0; });
    return init;
  });

  React.useEffect(() => {
    const id = setInterval(() => {
      setDeltas(prev => {
        const next = {};
        drivers.forEach(d => {
          // small random walk, slight mean-reversion toward 0 so it doesn't drift
          const cur = prev[d.code] ?? 0;
          const step = (Math.random() - 0.5) * 3;        // ±1.5 pt
          const pull = -cur * 0.05;                       // mild mean-revert
          const v = cur + step + pull;
          // bound to ±6 pt so numbers stay believable
          next[d.code] = Math.max(-6, Math.min(6, v));
        });
        return next;
      });
    }, 1800);
    return () => clearInterval(id);
  }, [drivers]);

  return deltas;
}

// Compute a driver's *base* live PnL — realized + unrealized — from the
// strings on the data record. Returns a number (may be 0).
function basePnl(d) {
  const parse = (s) => {
    if (!s || s === "—") return 0;
    const n = parseInt(String(s).replace(/[^\d+\-−]/g, "").replace("−", "-"), 10);
    return isNaN(n) ? 0 : n;
  };
  return parse(d.realized) + parse(d.unreal);
}

// Format with sign and "pt" suffix.
function fmtPt(n) {
  const r = Math.round(n);
  return (r >= 0 ? "+" : "") + r + " pt";
}

window.useLivePnl = useLivePnl;
window.basePnl   = basePnl;
window.fmtPt     = fmtPt;
