import { useMemo } from "react";
import * as THREE from "three";

type ShipMeshProps = {
  color?: string;
  emissive?: string;
  scale?: number;
  hostile?: boolean;
  engineActive?: boolean;
};

export function ShipMesh({
  color = "#c8d6e5",
  emissive = "#f0a030",
  scale = 1,
  hostile = false,
  engineActive = true,
}: ShipMeshProps) {
  const geometry = useMemo(() => {
    const s = scale;
    const vertices = new Float32Array([
      14 * s, 0, 0, -8 * s, 0, -6 * s, -8 * s, 0, 6 * s,
      14 * s, -2 * s, 0, -8 * s, -2 * s, 6 * s, -8 * s, -2 * s, -6 * s,
      14 * s, 0, 0, 14 * s, -2 * s, 0, -8 * s, -2 * s, 6 * s,
      14 * s, 0, 0, -8 * s, -2 * s, 6 * s, -8 * s, 0, 6 * s,
      14 * s, 0, 0, -8 * s, 0, -6 * s, 14 * s, -2 * s, 0,
      14 * s, -2 * s, 0, -8 * s, 0, -6 * s, -8 * s, -2 * s, -6 * s,
      -8 * s, 0, -6 * s, -8 * s, 0, 6 * s, -8 * s, -2 * s, 6 * s,
      -8 * s, 0, -6 * s, -8 * s, -2 * s, 6 * s, -8 * s, -2 * s, -6 * s,
      -8 * s, 0, 6 * s, -8 * s, -2 * s, 6 * s, 14 * s, -2 * s, 0,
      -8 * s, 0, 6 * s, 14 * s, -2 * s, 0, 14 * s, 0, 0,
      14 * s, 0, 0, 14 * s, -2 * s, 0, -8 * s, -2 * s, -6 * s,
      14 * s, 0, 0, -8 * s, -2 * s, -6 * s, -8 * s, 0, -6 * s,
    ]);
    const geo = new THREE.BufferGeometry();
    geo.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
    geo.computeVertexNormals();
    return geo;
  }, [scale]);

  return (
    <group>
      <mesh geometry={geometry} castShadow>
        <meshStandardMaterial color={color} emissive={emissive} emissiveIntensity={0.18} metalness={0.65} roughness={0.28} flatShading />
      </mesh>
      <pointLight position={[-7 * scale, -1 * scale, 0]} intensity={engineActive ? (hostile ? 1.4 : 2.2) : 0.35} distance={18 * scale} color={hostile ? "#ef4444" : "#22d3ee"} />
      <mesh position={[-8.5 * scale, -1 * scale, 0]} rotation={[0, Math.PI / 2, 0]}>
        <coneGeometry args={[1.6 * scale, 4 * scale, 16]} />
        <meshBasicMaterial color={hostile ? "#ef4444" : "#22d3ee"} transparent opacity={engineActive ? 0.45 : 0.12} />
      </mesh>
    </group>
  );
}
