import { useEffect, useState } from 'react';
import { useTheme } from '@/lib/theme';
import { useAnimBg, useAnimParams } from '@/lib/anim';
import { MatrixRain } from './MatrixRain';
import { NeonField } from './NeonField';

// Derives the animation gate: toggle ON *and* not prefers-reduced-motion.
// When false, both the canvas mount and the bc-anim-on html class are removed,
// disabling all CSS animations (scanline, caret, glitch) that scope under it.
function useAnimGate(): boolean {
  const animOn = useAnimBg();
  const [reducedMotion, setReducedMotion] = useState(() => {
    if (typeof window === 'undefined') return false;
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  });

  useEffect(() => {
    if (typeof window === 'undefined') return;
    const mql = window.matchMedia('(prefers-reduced-motion: reduce)');
    const onChange = (e: MediaQueryListEvent) => setReducedMotion(e.matches);
    mql.addEventListener('change', onChange);
    return () => mql.removeEventListener('change', onChange);
  }, []);

  return animOn && !reducedMotion;
}

// Mounted once in AppShell. Manages:
//   1. The bc-anim-on class on <html> (gate for all theme animation CSS).
//   2. The per-theme canvas component (MatrixRain / NeonField / null).
// Native base speeds for each canvas; the user's `speed` slider is a multiplier.
const RAIN_BASE_SPEED = 0.7;
const FIELD_BASE_SPEED = 0.18;

export function ThemeFx() {
  const { id } = useTheme();
  const gateOn = useAnimGate();
  const { density, speed, opacity } = useAnimParams();

  // Sync bc-anim-on class. Effect runs whenever gateOn changes; cleanup
  // removes the class so a stale gate never persists across unmount.
  useEffect(() => {
    if (gateOn) {
      document.documentElement.classList.add('bc-anim-on');
    } else {
      document.documentElement.classList.remove('bc-anim-on');
    }
    return () => {
      document.documentElement.classList.remove('bc-anim-on');
    };
  }, [gateOn]);

  if (id === 'boocode-classic') {
    return (
      <MatrixRain
        enabled={gateOn}
        density={density}
        speed={RAIN_BASE_SPEED * speed}
        opacity={opacity}
      />
    );
  }
  if (id === 'boocode-override') {
    return <NeonField enabled={gateOn} speed={FIELD_BASE_SPEED * speed} opacity={opacity} />;
  }
  return null;
}
