import { useRef, useMemo, useEffect, useState } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

interface StarfieldParticlesProps {
  count?: number;
  speedRef: React.MutableRefObject<number>;
}

function StarfieldParticles({ count = 2000, speedRef }: StarfieldParticlesProps) {
  const meshRef = useRef<THREE.Points>(null);
  
  const [positions, velocities] = useMemo(() => {
    const positions = new Float32Array(count * 3);
    const velocities = new Float32Array(count);
    
    for (let i = 0; i < count; i++) {
      const i3 = i * 3;
      // Random position in a large sphere
      const radius = 500 + Math.random() * 1000;
      const theta = Math.random() * Math.PI * 2;
      const phi = Math.acos(2 * Math.random() - 1);
      
      positions[i3] = radius * Math.sin(phi) * Math.cos(theta);
      positions[i3 + 1] = radius * Math.sin(phi) * Math.sin(theta);
      positions[i3 + 2] = radius * Math.cos(phi);
      
      velocities[i] = 0.5 + Math.random() * 1.5;
    }
    
    return [positions, velocities];
  }, [count]);

  useFrame((_, delta) => {
    if (!meshRef.current) return;
    
    const positionArray = meshRef.current.geometry.attributes.position.array as Float32Array;
    const speed = speedRef.current * delta * 60;
    
    for (let i = 0; i < count; i++) {
      const i3 = i * 3;
      
      // Move stars towards camera (positive Z)
      positionArray[i3 + 2] += velocities[i] * speed;
      
      // Reset stars that pass the camera
      if (positionArray[i3 + 2] > 500) {
        positionArray[i3 + 2] = -1500 - Math.random() * 500;
        const radius = 500 + Math.random() * 1000;
        const theta = Math.random() * Math.PI * 2;
        positionArray[i3] = radius * Math.cos(theta);
        positionArray[i3 + 1] = radius * Math.sin(theta);
      }
    }
    
    meshRef.current.geometry.attributes.position.needsUpdate = true;
  });

  return (
    <points ref={meshRef}>
      <bufferGeometry>
        <bufferAttribute
          attach="attributes-position"
          args={[positions, 3]}
          count={count}
          itemSize={3}
        />
      </bufferGeometry>
      <pointsMaterial
        size={2}
        color="#ffffff"
        transparent
        opacity={0.8}
        sizeAttenuation
      />
    </points>
  );
}

function CameraController() {
  useFrame((state) => {
    // Subtle camera movement based on mouse
    const { x, y } = state.pointer;
    state.camera.position.x += (x * 10 - state.camera.position.x) * 0.05;
    state.camera.position.y += (y * 10 - state.camera.position.y) * 0.05;
    state.camera.lookAt(0, 0, 0);
  });
  
  return null;
}

export default function Starfield() {
  const speedRef = useRef(1);
  const containerRef = useRef<HTMLDivElement>(null);
  const [reducedMotion, setReducedMotion] = useState(false);

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

  useEffect(() => {
    if (reducedMotion) return;
    // Scroll-based speed control
    const triggers: ScrollTrigger[] = [];
    
    triggers.push(
      ScrollTrigger.create({
        trigger: 'body',
        start: 'top top',
        end: 'bottom bottom',
        onUpdate: (self) => {
          // Increase speed based on scroll velocity
          const velocity = Math.abs(self.getVelocity());
          const targetSpeed = 1 + (velocity / 1000);
          speedRef.current = Math.min(targetSpeed, 20);
        },
      })
    );

    // Hero section - accelerate starfield
    triggers.push(
      ScrollTrigger.create({
        trigger: '#hero',
        start: 'top top',
        end: 'bottom top',
        scrub: 1,
        onUpdate: (self) => {
          speedRef.current = 1 + self.progress * 10;
        },
      })
    );

    // CTA section - hyperdrive effect
    triggers.push(
      ScrollTrigger.create({
        trigger: '#contact',
        start: 'top bottom',
        end: 'bottom bottom',
        scrub: 1,
        onUpdate: (self) => {
          speedRef.current = 1 + self.progress * 30;
        },
      })
    );

    return () => {
      triggers.forEach(t => t.kill());
    };
  }, [reducedMotion]);

  if (reducedMotion) return null;

  return (
    <div 
      ref={containerRef}
      className="starfield-canvas"
      style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 0 }}
    >
      <Canvas
        camera={{ position: [0, 0, 500], fov: 60 }}
        dpr={[1, 2]}
        gl={{ 
          antialias: true, 
          alpha: true,
          powerPreference: 'high-performance'
        }}
      >
        <CameraController />
        <StarfieldParticles count={500} speedRef={speedRef} />
      </Canvas>
    </div>
  );
}
