import React from 'react';
import { useCurrentFrame, interpolate } from 'remotion';

interface Particle {
  x: number;
  y: number;
  size: number;
  speed: number;
  opacity: number;
  phase: number;
}

const generateParticles = (count: number, seed: number): Particle[] => {
  const particles: Particle[] = [];
  for (let i = 0; i < count; i++) {
    const hash = Math.sin(seed + i * 127.1) * 43758.5453;
    const h2 = Math.sin(seed + i * 269.5) * 76321.123;
    const h3 = Math.sin(seed + i * 419.2) * 29451.72;
    particles.push({
      x: (hash - Math.floor(hash)) * 1920,
      y: (h2 - Math.floor(h2)) * 1080,
      size: 1 + (h3 - Math.floor(h3)) * 3,
      speed: 0.2 + (hash - Math.floor(hash)) * 0.6,
      opacity: 0.15 + (h2 - Math.floor(h2)) * 0.35,
      phase: (h3 - Math.floor(h3)) * Math.PI * 2,
    });
  }
  return particles;
};

export const ParticleField: React.FC<{
  count?: number;
  color?: string;
  seed?: number;
  drift?: 'up' | 'down' | 'none';
  fadeIn?: number;
}> = ({
  count = 50,
  color = '#ffffff',
  seed = 42,
  drift = 'up',
  fadeIn = 20,
}) => {
  const frame = useCurrentFrame();
  const particles = React.useMemo(() => generateParticles(count, seed), [count, seed]);

  const globalOpacity = interpolate(frame, [0, fadeIn], [0, 1], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  return (
    <div
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        width: 1920,
        height: 1080,
        pointerEvents: 'none',
        opacity: globalOpacity,
      }}
    >
      {particles.map((p, i) => {
        const driftY =
          drift === 'up'
            ? -frame * p.speed * 0.5
            : drift === 'down'
            ? frame * p.speed * 0.5
            : 0;
        const floatX = Math.sin(frame * 0.02 + p.phase) * 15;
        const floatY = Math.cos(frame * 0.015 + p.phase) * 10;
        const pulse = 0.7 + Math.sin(frame * 0.04 + p.phase) * 0.3;

        const y = ((p.y + driftY + floatY) % 1180) - 50;
        const x = p.x + floatX;

        return (
          <div
            key={i}
            style={{
              position: 'absolute',
              left: x,
              top: y < -50 ? y + 1180 : y,
              width: p.size,
              height: p.size,
              borderRadius: '50%',
              background: color,
              opacity: p.opacity * pulse,
              boxShadow: p.size > 2 ? `0 0 ${p.size * 3}px ${color}` : undefined,
            }}
          />
        );
      })}
    </div>
  );
};
