// client/src/utils/debug_logger.rs
use lazy_static::lazy_static;
use std::collections::VecDeque; // <-- FIX: Import VecDeque
use std::io;
use std::sync::{Arc, Mutex}; // <-- FIX: Import Mutex

lazy_static! {
    static ref UI_DEBUG_BUFFER: Arc<Mutex<VecDeque<(String, bool)>>> =
        Arc::new(Mutex::new(VecDeque::from([(String::from("Logger initialized..."), false)])));
}

#[derive(Clone)]
pub struct UiDebugWriter;

impl Default for UiDebugWriter {
    fn default() -> Self {
        Self::new()
    }
}

impl UiDebugWriter {
    pub fn new() -> Self {
        Self
    }
}

impl io::Write for UiDebugWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let mut buffer = UI_DEBUG_BUFFER.lock().unwrap();
        let message = String::from_utf8_lossy(buf);
        let trimmed_message = message.trim().to_string();
        let is_error = trimmed_message.starts_with("ERROR");
        // Add the new message to the back of the queue
        buffer.push_back((trimmed_message, is_error));
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

// A public function to pop the next message from the front of the queue.
pub fn pop_next_debug_message() -> Option<(String, bool)> {
    UI_DEBUG_BUFFER.lock().unwrap().pop_front()
}
