// Solar grid: an interactive canvas backdrop for the hero.
// Renders a subtle solar-panel grid; orange "light" follows the cursor and
// drifts on scroll, illuminating cells nearest the pointer.

function SolarGrid() {
  const canvasRef = React.useRef(null);
  const stateRef = React.useRef({
    mouse: { x: -9999, y: -9999, active: false },
    drift: 0,
    rafId: 0,
    cells: [],
    w: 0, h: 0, dpr: 1,
  });

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const S = stateRef.current;

    function resize() {
      const r = canvas.getBoundingClientRect();
      S.dpr = Math.min(window.devicePixelRatio || 1, 2);
      S.w = r.width; S.h = r.height;
      canvas.width = Math.floor(r.width * S.dpr);
      canvas.height = Math.floor(r.height * S.dpr);
      ctx.setTransform(S.dpr, 0, 0, S.dpr, 0, 0);
      buildCells();
    }

    function buildCells() {
      // Solar-panel inspired layout: rectangles slightly taller than wide.
      const cellW = 56;
      const cellH = 64;
      const gap = 6;
      const cols = Math.ceil(S.w / (cellW + gap)) + 1;
      const rows = Math.ceil(S.h / (cellH + gap)) + 1;
      // offset so the grid is centered-ish
      const offX = -((cols * (cellW + gap)) - S.w) / 2;
      const offY = -((rows * (cellH + gap)) - S.h) / 2;
      const cells = [];
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
          cells.push({
            x: offX + c * (cellW + gap),
            y: offY + r * (cellH + gap),
            w: cellW, h: cellH,
            // tiny per-cell phase so the ambient shimmer isn't synchronized
            phase: Math.random() * Math.PI * 2,
          });
        }
      }
      S.cells = cells;
    }

    function onMove(e) {
      const r = canvas.getBoundingClientRect();
      S.mouse.x = e.clientX - r.left;
      S.mouse.y = e.clientY - r.top;
      S.mouse.active = true;
    }
    function onLeave() { S.mouse.active = false; }
    function onScroll() {
      S.drift = window.scrollY;
    }

    resize();
    onScroll();
    window.addEventListener("resize", resize);
    window.addEventListener("mousemove", onMove);
    canvas.addEventListener("mouseleave", onLeave);
    window.addEventListener("scroll", onScroll, { passive: true });

    let last = performance.now();
    function tick(now) {
      const dt = (now - last) / 1000;
      last = now;
      // drift the "active" point downward slightly with scroll for a parallax light feel
      const driftY = S.drift * 0.18;
      const mx = S.mouse.active ? S.mouse.x : S.w * 0.7;
      const my = S.mouse.active ? S.mouse.y : (S.h * 0.5 + Math.sin(now / 2200) * 60) - driftY;

      ctx.clearRect(0, 0, S.w, S.h);

      const t = now / 1000;
      const reach = 260; // px radius of mouse glow
      const reachSq = reach * reach;

      for (let i = 0; i < S.cells.length; i++) {
        const cell = S.cells[i];
        const cx = cell.x + cell.w / 2;
        const cy = cell.y + cell.h / 2;
        const dx = cx - mx;
        const dy = cy - my;
        const distSq = dx * dx + dy * dy;
        // ambient breathing — very subtle
        const ambient = 0.025 + 0.012 * Math.sin(t * 1.1 + cell.phase);
        let glow = 0;
        if (distSq < reachSq) {
          const d = Math.sqrt(distSq);
          glow = Math.pow(1 - d / reach, 2.2); // soft falloff
        }
        const intensity = ambient + glow * 0.55;

        // base panel cell — very dim orange, almost black
        const baseAlpha = 0.05 + ambient * 0.5;
        ctx.fillStyle = `rgba(240,127,33,${baseAlpha})`;
        ctx.fillRect(cell.x, cell.y, cell.w, cell.h);

        // glow overlay
        if (glow > 0.01) {
          ctx.fillStyle = `rgba(255,160,70,${glow * 0.55})`;
          ctx.fillRect(cell.x, cell.y, cell.w, cell.h);
        }

        // panel inner cross-lines (the silvery cell pattern of a real PV panel)
        ctx.strokeStyle = `rgba(255,165,80,${0.08 + glow * 0.35})`;
        ctx.lineWidth = 0.6;
        ctx.beginPath();
        ctx.moveTo(cell.x + cell.w / 2, cell.y + 4);
        ctx.lineTo(cell.x + cell.w / 2, cell.y + cell.h - 4);
        ctx.moveTo(cell.x + 4, cell.y + cell.h * 0.33);
        ctx.lineTo(cell.x + cell.w - 4, cell.y + cell.h * 0.33);
        ctx.moveTo(cell.x + 4, cell.y + cell.h * 0.66);
        ctx.lineTo(cell.x + cell.w - 4, cell.y + cell.h * 0.66);
        ctx.stroke();

        // hot-edge: bright top edge near the mouse, like reflection
        if (glow > 0.08) {
          ctx.strokeStyle = `rgba(255,200,120,${glow * 0.9})`;
          ctx.lineWidth = 1.2;
          ctx.strokeRect(cell.x + 0.5, cell.y + 0.5, cell.w - 1, cell.h - 1);
        }
      }

      // soft radial light layer for extra warmth at the cursor
      const grad = ctx.createRadialGradient(mx, my, 0, mx, my, reach * 1.3);
      grad.addColorStop(0, "rgba(240,127,33,0.18)");
      grad.addColorStop(0.5, "rgba(240,127,33,0.06)");
      grad.addColorStop(1, "rgba(240,127,33,0)");
      ctx.fillStyle = grad;
      ctx.fillRect(0, 0, S.w, S.h);

      S.rafId = requestAnimationFrame(tick);
    }
    S.rafId = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(S.rafId);
      window.removeEventListener("resize", resize);
      window.removeEventListener("mousemove", onMove);
      canvas.removeEventListener("mouseleave", onLeave);
      window.removeEventListener("scroll", onScroll);
    };
  }, []);

  return <canvas ref={canvasRef} className="ams-solar-grid" aria-hidden="true" />;
}

window.SolarGrid = SolarGrid;
