import type { Vec3 } from "./types";

export type ProjectileView = {
  id: string;
  from: Vec3;
  to: Vec3;
  progress: number;
  color: string;
  size?: number;
};

export type ImpactView = {
  id: string;
  position: Vec3;
  color: string;
  age: number;
};

const lerp = (a: number, b: number, t: number) => a + (b - a) * t;

export function Projectiles({ projectiles, impacts }: { projectiles: ProjectileView[]; impacts?: ImpactView[] }) {
  return (
    <>
      {projectiles.map((projectile) => {
        const t = Math.min(1, Math.max(0, projectile.progress));
        const position: Vec3 = [
          lerp(projectile.from[0], projectile.to[0], t),
          lerp(projectile.from[1], projectile.to[1], t),
          lerp(projectile.from[2], projectile.to[2], t),
        ];
        return (
          <mesh key={projectile.id} position={position}>
            <sphereGeometry args={[projectile.size ?? 0.35, 10, 10]} />
            <meshBasicMaterial color={projectile.color} />
            <pointLight color={projectile.color} intensity={1.5} distance={10} />
          </mesh>
        );
      })}
      {impacts?.map((impact) => (
        <mesh key={impact.id} position={impact.position} scale={1 + impact.age * 0.12}>
          <sphereGeometry args={[1.2, 16, 16]} />
          <meshBasicMaterial color={impact.color} transparent opacity={Math.max(0, 0.8 - impact.age * 0.12)} depthWrite={false} />
        </mesh>
      ))}
    </>
  );
}
