/* FluidHero.jsx — じぶん湯 Hero Background Animation */
'use strict';

function FluidHero() {
  const canvasRef = React.useRef(null);
  const animRef = React.useRef(null);

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

    const colors = ['#b4563a', '#34486e', '#c4aa6c', '#5c7a4e'];

    const resize = () => {
      canvas.width  = canvas.offsetWidth;
      canvas.height = canvas.offsetHeight;
    };
    resize();
    window.addEventListener('resize', resize);

    // Blob state
    const blobs = colors.map((color, i) => ({
      x: (canvas.width / 5) * (i + 1),
      y: canvas.height * 0.5 + (Math.random() - 0.5) * 80,
      vx: (Math.random() - 0.5) * 0.4,
      vy: (Math.random() - 0.5) * 0.3,
      r: 80 + Math.random() * 60,
      color,
      phase: i * Math.PI * 0.5,
    }));

    let t = 0;
    const draw = () => {
      const w = canvas.width;
      const h = canvas.height;
      ctx.clearRect(0, 0, w, h);

      t += 0.005;

      blobs.forEach((b, i) => {
        // Gentle drift
        b.x += b.vx + Math.sin(t * 0.7 + b.phase) * 0.25;
        b.y += b.vy + Math.cos(t * 0.5 + b.phase) * 0.18;

        // Soft boundary bounce
        if (b.x < b.r)       { b.x = b.r;       b.vx *= -0.6; }
        if (b.x > w - b.r)   { b.x = w - b.r;   b.vx *= -0.6; }
        if (b.y < b.r * 0.5) { b.y = b.r * 0.5; b.vy *= -0.6; }
        if (b.y > h - b.r * 0.5) { b.y = h - b.r * 0.5; b.vy *= -0.6; }

        // Radial gradient blob
        const pulsedR = b.r * (1 + 0.08 * Math.sin(t * 1.2 + i));
        const grad = ctx.createRadialGradient(b.x, b.y, 0, b.x, b.y, pulsedR * 1.8);
        grad.addColorStop(0,   hexAlpha(b.color, 0.18));
        grad.addColorStop(0.5, hexAlpha(b.color, 0.09));
        grad.addColorStop(1,   hexAlpha(b.color, 0));

        ctx.beginPath();
        ctx.arc(b.x, b.y, pulsedR * 1.8, 0, Math.PI * 2);
        ctx.fillStyle = grad;
        ctx.fill();
      });

      // Subtle grain overlay (single pass noise using offscreen)
      animRef.current = requestAnimationFrame(draw);
    };

    draw();
    return () => {
      cancelAnimationFrame(animRef.current);
      window.removeEventListener('resize', resize);
    };
  }, []);

  return React.createElement('canvas', {
    ref: canvasRef,
    style: {
      position: 'absolute',
      inset: 0,
      width: '100%',
      height: '100%',
      pointerEvents: 'none',
    }
  });
}

function hexAlpha(hex, alpha) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return `rgba(${r},${g},${b},${alpha})`;
}

window.FluidHero = FluidHero;
