// Interactive ripple canvas - expanding circles on click, mouse follow, ambient waves

const RippleCanvas = ({ theme = 'aurora', intensity = 1 }) => {
  const canvasRef = React.useRef(null);
  const ripplesRef = React.useRef([]);
  const mouseRef = React.useRef({ x: 0, y: 0, active: false });
  const ambientRef = React.useRef([]);
  const rafRef = React.useRef(0);

  // Theme colors
  const themes = {
    aurora:   { bg: '#0C1814', fg: '0,212,168',   accent: '125,255,210' },
    midnight: { bg: '#0A1628', fg: '74,158,255',  accent: '150,200,255' },
    noir:     { bg: '#0A0A0A', fg: '255,255,255', accent: '200,200,200' },
  };

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = Math.min(window.devicePixelRatio || 1, 2);

    const resize = () => {
      const rect = canvas.getBoundingClientRect();
      canvas.width = rect.width * dpr;
      canvas.height = rect.height * dpr;
      ctx.scale(dpr, dpr);
    };
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    // Seed ambient ripples
    const rect = canvas.getBoundingClientRect();
    ambientRef.current = Array.from({ length: 6 }, () => ({
      x: Math.random() * rect.width,
      y: Math.random() * rect.height,
      r: Math.random() * 200,
      maxR: 300 + Math.random() * 400,
      speed: 0.15 + Math.random() * 0.25,
      seed: Math.random() * Math.PI * 2,
    }));

    // Auto-ripple scheduler: drop a click-style ripple at a random point periodically
    let autoTimer = 0;
    const scheduleNextAuto = () => {
      autoTimer = 3800 + Math.random() * 2000; // 3.8–5.8s
    };
    scheduleNextAuto();

    let t = 0;
    let lastTime = performance.now();
    const draw = () => {
      const now = performance.now();
      const dt = now - lastTime;
      lastTime = now;
      const rect = canvas.getBoundingClientRect();
      const w = rect.width, h = rect.height;
      t += 0.008;
      const colors = themes[theme] || themes.aurora;

      // Auto-fire random ripples
      autoTimer -= dt;
      if (autoTimer <= 0) {
        const pad = 80;
        ripplesRef.current.push({
          x: pad + Math.random() * Math.max(1, w - pad * 2),
          y: pad + Math.random() * Math.max(1, h - pad * 2),
          life: 0,
          maxR: (0.3 + Math.random() * 0.4) * Math.max(w, h),
          auto: true,
        });
        scheduleNextAuto();
      }

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

      // Ambient slow breathing circles (background depth)
      ambientRef.current.forEach((a, i) => {
        a.r += a.speed * intensity;
        if (a.r > a.maxR) {
          a.r = 0;
          a.x = Math.random() * w;
          a.y = Math.random() * h;
          a.maxR = 300 + Math.random() * 400;
        }
        const alpha = Math.sin((a.r / a.maxR) * Math.PI) * 0.06;
        ctx.strokeStyle = `rgba(${colors.fg}, ${alpha})`;
        ctx.lineWidth = 1;
        ctx.beginPath();
        // wavy ring
        const steps = 80;
        for (let s = 0; s <= steps; s++) {
          const ang = (s / steps) * Math.PI * 2;
          const wob = Math.sin(ang * 4 + t * 2 + a.seed) * 4 + Math.sin(ang * 7 + t + a.seed) * 2;
          const x = a.x + Math.cos(ang) * (a.r + wob);
          const y = a.y + Math.sin(ang) * (a.r + wob);
          if (s === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
        }
        ctx.stroke();
      });

      // Mouse-follow ripple (subtle)
      if (mouseRef.current.active) {
        const { x, y } = mouseRef.current;
        for (let i = 0; i < 3; i++) {
          const r = 30 + i * 28 + Math.sin(t * 3 + i) * 4;
          ctx.strokeStyle = `rgba(${colors.accent}, ${0.18 - i * 0.05})`;
          ctx.lineWidth = 1;
          ctx.beginPath();
          ctx.arc(x, y, r, 0, Math.PI * 2);
          ctx.stroke();
        }
      }

      // Click ripples (dramatic expanding)
      ripplesRef.current = ripplesRef.current.filter(r => r.life < 1);
      ripplesRef.current.forEach(r => {
        r.life += 0.012;
        const eased = 1 - Math.pow(1 - r.life, 3);
        const radius = eased * r.maxR;
        const baseAlpha = r.auto ? 0.5 : 0.8;
        const alpha = (1 - r.life) * baseAlpha;

        // multiple rings
        for (let i = 0; i < 3; i++) {
          const ringR = radius - i * 18;
          if (ringR <= 0) continue;
          ctx.strokeStyle = `rgba(${colors.accent}, ${alpha * (1 - i * 0.3)})`;
          ctx.lineWidth = 1.5 - i * 0.3;
          ctx.beginPath();
          const steps = 100;
          for (let s = 0; s <= steps; s++) {
            const ang = (s / steps) * Math.PI * 2;
            const wob = Math.sin(ang * 5 + t * 4) * 2;
            const x = r.x + Math.cos(ang) * (ringR + wob);
            const y = r.y + Math.sin(ang) * (ringR + wob);
            if (s === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
          }
          ctx.stroke();
        }

        // soft glow center
        const grad = ctx.createRadialGradient(r.x, r.y, 0, r.x, r.y, radius);
        grad.addColorStop(0, `rgba(${colors.accent}, ${alpha * 0.12})`);
        grad.addColorStop(1, `rgba(${colors.accent}, 0)`);
        ctx.fillStyle = grad;
        ctx.fillRect(r.x - radius, r.y - radius, radius * 2, radius * 2);
      });

      rafRef.current = requestAnimationFrame(draw);
    };
    draw();

    const onMove = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouseRef.current = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
        active: true,
      };
    };
    const onLeave = () => { mouseRef.current.active = false; };
    const onClick = (e) => {
      const rect = canvas.getBoundingClientRect();
      ripplesRef.current.push({
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
        life: 0,
        maxR: Math.max(rect.width, rect.height) * 0.6,
      });
    };

    const parent = canvas.parentElement;
    parent.addEventListener('mousemove', onMove);
    parent.addEventListener('mouseleave', onLeave);
    parent.addEventListener('click', onClick);

    return () => {
      cancelAnimationFrame(rafRef.current);
      ro.disconnect();
      parent.removeEventListener('mousemove', onMove);
      parent.removeEventListener('mouseleave', onLeave);
      parent.removeEventListener('click', onClick);
    };
  }, [theme, intensity]);

  return (
    <canvas
      ref={canvasRef}
      style={{
        position: 'absolute',
        inset: 0,
        width: '100%',
        height: '100%',
        pointerEvents: 'none',
      }}
    />
  );
};

window.RippleCanvas = RippleCanvas;
