/* global React */
const { useEffect, useRef } = React;

function HeroBackdrop() {
  const canvasRef = useRef(null);
  const sparkRef = useRef(null);

  // Floating discount tags — drift slowly across the hero
  const floaters = [
    { txt: '−70%', x: 8,  y: 18, size: 28, hue: 'orange',  rot: -8,  delay: 0,   dur: 22 },
    { txt: 'SALE', x: 86, y: 14, size: 22, hue: 'sky',     rot: 6,   delay: 3,   dur: 26 },
    { txt: '€',    x: 18, y: 72, size: 38, hue: 'yellow',  rot: -12, delay: 1,   dur: 24 },
    { txt: '%',    x: 92, y: 64, size: 44, hue: 'orange',  rot: 14,  delay: 5,   dur: 28 },
    { txt: 'NEU',  x: 50, y: 8,  size: 18, hue: 'danger',  rot: -3,  delay: 2.5, dur: 25 },
    { txt: '−50%', x: 4,  y: 50, size: 20, hue: 'sky',     rot: 8,   delay: 4,   dur: 30 },
    { txt: '%',    x: 62, y: 88, size: 28, hue: 'yellow',  rot: -6,  delay: 6,   dur: 27 },
    { txt: '★',    x: 78, y: 38, size: 24, hue: 'orange',  rot: 0,   delay: 1.5, dur: 23 },
  ];

  // Particle layer — twinkling sparks
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) return;

    let dpr = Math.min(window.devicePixelRatio || 1, 2);
    let w = 0, h = 0, raf = 0;
    let particles = [];

    const palette = [
      'rgba(255,106,0,',   // orange
      'rgba(255,159,47,',  // orange light
      'rgba(0,174,232,',   // sky
      'rgba(255,213,53,',  // yellow
      'rgba(255,255,255,', // white sparkle
    ];

    function resize() {
      const rect = canvas.parentElement.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width = w * dpr; canvas.height = h * dpr;
      canvas.style.width = w + 'px'; canvas.style.height = h + 'px';
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      seed();
    }
    function seed() {
      const count = Math.max(40, Math.min(110, Math.round((w * h) / 14000)));
      particles = [];
      for (let i = 0; i < count; i++) {
        particles.push({
          x: Math.random() * w,
          y: Math.random() * h,
          vx: (Math.random() - 0.5) * 0.25,
          vy: -0.1 - Math.random() * 0.4,
          r: 0.5 + Math.random() * 2.4,
          color: palette[Math.floor(Math.random() * palette.length)],
          life: Math.random(),
          twinkle: 0.005 + Math.random() * 0.02,
          maxAlpha: 0.4 + Math.random() * 0.6,
        });
      }
    }
    function tick() {
      ctx.clearRect(0, 0, w, h);
      for (const p of particles) {
        p.x += p.vx;
        p.y += p.vy;
        p.life += p.twinkle;
        if (p.y < -10 || p.x < -10 || p.x > w + 10) {
          p.x = Math.random() * w;
          p.y = h + 10;
          p.life = 0;
        }
        const alpha = (Math.sin(p.life * Math.PI * 2) * 0.5 + 0.5) * p.maxAlpha;
        ctx.fillStyle = p.color + alpha.toFixed(3) + ')';
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
        ctx.fill();
        // soft glow
        if (p.r > 1.5) {
          ctx.fillStyle = p.color + (alpha * 0.15).toFixed(3) + ')';
          ctx.beginPath();
          ctx.arc(p.x, p.y, p.r * 4, 0, Math.PI * 2);
          ctx.fill();
        }
      }
      raf = requestAnimationFrame(tick);
    }
    const ro = new ResizeObserver(resize);
    ro.observe(canvas.parentElement);
    resize();
    raf = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(raf); ro.disconnect(); };
  }, []);

  // Random spark bursts
  useEffect(() => {
    const layer = sparkRef.current;
    if (!layer) return;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) return;
    let alive = true;
    function spawnBurst() {
      if (!alive) return;
      const burst = document.createElement('div');
      burst.className = 'dp2-spark';
      burst.style.left = (5 + Math.random() * 90) + '%';
      burst.style.top = (10 + Math.random() * 80) + '%';
      const colors = ['#FF6A00', '#00AEE8', '#FFD535', '#FF9F2F'];
      burst.style.setProperty('--spark-c', colors[Math.floor(Math.random() * colors.length)]);
      burst.style.setProperty('--spark-s', (0.8 + Math.random() * 0.8).toFixed(2));
      layer.appendChild(burst);
      setTimeout(() => burst.remove(), 1400);
      setTimeout(spawnBurst, 600 + Math.random() * 1400);
    }
    const t = setTimeout(spawnBurst, 1000);
    return () => { alive = false; clearTimeout(t); };
  }, []);

  return (
    <div className="dp2-backdrop" aria-hidden="true">
      {/* Mesh gradient blobs */}
      <div className="dp2-blob dp2-blob--1"></div>
      <div className="dp2-blob dp2-blob--2"></div>
      <div className="dp2-blob dp2-blob--3"></div>
      <div className="dp2-blob dp2-blob--4"></div>

      {/* Particle canvas */}
      <canvas ref={canvasRef} className="dp2-particles"></canvas>

      {/* Spark burst layer */}
      <div ref={sparkRef} className="dp2-sparks"></div>

      {/* Floating discount tags */}
      <div className="dp2-floaters">
        {floaters.map((f, i) => (
          <span
            key={i}
            className={`dp2-floater dp2-floater--${f.hue}`}
            style={{
              left: f.x + '%',
              top: f.y + '%',
              fontSize: f.size + 'px',
              transform: `rotate(${f.rot}deg)`,
              animationDuration: f.dur + 's',
              animationDelay: '-' + f.delay + 's',
            }}
          >{f.txt}</span>
        ))}
      </div>

      {/* Scan-line / shimmer pass */}
      <div className="dp2-shimmer"></div>
    </div>
  );
}
window.HeroBackdrop = HeroBackdrop;
