/* global React */
// MagMapper GPS Behavior Demo — conceptual visualization of GPS scatter,
// cell assignment, and survey strategies. NOT a precise simulator.

const { useState, useRef, useEffect, useCallback } = React;

// ---------- helpers ----------

function gaussianRandom() {
  // Box-Muller transform
  let u = 0, v = 0;
  while (u === 0) u = Math.random();
  while (v === 0) v = Math.random();
  return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
}

function gpsNoise(sigma) {
  // Heavy-tail mixture: 85% nominal, 15% multipath outlier (conceptual)
  const s = Math.random() < 0.85 ? sigma : sigma * 2.5;
  return { dx: gaussianRandom() * s, dy: gaussianRandom() * s };
}

function monopoleField(r, c, wellR, wellC, gridSize) {
  const dr = r - wellR, dc = c - wellC;
  const dist = Math.sqrt(dr * dr + dc * dc);
  return Math.max(0, 1 - dist / (gridSize * 0.45));
}

function heatColor(t) {
  // 0=cool blue  1=hot red  (matches tutorial --heat-0 … --heat-6)
  t = Math.max(0, Math.min(1, t));
  if (t < 0.17) return [60, 90, 180];
  if (t < 0.33) return [80, 140, 200];
  if (t < 0.50) return [100, 190, 140];
  if (t < 0.67) return [180, 200, 80];
  if (t < 0.83) return [220, 160, 50];
  return [200, 80, 40];
}

function generateBoustrophedon(gridSize) {
  // Row-by-row back-and-forth walking path through grid centers
  const path = [];
  for (let r = 0; r < gridSize; r++) {
    if (r % 2 === 0) {
      for (let c = 0; c < gridSize; c++) path.push({ r: r + 0.5, c: c + 0.5 });
    } else {
      for (let c = gridSize - 1; c >= 0; c--) path.push({ r: r + 0.5, c: c + 0.5 });
    }
  }
  return path;
}

// Detect light or dark theme from CSS custom property
function isLightTheme() {
  return document.documentElement.getAttribute('data-theme') === 'light';
}

// ---------- main component ----------

const MAX_AUTO_PASSES = 2;

function GPSDemo() {
  const canvasRef = useRef(null);
  const animRef = useRef(null);
  const stateRef = useRef(null);

  const [gpsQuality, setGpsQuality] = useState('moderate'); // good | moderate | poor
  const [cellSize, setCellSize] = useState(2);               // 2 | 3 | 5
  const [walking, setWalking] = useState('steady');           // stopped | steady
  const [running, setRunning] = useState(false);

  const sigmaMap = { good: 1.2, moderate: 2.4, poor: 4.0 };

  // Derive grid size from cell size so footprint stays ~22m
  const gridSize = cellSize === 2 ? 11 : cellSize === 3 ? 7 : 5;
  const footprint = gridSize * cellSize;

  const initState = useCallback(() => {
    const path = generateBoustrophedon(gridSize);
    const isWalking = walking === 'steady';
    // Walking: start at path[0] (top-left). Stopped: start at grid center
    // (on the anomaly) so the stacking demo shows visible signal.
    const startPos = isWalking
      ? { ...path[0] }
      : { r: gridSize / 2, c: gridSize / 2 };
    const startNoise = gpsNoise(sigmaMap[gpsQuality] / cellSize);
    const startGps = {
      r: startPos.r + startNoise.dy,
      c: startPos.c + startNoise.dx,
    };
    return {
      path,
      gridSize,
      cellSize,
      sigma: sigmaMap[gpsQuality],
      walking: isWalking,
      step: 0,
      passNum: 1,
      truePos: { ...startPos },
      displayGps: { ...startPos },  // blue arrow on screen (wanders freely)
      recordGps: { ...startGps },   // coordinate stamped on recorded data (noisy)
      lastGpsFix: { ...startPos },  // true pos at last GPS update
      ticksSinceGps: 0,             // frames since last recorded-GPS update
      recorded: [],          // { r, c, intensity }
      cellData: {},          // 'r,c' → [intensity, …]
      done: false,
    };
  }, [gridSize, cellSize, gpsQuality, walking]);

  const reset = useCallback(() => {
    if (animRef.current) cancelAnimationFrame(animRef.current);
    animRef.current = null;
    setRunning(false);
    stateRef.current = initState();
    drawFrame(stateRef.current);
  }, [initState]);

  useEffect(() => { reset(); }, [reset]);

  // ---------- draw ----------

  function drawFrame(s) {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const W = canvas.width, H = canvas.height;
    const px = W / s.gridSize; // pixels per cell

    const light = isLightTheme();

    ctx.clearRect(0, 0, W, H);

    // Background — light neutral to match strategy demo
    ctx.fillStyle = light ? '#f0f2ef' : '#e8eae6';
    ctx.fillRect(0, 0, W, H);

    // Grid lines
    ctx.strokeStyle = light ? 'rgba(0,0,0,0.12)' : 'rgba(0,0,0,0.15)';
    ctx.lineWidth = 0.5;
    for (let i = 0; i <= s.gridSize; i++) {
      ctx.beginPath(); ctx.moveTo(i * px, 0); ctx.lineTo(i * px, H); ctx.stroke();
      ctx.beginPath(); ctx.moveTo(0, i * px); ctx.lineTo(W, i * px); ctx.stroke();
    }

    // Filled cells (from recorded data — show median)
    for (const key of Object.keys(s.cellData)) {
      const [cr, cc] = key.split(',').map(Number);
      if (cr < 0 || cr >= s.gridSize || cc < 0 || cc >= s.gridSize) continue;
      const vals = s.cellData[key];
      // Median intensity
      const sorted = [...vals].sort((a, b) => a - b);
      const med = sorted[Math.floor(sorted.length / 2)];
      const [rr, gg, bb] = heatColor(med);
      const complete = vals.length >= 6; // simplified completeness for demo
      const inset = complete ? 0.5 : 2;
      const size = complete ? px - 1 : px - 4;
      ctx.fillStyle = `rgba(${rr},${gg},${bb},${complete ? 0.88 : 0.55})`;
      ctx.fillRect(cc * px + inset, cr * px + inset, size, size);
    }

    // Synthetic anomaly center hint (subtle crosshair)
    const wellR = s.gridSize / 2, wellC = s.gridSize / 2;
    ctx.strokeStyle = 'rgba(180,150,40,0.2)';
    ctx.lineWidth = 0.5;
    ctx.setLineDash([3, 3]);
    ctx.beginPath(); ctx.moveTo(wellC * px, 0); ctx.lineTo(wellC * px, H); ctx.stroke();
    ctx.beginPath(); ctx.moveTo(0, wellR * px); ctx.lineTo(W, wellR * px); ctx.stroke();
    ctx.setLineDash([]);

    // GPS accuracy circle (drawn at display position — the blue arrow)
    const gx = s.displayGps.c * px, gy = s.displayGps.r * px;
    const circleR = s.sigma * px / s.cellSize; // sigma in cell units → pixels
    ctx.fillStyle = 'rgba(60,120,220,0.07)';
    ctx.beginPath(); ctx.arc(gx, gy, circleR, 0, Math.PI * 2); ctx.fill();
    ctx.strokeStyle = 'rgba(60,120,220,0.3)';
    ctx.lineWidth = 1;
    ctx.beginPath(); ctx.arc(gx, gy, circleR, 0, Math.PI * 2); ctx.stroke();

    // Recorded sample dots (tiny) — show where data was actually assigned
    const maxDots = Math.min(s.recorded.length, 500);
    const startDot = s.recorded.length - maxDots;
    for (let i = startDot; i < s.recorded.length; i++) {
      const p = s.recorded[i];
      ctx.fillStyle = 'rgba(220,80,40,0.24)';
      ctx.beginPath();
      ctx.arc(p.c * px, p.r * px, 1.2, 0, Math.PI * 2);
      ctx.fill();
    }

    // Latest recorded coordinate marker. In stopped mode the larger stack
    // marker below takes over, so this is only needed while walking.
    if (s.walking && s.recorded.length > 0) {
      const latest = s.recorded[s.recorded.length - 1];
      ctx.strokeStyle = 'rgba(220,80,40,0.75)';
      ctx.lineWidth = 1.4;
      ctx.beginPath();
      ctx.arc(latest.c * px, latest.r * px, 4.5, 0, Math.PI * 2);
      ctx.stroke();
    }

    // In stopped mode, show stacked-sample indicator at the frozen GPS fix
    if (!s.walking && s.recorded.length > 0) {
      const rx = s.recordGps.c * px, ry = s.recordGps.r * px;
      // Growing orange ring to show accumulation
      const stackR = Math.min(4 + s.recorded.length * 0.08, 18);
      ctx.strokeStyle = 'rgba(220,80,40,0.6)';
      ctx.lineWidth = 2;
      ctx.beginPath(); ctx.arc(rx, ry, stackR, 0, Math.PI * 2); ctx.stroke();
      // Pulsing fill to draw attention
      const pulse = 0.08 + 0.04 * Math.sin(s.recorded.length * 0.15);
      ctx.fillStyle = `rgba(220,80,40,${pulse})`;
      ctx.beginPath(); ctx.arc(rx, ry, stackR, 0, Math.PI * 2); ctx.fill();
      // Count label
      ctx.fillStyle = 'rgba(200,60,30,0.85)';
      ctx.font = 'bold 10px Inter, system-ui, sans-serif';
      ctx.fillText(`${s.recorded.length} readings`, rx + stackR + 4, ry - 2);
      ctx.font = '9px Inter, system-ui, sans-serif';
      ctx.fillStyle = 'rgba(200,60,30,0.6)';
      const filledCells = Object.keys(s.cellData).length;
      ctx.fillText(`${filledCells} cell${filledCells !== 1 ? 's' : ''} filled`, rx + stackR + 4, ry + 10);
    }

    // True position (green dot)
    const tx = s.truePos.c * px, ty = s.truePos.r * px;
    ctx.fillStyle = 'rgba(76,175,80,0.25)';
    ctx.beginPath(); ctx.arc(tx, ty, 8, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = '#388E3C';
    ctx.beginPath(); ctx.arc(tx, ty, 4, 0, Math.PI * 2); ctx.fill();

    // GPS position (blue arrow dot)
    ctx.fillStyle = 'rgba(60,120,220,0.3)';
    ctx.beginPath(); ctx.arc(gx, gy, 6, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = '#2962FF';
    ctx.beginPath(); ctx.arc(gx, gy, 3.5, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = '#fff';
    ctx.beginPath(); ctx.arc(gx, gy, 1.5, 0, Math.PI * 2); ctx.fill();

    // Legend
    const textCol = 'rgba(0,0,0,0.45)';
    ctx.font = '9px Inter, system-ui, sans-serif';
    const lx = 6, ly = H - 6;
    ctx.fillStyle = '#388E3C';
    ctx.beginPath(); ctx.arc(lx + 4, ly - 3, 3, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = textCol;
    ctx.fillText('true position', lx + 10, ly);
    ctx.fillStyle = '#2962FF';
    ctx.beginPath(); ctx.arc(lx + 90, ly - 3, 3, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = textCol;
    ctx.fillText('GPS estimate', lx + 96, ly);
    ctx.fillStyle = '#DC5028';
    ctx.beginPath(); ctx.arc(lx + 185, ly - 3, 3, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = textCol;
    ctx.fillText('recorded fix', lx + 191, ly);

    // Grid info label
    ctx.fillStyle = 'rgba(0,0,0,0.3)';
    ctx.fillText(`${s.gridSize}\u00d7${s.gridSize} \u00b7 ${s.cellSize}m cells \u00b7 ~${footprint}m`, 6, 12);

    // Status — pass counter + progress
    ctx.fillStyle = 'rgba(0,0,0,0.4)';
    if (s.done) {
      ctx.fillText(`Done \u2014 ${s.passNum} pass${s.passNum > 1 ? 'es' : ''} complete`, 6, 24);
    } else if (s.walking && s.step > 0) {
      const passProgress = Math.round(((s.step % s.path.length) / s.path.length) * 100);
      ctx.fillText(`Pass ${s.passNum} \u2014 ${passProgress}%`, 6, 24);
    } else if (!s.walking && s.recorded.length > 0) {
      ctx.fillText(`Stopped \u2014 ${s.recorded.length} readings, 1 GPS coord \u2014 no spatial coverage`, 6, 24);
    }
  }

  // ---------- animate ----------

  function tick() {
    const s = stateRef.current;
    if (!s || s.done) { setRunning(false); return; }

    const target = s.path[s.step];

    // Display GPS (blue arrow) wanders on every frame regardless of movement
    const displayNoise = gpsNoise(s.sigma / s.cellSize);
    s.displayGps = {
      r: s.truePos.r + displayNoise.dy,
      c: s.truePos.c + displayNoise.dx,
    };

    if (s.walking) {
      // Move true position toward target
      const speed = 0.22; // cells per tick
      const dr = target.r - s.truePos.r;
      const dc = target.c - s.truePos.c;
      const dist = Math.sqrt(dr * dr + dc * dc);
      if (dist < speed) {
        s.truePos = { ...target };
        s.step++;

        // End of one full pass through the grid
        if (s.step >= s.path.length) {
          if (s.passNum >= MAX_AUTO_PASSES) {
            s.done = true;
          } else {
            // Start next pass — teleport back, keep cellData so median improves
            s.passNum++;
            s.step = 0;
            s.truePos = { ...s.path[0] };
            s.lastGpsFix = { ...s.truePos };
            const n = gpsNoise(s.sigma / s.cellSize);
            s.recordGps = { r: s.truePos.r + n.dy, c: s.truePos.c + n.dx };
          }
        }
      } else {
        s.truePos.r += (dr / dist) * speed;
        s.truePos.c += (dc / dist) * speed;
      }

      // Recorded GPS updates after ~1m movement (distanceFilter: 1)
      const gpsDist = Math.sqrt(
        (s.truePos.r - s.lastGpsFix.r) ** 2 +
        (s.truePos.c - s.lastGpsFix.c) ** 2
      );
      const distFilter = 1.0 / s.cellSize; // 1m in cell units
      if (gpsDist >= distFilter) {
        const noise = gpsNoise(s.sigma / s.cellSize);
        s.recordGps = {
          r: s.truePos.r + noise.dy,
          c: s.truePos.c + noise.dx,
        };
        s.lastGpsFix = { ...s.truePos };
      }
    } else {
      // Stopped: recorded GPS does NOT update (no movement exceeds
      // distanceFilter). The blue arrow still wanders (displayGps above),
      // but all recorded samples reuse the same last fix.
      s.ticksSinceGps++;
    }

    // Measure magnetic field at TRUE position, stamp with RECORDED GPS
    const wellR = s.gridSize / 2, wellC = s.gridSize / 2;
    const intensity = monopoleField(s.truePos.r, s.truePos.c, wellR, wellC, s.gridSize);
    s.recorded.push({ r: s.recordGps.r, c: s.recordGps.c, intensity });

    // Assign to grid cell based on recorded GPS (not true position)
    const cr = Math.floor(s.recordGps.r);
    const cc = Math.floor(s.recordGps.c);
    if (cr >= 0 && cr < s.gridSize && cc >= 0 && cc < s.gridSize) {
      const key = `${cr},${cc}`;
      if (!s.cellData[key]) s.cellData[key] = [];
      s.cellData[key].push(intensity);
    }

    // Stopped mode: auto-stop after ~200 ticks
    if (!s.walking && s.recorded.length > 200) {
      s.done = true;
    }

    drawFrame(s);

    if (!s.done) {
      animRef.current = requestAnimationFrame(tick);
    } else {
      setRunning(false);
    }
  }

  function start() {
    reset();
    setTimeout(() => {
      setRunning(true);
      if (stateRef.current) stateRef.current.done = false;
      animRef.current = requestAnimationFrame(tick);
    }, 60);
  }

  function stop() {
    const s = stateRef.current;
    if (s) s.done = true;
    if (animRef.current) cancelAnimationFrame(animRef.current);
    animRef.current = null;
    setRunning(false);
    if (s) drawFrame(s);
  }

  // Cleanup on unmount
  useEffect(() => {
    return () => { if (animRef.current) cancelAnimationFrame(animRef.current); };
  }, []);

  return (
    <div className="gps-demo">
      <canvas
        ref={canvasRef}
        width={320}
        height={320}
        className="gps-demo-canvas"
        aria-label="GPS behavior demo showing true position, GPS estimate, and grid cell filling"
      />
      <div className="gps-demo-controls">
        <div className="gps-control-row">
          <label>GPS quality</label>
          <div className="tabs mini">
            {[['good', 'Good'], ['moderate', 'Moderate'], ['poor', 'Poor']].map(([k, l]) => (
              <button key={k} className={`tab ${gpsQuality === k ? 'active' : ''}`}
                onClick={() => setGpsQuality(k)}>{l}</button>
            ))}
          </div>
        </div>
        <div className="gps-control-row">
          <label>Cell size</label>
          <div className="tabs mini">
            {[2, 3, 5].map(v => (
              <button key={v} className={`tab ${cellSize === v ? 'active' : ''}`}
                onClick={() => setCellSize(v)}>{v}m</button>
            ))}
          </div>
        </div>
        <div className="gps-control-row">
          <label>Walking</label>
          <div className="tabs mini">
            {[['stopped', 'Stopped'], ['steady', 'Steady']].map(([k, l]) => (
              <button key={k} className={`tab ${walking === k ? 'active' : ''}`}
                onClick={() => setWalking(k)}>{l}</button>
            ))}
          </div>
        </div>
        <button className="gps-demo-run" onClick={running ? stop : start}>
          {running ? 'Stop' : 'Run demo'}
        </button>
      </div>
      <div className="gps-demo-note">
        This demo illustrates GPS behavior conceptually. Actual accuracy varies by device, sky view, and environment.
      </div>
    </div>
  );
}

Object.assign(window, { GPSDemo });
