use kira::{
    AudioManager, AudioManagerSettings, DefaultBackend, Mix,
    effect::reverb::ReverbBuilder,
    listener::ListenerHandle,
    track::{SendTrackBuilder, SendTrackHandle},
};

#[derive(Default)]
pub struct AudioEngine {
    pub manager: Option<AudioManager<DefaultBackend>>,
    pub listener: Option<ListenerHandle>,
    pub reverb_send: Option<SendTrackHandle>,
    pub initialized: bool,
}

impl AudioEngine {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn initialize(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if self.initialized {
            return Ok(());
        }

        match AudioManager::<DefaultBackend>::new(AudioManagerSettings::default()) {
            Ok(mut manager) => {
                let reverb_send = manager
                    .add_send_track(
                        SendTrackBuilder::new()
                            .with_effect(ReverbBuilder::new().mix(Mix::WET).damping(0.5)),
                    )
                    .map_err(|e| format!("Failed to create reverb send track: {}", e))?;

                self.reverb_send = Some(reverb_send);
                self.manager = Some(manager);
                self.initialized = true;
                log::info!("Audio engine initialized successfully with reverb");
                Ok(())
            }
            Err(error) => {
                log::error!("Failed to initialize audio engine: {}", error);
                Err(Box::new(error))
            }
        }
    }

    pub fn is_initialized(&self) -> bool {
        self.initialized && self.manager.is_some()
    }
}
