import { useRef } from "react";
import { useFrame } from "@react-three/fiber";
import * as THREE from "three";
import { SpaceCanvas } from "../shared/SpaceCanvas";
import { SpaceEnvironment } from "../shared/SpaceEnvironment";
import { ShipMesh } from "../shared/ShipMesh";
import { AsteroidMesh } from "../shared/AsteroidMesh";
import { StationMesh } from "../shared/StationMesh";
import { RouteLine } from "../shared/RouteLine";

function HudSpaceWorld({ targetLocked = true, afterburner = false }: { targetLocked?: boolean; afterburner?: boolean }) {
  const playerRef = useRef<THREE.Group>(null);
  const enemyRef = useRef<THREE.Group>(null);
  useFrame((state) => {
    const t = state.clock.elapsedTime;
    if (playerRef.current) {
      playerRef.current.position.y = -1 + Math.sin(t * 1.5) * 0.18;
      playerRef.current.rotation.z = Math.sin(t * 0.4) * 0.03;
    }
    if (enemyRef.current) {
      enemyRef.current.position.x = 5 + Math.sin(t * 1.1) * 1.2;
      enemyRef.current.position.y = 1 + Math.cos(t * 0.8) * 0.5;
      enemyRef.current.rotation.z = Math.sin(t * 0.6) * 0.04;
    }
  });

  return (
    <>
      <SpaceEnvironment density={3800} spread={2600} />
      <group ref={playerRef} position={[0, -1, 15]}>
        <ShipMesh scale={0.42} engineActive={afterburner} />
        <mesh>
          <sphereGeometry args={[2.6, 24, 24]} />
          <meshBasicMaterial color="#22d3ee" transparent opacity={0.06} wireframe />
        </mesh>
      </group>
      <group ref={enemyRef} position={[5, 1, -20]}>
        <ShipMesh scale={0.34} hostile color="#7f1d1d" emissive="#ef4444" />
        {targetLocked && (
          <mesh>
            <torusGeometry args={[2.6, 0.04, 8, 32]} />
            <meshBasicMaterial color="#f0a030" />
          </mesh>
        )}
      </group>
      {targetLocked && <RouteLine points={[[0, -1, 15], [5, 1, -20]]} color="#f0a030" width={1} />}
      {[-25, -20, -30, 30, 35, -15, 20].map((x, index) => (
        <group key={x} position={[x, -3 + (index % 3), -12 - index * 4]} rotation={[index, index * 0.4, 0]}>
          <AsteroidMesh scale={1.5 + (index % 3) * 0.5} />
        </group>
      ))}
      <group position={[40, 2, -40]}>
        <StationMesh scale={1} />
      </group>
    </>
  );
}

export function HudSpaceScene(props: { targetLocked?: boolean; afterburner?: boolean }) {
  return (
    <SpaceCanvas camera={{ position: [0, 8, 25], fov: 60, near: 0.1, far: 5000 }}>
      <HudSpaceWorld {...props} />
    </SpaceCanvas>
  );
}
