// src/components/canvas/NeuronNetwork.tsx
"use client";

import { useRef, useMemo } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { Points, PointMaterial } from "@react-three/drei";
import * as THREE from "three";

function NeuronParticles({ count = 200 }) {
  // Create a ref for the points to animate them
  const points = useRef<THREE.Points>(null!);

  // Generate random positions for the neurons
  const positions = useMemo(() => {
    const pos = new Float32Array(count * 3);
    for (let i = 0; i < count; i++) {
      // Spread particles across a wide area (x, y, z)
      pos[i * 3] = (Math.random() - 0.5) * 25;     // x
      pos[i * 3 + 1] = (Math.random() - 0.5) * 25; // y
      pos[i * 3 + 2] = (Math.random() - 0.5) * 10; // z
    }
    return pos;
  }, [count]);

  useFrame((state, delta) => {
    if (points.current) {
      // subtle rotation of the entire system
      points.current.rotation.x -= delta / 50;
      points.current.rotation.y -= delta / 60;
      
      // Optional: Gentle wave motion could be added here
    }
  });

  return (
    <group rotation={[0, 0, Math.PI / 4]}>
      <Points
        ref={points}
        positions={positions}
        stride={3}
        frustumCulled={false}
      >
        <PointMaterial
          transparent
          color="#22d3ee" // Cyan-400
          size={0.08}
          sizeAttenuation={true}
          depthWrite={false}
          opacity={0.6}
        />
      </Points>
      {/* For true "connections" (lines), calculating distance between 200 points 
        every frame is heavy. A visual trick is to render a second layer 
        of slightly larger, fainter particles or use a custom shader.
        
        However, for a clean "Neuron" look, we often just need the floating nodes 
        and a faint fog, or we can use the <Line> component from drei 
        if the count is low (<50). 
      */}
    </group>
  );
}

// A wrapper to handle the Canvas settings
export default function NeuronNetwork() {
  return (
    <div className="absolute inset-0 z-0">
      <Canvas
        camera={{ position: [0, 0, 10], fov: 60 }}
        gl={{ alpha: true, antialias: true }}
        dpr={[1, 2]} // Handle high-res screens
      >
        <color attach="background" args={["transparent"]} />
        <ambientLight intensity={0.5} />
        <NeuronParticles count={300} />
        {/* Fog creates depth, fading distant neurons */}
        <fog attach="fog" args={['#030712', 5, 20]} /> 
      </Canvas>
    </div>
  );
}