use eframe::egui;
use crate::ui::theme::Theme;

pub struct ChatOverlay {
    pub messages: Vec<(String, String)>,
    pub input: String,
}

impl ChatOverlay {
    pub fn new() -> Self {
        Self {
            messages: vec![
                ("HQ".to_string(), "Tactical Command Center online.".to_string()),
                ("Samuel".to_string(), "All units, check in.".to_string()),
            ],
            input: String::new(),
        }
    }

    pub fn show(&mut self, ctx: &egui::Context) {
        egui::Window::new("COMMUNICATION OVERLAY")
            .id(egui::Id::new("chat_overlay"))
            .anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-24.0, -24.0))
            .resizable(true)
            .default_width(400.0)
            .frame(Theme::glass_frame())
            .title_bar(false)
            .show(ctx, |ui| {
                ui.vertical(|ui| {
                    // Header
                    ui.horizontal(|ui| {
                        ui.label(egui::RichText::new("󰭹").size(16.0).color(Theme::COBALT_BLUE));
                        ui.label(egui::RichText::new("OPERATIONAL CHAT").size(11.0).strong().color(Theme::TEXT_SECONDARY));
                    });
                    ui.add_space(8.0);
                    ui.separator();

                    // Message Area
                    egui::ScrollArea::vertical()
                        .max_height(200.0)
                        .stick_to_bottom(true)
                        .show(ui, |ui| {
                            for (sender, msg) in &self.messages {
                                ui.add_space(8.0);
                                ui.vertical(|ui| {
                                    ui.label(egui::RichText::new(sender).size(10.0).strong().color(Theme::COBALT_BLUE));
                                    ui.label(egui::RichText::new(msg).size(13.0).color(Theme::TEXT_PRIMARY));
                                });
                            }
                        });

                    ui.add_space(12.0);

                    // Input
                    ui.horizontal(|ui| {
                        let response = ui.add(
                            egui::TextEdit::singleline(&mut self.input)
                                .hint_text("Transmit command...")
                                .frame(egui::Frame::NONE)
                                .margin(egui::Margin::same(8))
                                .desired_width(f32::INFINITY)
                        );
                        
                        if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
                            if !self.input.is_empty() {
                                self.messages.push(("Samuel".to_string(), self.input.clone()));
                                self.input.clear();
                            }
                        }
                    });
                });
            });
    }
}
