import { Canvas, useFrame, useThree } from '@react-three/fiber';
import { useRef, useEffect, useState } from 'react';
import * as THREE from 'three';
import Stats from 'three/addons/libs/stats.module.js';

function SmokeParticles() {
  const groupRef = useRef();
  const particlesRef = useRef([]);
  const clockRef = useRef(new THREE.Clock());
  const statsRef = useRef();
  const { scene, size } = useThree();
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 });



  // Update mouse position
  useEffect(() => {
    const handleMouseMove = (event) => {
      const x = (event.clientX / size.width) * 2 - 1;
      const y = -(event.clientY / size.height) * 2 + 1;
      setMousePos({ x, y });
    };

    window.addEventListener("mousemove", handleMouseMove);
    return () => window.removeEventListener("mousemove", handleMouseMove);
  }, [size]);

  // Create smoke particles
  useEffect(() => {
    const loader = new THREE.TextureLoader();

    loader.load('https://s3-us-west-2.amazonaws.com/s.cdpn.io/95637/Smoke-Element.png', (smokeTexture) => {
      const smokeGeo = new THREE.PlaneGeometry(300, 300);

      for (let p = 0; p < 150; p++) {
        const colors = [0xFFD700, 0xFACC15, 0xFFA500]; // Gold, yellow-400, amber
        const randomColor = colors[Math.floor(Math.random() * colors.length)];

        const smokeMaterial = new THREE.MeshLambertMaterial({
          color: randomColor,
          map: smokeTexture,
          transparent: true,
          opacity: Math.random() * 0.6 + 0.4, // More vibrant
          emissive: randomColor,
          emissiveIntensity: 1.2, // Stronger glow
        });

        const particle = new THREE.Mesh(smokeGeo, smokeMaterial);
        particle.position.set(
          Math.random() * 500 - 250,
          Math.random() * 500 - 250,
          Math.random() * 1000 - 100
        );
        particle.rotation.z = Math.random() * 360;
        particle.userData.originalPos = { ...particle.position };
        groupRef.current.add(particle);
        particlesRef.current.push(particle);
      }
    });

    // Add a golden light for extra glow
    const light = new THREE.PointLight(0xFFD700, 2.0, 2000);
    light.position.set(0, 0, 500);
    scene.add(light);

  }, [scene]);

  // Animation loop with smooth wind effect
  useFrame(() => {
    if (statsRef.current) statsRef.current.begin();

    const delta = clockRef.current.getDelta();

    particlesRef.current.forEach((particle) => {
      if (particle) {
        particle.rotation.z += delta * 0.2;

        // Get particle position
        const particlePos = particle.position;
        const originalPos = particle.userData.originalPos;

        // Calculate distance from mouse
        const dx = (mousePos.x * 500) - particlePos.x;
        const dy = (mousePos.y * 500) - particlePos.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        // Wind effect: move particles with a slight random offset
        if (distance < 150) { 
          particlePos.x += dx * 0.02 + (Math.random() - 0.5) * 2;
          particlePos.y += dy * 0.02 + (Math.random() - 0.5) * 2;
        }

        // Smoothly return particles to original position but with a slight offset
        particlePos.x = THREE.MathUtils.lerp(particlePos.x, originalPos.x + (Math.random() - 0.5) * 5, delta);
        particlePos.y = THREE.MathUtils.lerp(particlePos.y, originalPos.y + (Math.random() - 0.5) * 5, delta);
      }
    });

    if (statsRef.current) statsRef.current.end();
  });

  return <group ref={groupRef} />;
}

export default function SmokeEffect() {
  return (
    <Canvas
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100vw',
        height: '100vh',
        zIndex: -10,
        background: 'white'
      }}
      camera={{
        fov: 75,
        position: [0, 0, 1000],
        near: 1,
        far: 10000
      }}
    >
      <SmokeParticles />
    </Canvas>
  );
}
