/*
RSK World – Tower Defense 3D (Projectile)
For support, licensing, or custom development inquiries: help@rskworld.in • Phone/WhatsApp: +91 9330539277
Website: RSK World • Business Inquiries: help@rskworld.in
🤝 Contributing: Suggestions and improvements are welcome!
*/

import * as THREE from 'three';

export class Projectile {
	constructor(origin, target, config = {}) {
		this.target = target;
		this.speed = config.speed ?? 28;
		this.damage = config.damage ?? 25;
		this.alive = true;
		this.maxLifetime = 3.0;
		this._life = 0;

		this.mesh = this._createMesh();
		this.mesh.position.copy(origin.clone().add(new THREE.Vector3(0, 1.2, 0)));
	}

	_createMesh() {
		const geo = new THREE.SphereGeometry(0.15, 12, 12);
		const mat = new THREE.MeshStandardMaterial({ color: 0xffd166, emissive: 0x7c3aed, emissiveIntensity: 0.8 });
		const m = new THREE.Mesh(geo, mat);
		m.castShadow = true;
		return m;
	}

	addTo(scene) { scene.add(this.mesh); }
	removeFrom(scene) { scene.remove(this.mesh); }

	update(delta) {
		if (!this.alive) return;
		this._life += delta;
		if (this._life > this.maxLifetime) {
			this.alive = false; return;
		}
		if (!this.target || !this.target.alive) { this.alive = false; return; }
		const pos = this.mesh.position;
		const targetPos = this.target.group.position.clone().add(new THREE.Vector3(0, 0.8, 0));
		const dir = targetPos.clone().sub(pos);
		const dist = dir.length();
		if (dist < (this.target.radius + 0.2)) {
			this.target.takeDamage(this.damage);
			this.alive = false;
			return;
		}
		dir.normalize();
		pos.addScaledVector(dir, this.speed * delta);
	}
}
