/*
RSK World – Tower Defense 3D (AllyUnit)
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 AllyUnit {
	constructor(position) {
		this.group = new THREE.Group();
		this.group.position.copy(position);
		this.speed = 4.0;
		this.damage = 30;
		this.range = 1.2;
		this.cooldown = 0.7;
		this._cd = 0;
		this._anim = 0;
		this.alive = true;
		this._create();
	}

	_create() {
		const body = new THREE.Mesh(new THREE.CapsuleGeometry(0.35, 0.6, 6, 10), new THREE.MeshStandardMaterial({ color: 0xf59e0b }));
		body.castShadow = true; body.receiveShadow = true; this.group.add(body);
		const head = new THREE.Mesh(new THREE.SphereGeometry(0.28, 12, 10), new THREE.MeshStandardMaterial({ color: 0xffe0c0 }));
		head.position.y = 0.7; this.group.add(head);
	}

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

	_updateTarget(enemies) {
		let best = null; let bestDistSq = Infinity;
		for (const e of enemies) {
			const dSq = e.group.position.distanceToSquared(this.group.position);
			if (dSq < bestDistSq) { best = e; bestDistSq = dSq; }
		}
		this.target = best;
	}

	update(delta, enemies) {
		if (!this.alive) return;
		this._cd = Math.max(0, this._cd - delta);
		this._updateTarget(enemies);
		if (!this.target) return;
		const pos = this.group.position;
		const to = this.target.group.position.clone().sub(pos);
		const d = to.length();
		if (d > this.range) {
			to.normalize(); pos.addScaledVector(to, this.speed * delta);
			this.group.rotation.y = Math.atan2(to.x, to.z);
		} else if (this._cd <= 0) {
			this.target.takeDamage(this.damage);
			this._cd = this.cooldown;
		}
		this._anim += delta * 6.0; this.group.position.y = Math.abs(Math.sin(this._anim)) * 0.04;
	}
}
