// background.jsx — full-screen video background with vignette overlay
const { useRef, useEffect } = React;

function AmbientBackground({ motion }) {
  const videoRef = useRef(null);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;
    video.playbackRate = 0.5; // adjust 0.3–1.0 to taste
    if (motion === 'off') {
      video.pause();
      return;
    }
    video.play().catch(() => {});
    // iOS Safari can refuse autoplay (Low Power Mode, data saver);
    // retry on the first user interaction
    const resume = () => {
      if (video.paused) video.play().catch(() => {});
    };
    window.addEventListener('touchstart', resume, { passive: true });
    window.addEventListener('click', resume);
    return () => {
      window.removeEventListener('touchstart', resume);
      window.removeEventListener('click', resume);
    };
  }, [motion]);

  return (
    <div aria-hidden="true" style={{ position:'fixed', inset:0, zIndex:0, pointerEvents:'none' }}>
      {/* dark base so there's always something while video loads */}
      <div style={{ position:'absolute', inset:0, background:'var(--bg)' }} />

      {/* video */}
      <video
        ref={videoRef}
        src="assets/bg-waves.mp4"
        autoPlay
        muted
        loop
        playsInline
        webkit-playsinline="true"
        preload="auto"
        style={{
          position: 'absolute',
          inset: 0,
          width: '100%',
          height: '100%',
          objectFit: 'cover',
          objectPosition: 'center',
          filter: 'saturate(0.65) brightness(0.85)',
        }}
      />

      {/* dark vignette so text stays readable */}
      <div style={{
        position: 'absolute',
        inset: 0,
        background: 'linear-gradient(to bottom, rgba(0,0,0,0.55) 0%, rgba(0,0,0,0.38) 40%, rgba(0,0,0,0.65) 100%)',
      }} />

      {/* subtle dark tint to keep palette harmony */}
      <div style={{
        position: 'absolute',
        inset: 0,
        background: 'rgba(10,8,18,0.38)',
      }} />
    </div>
  );
}

window.AmbientBackground = AmbientBackground;
