import * as THREE from 'three';
import type { Game } from './Game';

const SPEED = 12;
const HIT_RADIUS = 0.9;

export class EnemyProjectile {
  body: THREE.Group;
  velocity: THREE.Vector3;
  damage: number;
  lifetime = 6;
  dead = false;

  constructor(from: THREE.Vector3, target: THREE.Vector3, damage: number) {
    this.damage = damage;
    this.body = new THREE.Group();
    this.body.position.copy(from);

    this.velocity = new THREE.Vector3()
      .subVectors(target, from)
      .normalize()
      .multiplyScalar(SPEED);

    // Glowing poison blob
    const glowMat = new THREE.MeshBasicMaterial({
      color: 0x66ff44,
      transparent: true,
      opacity: 0.55,
      blending: THREE.AdditiveBlending,
      depthWrite: false,
    });
    const glow = new THREE.Mesh(new THREE.SphereGeometry(0.4, 12, 12), glowMat);
    this.body.add(glow);

    const coreMat = new THREE.MeshBasicMaterial({
      color: 0xaaff88,
      blending: THREE.AdditiveBlending,
      depthWrite: false,
    });
    const core = new THREE.Mesh(new THREE.SphereGeometry(0.2, 10, 10), coreMat);
    this.body.add(core);
  }

  update(dt: number, game: Game): boolean {
    this.lifetime -= dt;
    this.body.position.x += this.velocity.x * dt;
    this.body.position.y += this.velocity.y * dt;
    this.body.position.z += this.velocity.z * dt;

    // Hit the player
    if (game.player.health > 0) {
      const dist = this.body.position.distanceTo(game.player.body.position);
      if (dist < HIT_RADIUS) {
        game.player.damage(this.damage, this.body.position);
        this.dead = true;
        return false;
      }
    }

    if (this.lifetime <= 0 || this.body.position.y < -1) {
      this.dead = true;
      return false;
    }
    return true;
  }

  dispose() {
    this.body.removeFromParent();
    for (const child of [...this.body.children]) {
      if (child instanceof THREE.Mesh) {
        child.geometry.dispose();
        (child.material as THREE.Material).dispose();
      }
    }
  }
}
