// video-bg.jsx — animated "video-like" backgrounds.
// Pure CSS + canvas. No actual video files — these are layered to feel like
// ambient cinematography behind the page. Scroll-coupled where it makes sense.

const { useEffect: vbUseEffect, useRef: vbUseRef, useState: vbUseState } = React;

// One-time keyframe injection
if (typeof document !== 'undefined' && !document.getElementById('video-bg-css')) {
  const style = document.createElement('style');
  style.id = 'video-bg-css';
  style.textContent = `
    @keyframes vbg-aurora-1 {
      0%   { transform: translate3d(-10%, -10%, 0) scale(1); }
      33%  { transform: translate3d(15%, 5%, 0) scale(1.15); }
      66%  { transform: translate3d(-5%, 20%, 0) scale(0.95); }
      100% { transform: translate3d(-10%, -10%, 0) scale(1); }
    }
    @keyframes vbg-aurora-2 {
      0%   { transform: translate3d(20%, 30%, 0) scale(1.1); }
      33%  { transform: translate3d(-10%, 10%, 0) scale(0.9); }
      66%  { transform: translate3d(25%, -15%, 0) scale(1.2); }
      100% { transform: translate3d(20%, 30%, 0) scale(1.1); }
    }
    @keyframes vbg-aurora-3 {
      0%   { transform: translate3d(40%, 0, 0) scale(0.9); }
      50%  { transform: translate3d(-20%, 35%, 0) scale(1.3); }
      100% { transform: translate3d(40%, 0, 0) scale(0.9); }
    }
    @keyframes vbg-grain {
      0%, 100% { transform: translate(0, 0); }
      10% { transform: translate(-5%, -10%); }
      20% { transform: translate(-15%, 5%); }
      30% { transform: translate(7%, -25%); }
      40% { transform: translate(-5%, 25%); }
      50% { transform: translate(-15%, 10%); }
      60% { transform: translate(15%, 0); }
      70% { transform: translate(0, 15%); }
      80% { transform: translate(3%, 35%); }
      90% { transform: translate(-10%, 10%); }
    }
    @keyframes vbg-scan {
      0% { transform: translateY(-100%); opacity: 0; }
      10% { opacity: 0.6; }
      90% { opacity: 0.6; }
      100% { transform: translateY(2000%); opacity: 0; }
    }
    @keyframes vbg-pan {
      from { background-position: 0% 0%; }
      to { background-position: 100% 100%; }
    }
    @keyframes vbg-ray {
      0%, 100% { opacity: 0.4; transform: scaleY(1); }
      50% { opacity: 0.9; transform: scaleY(1.1); }
    }
    .vbg-noise {
      background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.55 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>");
      background-size: 200px 200px;
    }
  `;
  document.head.appendChild(style);
}

// ====================== AuroraBG ======================
// Three large blurred radial gradients drifting through the layer.
// Optional `scroll` prop couples motion to page scroll (useful behind hero).
function AuroraBG({ colors = ['#ff8c2e', '#54c993', '#ff8c9e'], opacity = 0.55, blur = 90, scrollCouple = false, style = {} }) {
  const [yOff, setYOff] = vbUseState(0);
  vbUseEffect(() => {
    if (!scrollCouple) return;
    const onScroll = () => setYOff(window.scrollY * 0.4);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [scrollCouple]);
  return (
    <div aria-hidden style={{
      position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none',
      filter: `blur(${blur}px)`, opacity, ...style,
    }}>
      <div style={{
        position: 'absolute', width: '55%', aspectRatio: '1',
        borderRadius: '50%', background: colors[0],
        top: `${-yOff * 0.15}px`, left: '-10%',
        animation: 'vbg-aurora-1 22s ease-in-out infinite',
        willChange: 'transform',
      }}></div>
      <div style={{
        position: 'absolute', width: '50%', aspectRatio: '1',
        borderRadius: '50%', background: colors[1],
        top: `${30 - yOff * 0.1}%`, right: '-15%',
        animation: 'vbg-aurora-2 28s ease-in-out infinite',
        willChange: 'transform',
      }}></div>
      <div style={{
        position: 'absolute', width: '60%', aspectRatio: '1',
        borderRadius: '50%', background: colors[2],
        bottom: `${-yOff * 0.08}px`, left: '20%',
        animation: 'vbg-aurora-3 34s ease-in-out infinite',
        willChange: 'transform',
      }}></div>
    </div>
  );
}

// ====================== GrainOverlay ======================
// A subtle animated film grain on top of everything in the section.
function GrainOverlay({ opacity = 0.18, style = {} }) {
  return (
    <div aria-hidden className="vbg-noise" style={{
      position: 'absolute', inset: '-50%',
      opacity, mixBlendMode: 'overlay', pointerEvents: 'none',
      animation: 'vbg-grain 8s steps(8) infinite',
      ...style,
    }}></div>
  );
}

// ====================== ScanLines ======================
// Faint moving horizontal scan line — feels like a film projector.
function ScanLines({ color = '#ff8c2e', opacity = 0.05, style = {} }) {
  return (
    <div aria-hidden style={{
      position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none',
      opacity, ...style,
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: '6%',
        background: `linear-gradient(180deg, transparent, ${color}, transparent)`,
        animation: 'vbg-scan 14s linear infinite',
      }}></div>
    </div>
  );
}

// ====================== ParticleField (canvas) ======================
// Slow upward-drifting dust particles. Scroll-coupled velocity.
function ParticleField({
  count = 80, color = '#ff8c2e', maxSize = 2.2, speed = 0.3,
  scrollCouple = true, style = {},
}) {
  const canvasRef = vbUseRef(null);
  const particlesRef = vbUseRef([]);
  const scrollRef = vbUseRef({ last: 0, dy: 0 });

  vbUseEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = window.devicePixelRatio || 1;
    let w = 0, h = 0, raf = 0;

    const resize = () => {
      const r = canvas.getBoundingClientRect();
      w = r.width;
      h = r.height;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.scale(dpr, dpr);
    };

    const init = () => {
      particlesRef.current = Array.from({ length: count }, () => ({
        x: Math.random() * w,
        y: Math.random() * h,
        r: Math.random() * maxSize + 0.4,
        vx: (Math.random() - 0.5) * 0.15,
        vy: -(Math.random() * 0.6 + 0.2) * speed,
        a: Math.random() * 0.5 + 0.2,
      }));
    };

    resize();
    init();

    const onScroll = () => {
      const y = window.scrollY;
      scrollRef.current.dy = (y - scrollRef.current.last) * 0.05;
      scrollRef.current.last = y;
    };
    if (scrollCouple) {
      scrollRef.current.last = window.scrollY;
      window.addEventListener('scroll', onScroll, { passive: true });
    }
    window.addEventListener('resize', resize);

    const loop = () => {
      ctx.clearRect(0, 0, w, h);
      const dy = scrollCouple ? scrollRef.current.dy : 0;
      // decay scroll velocity
      scrollRef.current.dy *= 0.92;
      for (const p of particlesRef.current) {
        p.x += p.vx;
        p.y += p.vy - dy;
        if (p.y < -10) { p.y = h + 10; p.x = Math.random() * w; }
        if (p.y > h + 10) { p.y = -10; p.x = Math.random() * w; }
        if (p.x < -10) p.x = w + 10;
        if (p.x > w + 10) p.x = -10;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
        ctx.fillStyle = color;
        ctx.globalAlpha = p.a;
        ctx.fill();
      }
      ctx.globalAlpha = 1;
      raf = requestAnimationFrame(loop);
    };
    loop();

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
      if (scrollCouple) window.removeEventListener('scroll', onScroll);
    };
  }, [count, color, maxSize, speed, scrollCouple]);

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

// ====================== ScrollingMarquees (background text) ======================
// Giant faint words scrolling at different speeds, parallax with page scroll.
function ScrollingMarquees({ phrases = [], color = '#ffffff', baseOpacity = 0.04, style = {} }) {
  const [scroll, setScroll] = vbUseState(0);
  vbUseEffect(() => {
    const onS = () => setScroll(window.scrollY);
    window.addEventListener('scroll', onS, { passive: true });
    return () => window.removeEventListener('scroll', onS);
  }, []);
  return (
    <div aria-hidden style={{
      position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none',
      display: 'flex', flexDirection: 'column', justifyContent: 'space-around',
      ...style,
    }}>
      {phrases.map((p, i) => {
        const offset = (scroll * (0.15 + i * 0.12)) % 800;
        return (
          <div key={i} style={{
            whiteSpace: 'nowrap',
            transform: `translateX(${-offset}px)`,
            fontFamily: `'Playfair Display', serif`,
            fontSize: 180, fontStyle: 'italic', fontWeight: 400,
            color, opacity: baseOpacity + i * 0.01, letterSpacing: -4,
            willChange: 'transform',
          }}>
            {p} · {p} · {p} · {p}
          </div>
        );
      })}
    </div>
  );
}

// ====================== AnimatedGrid ======================
// Big SVG grid that pans diagonally — feels like a slow space pan.
function AnimatedGrid({ color = '#ff8c2e', size = 64, opacity = 0.08, style = {} }) {
  return (
    <div aria-hidden style={{
      position: 'absolute', inset: 0, pointerEvents: 'none',
      backgroundImage: `linear-gradient(${color}66 1px, transparent 1px), linear-gradient(90deg, ${color}66 1px, transparent 1px)`,
      backgroundSize: `${size}px ${size}px`,
      opacity,
      animation: `vbg-pan 60s linear infinite`,
      maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 80%)',
      WebkitMaskImage: 'radial-gradient(ellipse at center, black 30%, transparent 80%)',
      ...style,
    }}></div>
  );
}

// ====================== LightRays ======================
// Vertical light rays — cinematic god-rays effect.
function LightRays({ color = '#ff8c2e', count = 5, style = {} }) {
  return (
    <div aria-hidden style={{
      position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none', ...style,
    }}>
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} style={{
          position: 'absolute', top: '-20%', height: '140%',
          width: `${30 + Math.random() * 80}px`,
          left: `${(i / count) * 100 + Math.random() * 10}%`,
          background: `linear-gradient(180deg, transparent, ${color}33, transparent)`,
          transform: 'skewX(-12deg)',
          animation: `vbg-ray ${6 + i * 1.4}s ease-in-out infinite`,
          animationDelay: `${i * -0.7}s`,
          filter: 'blur(20px)',
        }}></div>
      ))}
    </div>
  );
}

// ====================== Composed Backdrops ======================
function HeroBackdrop({ colors }) {
  return (
    <>
      <AuroraBG colors={colors} opacity={0.5} blur={120} scrollCouple />
      <LightRays color={colors?.[0] || '#ff8c2e'} count={4} />
      <ParticleField count={70} color={colors?.[0] || '#ff8c2e'} maxSize={2} speed={0.4} />
      <GrainOverlay opacity={0.22} />
    </>
  );
}

function AmbientBackdrop({ color = '#ff8c2e' }) {
  return (
    <>
      <ParticleField count={40} color={color} maxSize={1.6} speed={0.25} />
      <GrainOverlay opacity={0.14} />
    </>
  );
}

function ChapterBackdrop({ color, phrase }) {
  return (
    <>
      <AnimatedGrid color={color} opacity={0.07} />
      <ScrollingMarquees phrases={phrase ? [phrase] : []} color={color} baseOpacity={0.045} />
      <GrainOverlay opacity={0.16} />
    </>
  );
}

function CloseBackdrop({ colors }) {
  return (
    <>
      <AuroraBG colors={colors} opacity={0.6} blur={100} scrollCouple />
      <LightRays color={colors?.[0] || '#ff8c2e'} count={6} />
      <ParticleField count={100} color={colors?.[0] || '#ff8c2e'} maxSize={2.4} speed={0.5} />
      <AnimatedGrid color={colors?.[1] || '#54c993'} opacity={0.05} />
      <GrainOverlay opacity={0.22} />
    </>
  );
}

Object.assign(window, {
  AuroraBG, GrainOverlay, ScanLines, ParticleField, ScrollingMarquees,
  AnimatedGrid, LightRays,
  HeroBackdrop, AmbientBackdrop, ChapterBackdrop, CloseBackdrop,
});
