"use client";

import { useState, useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { Points, PointMaterial } from "@react-three/drei";
import { useTheme } from "next-themes";
import * as random from "maath/random/dist/maath-random.esm";

function StarField(props: any) {
  const ref = useRef<any>();
  
  // Generate random points on a sphere
  // Dark Mode: 5000 stars (High density)
  // Light Mode: 3000 particles (Cleaner look)
  const [sphere] = useState(() => 
    random.inSphere(new Float32Array(5000), { radius: 1.5 })
  );

  useFrame((state, delta) => {
    if (!ref.current) return;

    // Continuous Rotation
    ref.current.rotation.x -= delta / 10;
    ref.current.rotation.y -= delta / 15;

    // Mouse Interaction (Parallax Tilt)
    // মাউস যেদিকে যাবে, পুরো গ্যালাক্সি সেদিকে একটু টিল্ট হবে
    const x = (state.pointer.x * Math.PI) / 10;
    const y = (state.pointer.y * Math.PI) / 10;
    
    // Smooth lerping for mouse movement
    ref.current.rotation.x += (y - ref.current.rotation.x) * 0.02;
    ref.current.rotation.y += (x - ref.current.rotation.y) * 0.02;
  });

  return (
    <group rotation={[0, 0, Math.PI / 4]}>
      <Points ref={ref} positions={sphere as Float32Array} stride={3} frustumCulled={false} {...props}>
        <PointMaterial
          transparent
          color={props.color}
          size={props.size}
          sizeAttenuation={true}
          depthWrite={false}
        />
      </Points>
    </group>
  );
}

export default function Background3D() {
  const { theme } = useTheme();
  
  // Configuration based on Theme
  // Dark Mode: White Stars, smaller size
  // Light Mode: Green Data Points, slightly bigger
  const particleColor = theme === "dark" ? "#ffffff" : "#16a34a"; // Green-600 for light
  const particleSize = theme === "dark" ? 0.002 : 0.003;

  return (
    <div className="absolute inset-0 -z-10 h-full w-full">
      <Canvas camera={{ position: [0, 0, 1] }}>
        <StarField color={particleColor} size={particleSize} />
      </Canvas>
    </div>
  );
}