const { useRef, useState, useMemo } = React;
const { Canvas, useFrame } = ReactThreeFiber;
const { Points, PointMaterial, OrbitControls } = ReactThreeDrei;

// --- UTILS ---
function generateSpherePoints(count, radius) {
    const points = new Float32Array(count * 3);
    for (let i = 0; i < count; i++) {
        const u = Math.random();
        const v = Math.random();
        const theta = 2 * Math.PI * u;
        const phi = Math.acos(2 * v - 1);
        const r = radius * Math.cbrt(Math.random());

        points[i * 3] = r * Math.sin(phi) * Math.cos(theta);
        points[i * 3 + 1] = r * Math.sin(phi) * Math.sin(theta);
        points[i * 3 + 2] = r * Math.cos(phi);
    }
    return points;
}

const ParticleGlobe = (props) => {
    const ref = useRef();
    const sphere = useMemo(() => generateSpherePoints(5000, 1.8), []);

    useFrame((state, delta) => {
        if (ref.current) {
            ref.current.rotation.y -= delta / 20;
        }
    });

    return (
        <group rotation={[0, 0, Math.PI / 8]}>
            <Points ref={ref} positions={sphere} stride={3} frustumCulled={false} {...props}>
                <PointMaterial
                    transparent
                    color="#0ea5e9" // Light Sky Blue
                    size={0.015}
                    sizeAttenuation={true}
                    depthWrite={false}
                    opacity={0.6}
                />
            </Points>
        </group>
    );
};

const Scene = () => {
    return (
        <div className="absolute inset-0 h-full w-full">
            <Canvas camera={{ position: [0, 0, 5] }} dpr={[1, 2]}>
                <ambientLight intensity={1} />
                <ParticleGlobe />
            </Canvas>
        </div>
    );
};

window.App.Components.Scene = Scene;
