use std::f32::consts::TAU;

use macroquad::math::Vec2;

use crate::{
    behavior::enemy::EnemyBehavior,
    command::{Transform, TransformEntity},
    context::DeathContext,
    enemy::Enemy,
};

#[derive(Clone)]
pub struct SplitOnDeath {
    generations: u32,
    count: u32,
    spread: f32,
}

impl SplitOnDeath {
    pub fn create(tier: u32) -> Box<dyn EnemyBehavior> {
        Box::new(Self {
            count: tier,
            generations: tier,
            spread: 22.0,
        })
    }
}

impl EnemyBehavior for SplitOnDeath {
    fn on_death(&mut self, e: &mut Enemy, c: &mut DeathContext) {
        if self.generations == 0 || self.count == 0 {
            return;
        }
        self.generations -= 1;
        self.count -= 1;
        for i in 0..self.count {
            let angle = TAU * (i as f32) / self.count.max(1) as f32; // even ring
            let jitter = (c.rng.f32() - 0.5) * 0.6; // ±0.3 rad, deterministic
            let dist = self.spread * (0.5 + 0.5 * c.rng.f32()); // 50–100% of spread
            let location = e.pos + Vec2::from_angle(angle + jitter) * dist;
            c.cmd.replicate(Transform {
                entity: TransformEntity::Enemy,
                id: e.id,
                location,
            });
        }
    }
}
