import React, { useMemo, useRef } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { OrbitControls, PerspectiveCamera } from '@react-three/drei';
import { generateSceneData } from './Generator';
import ObjectInstances from './ObjectInstances';
import TransmissionLines from './TransmissionLines';
import Landscape from './Landscape';
import * as THREE from 'three';

const WebGLContent: React.FC = () => {
    // Generate the procedural data with a fixed seed so it's consistent
    const sceneData = useMemo(() => generateSceneData(42), []);

    const groupRef = useRef<THREE.Group>(null!);

    // Very slow rotation for a cinematic feel
    useFrame((state, delta) => {
        if (groupRef.current) {
            groupRef.current.rotation.y += delta * 0.05;
        }
    });

    return (
        <>
            <PerspectiveCamera makeDefault position={[0, 150, 350]} fov={50} />
            <OrbitControls enableZoom={false} enablePan={false} autoRotate autoRotateSpeed={0.5} maxPolarAngle={Math.PI / 2.2} />

            {/* Atmospheric Fog - blends the edges into the space background */}
            <fog attach="fog" args={['#061121', 100, 450]} />

            <ambientLight intensity={0.4} />
            <directionalLight position={[100, 200, 50]} intensity={1.5} color="#e0f2fe" castShadow />
            <directionalLight position={[-100, 100, -50]} intensity={0.5} color="#3b82f6" />

            <group ref={groupRef}>
                <Landscape seed={42} />
                <ObjectInstances data={sceneData} />
                <TransmissionLines data={sceneData} />
            </group>
        </>
    );
};

export default function HeroWebGLScene() {
    return (
        <div className="w-full h-full absolute inset-0 z-0 bg-gradient-to-t from-[#020a17] to-[#0d2a5a]">
            <Canvas shadows gl={{ antialias: true, alpha: true }}>
                <WebGLContent />
            </Canvas>
            {/* Decorative overlaid gradient exactly like space */}
            <div className="absolute inset-0 bg-gradient-to-b from-transparent to-[#020a17]/80 pointer-events-none" />
        </div>
    );
}
