use eframe::egui;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use tokio::sync::watch;
use crate::ui::theme::Theme;
use crate::ui::components::{TopRibbon, TacticalCanvas, OperatorCard, ChatOverlay};

pub struct VoiceApp {
    // ── Components ──
    top_ribbon: TopRibbon,
    tactical_canvas: TacticalCanvas,
    operator_card: OperatorCard,
    chat_overlay: ChatOverlay,

    // ── Shared State ──
    mic_level_rx: watch::Receiver<f32>,
    mute_flag: Arc<AtomicBool>,
    audio_dumper_flag: Arc<AtomicBool>,
    
    // UI Local State
    show_dev_settings: bool,
}

impl VoiceApp {
    pub fn new(
        _cc: &eframe::CreationContext<'_>,
        mic_level_rx: watch::Receiver<f32>,
        mute_flag: Arc<AtomicBool>,
        audio_dumper_flag: Arc<AtomicBool>,
    ) -> Self {
        Theme::apply(&_cc.egui_ctx);

        Self {
            top_ribbon: TopRibbon::new(),
            tactical_canvas: TacticalCanvas::new(),
            operator_card: OperatorCard::new(),
            chat_overlay: ChatOverlay::new(),

            mic_level_rx,
            mute_flag,
            audio_dumper_flag,
            show_dev_settings: false,
        }
    }
}

impl eframe::App for VoiceApp {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        self.draw_ui(ui);
        
        // Forced refresh for animations
        ui.ctx().request_repaint();
    }
}

impl VoiceApp {
    fn draw_ui(&mut self, ui: &mut egui::Ui) {
        // Update local mute state from operator card
        self.mute_flag.store(self.operator_card.is_muted, std::sync::atomic::Ordering::Relaxed);
        
        // 1. Top Ribbon (Always Visible)
        egui::Panel::top("top_ribbon_panel")
            .frame(egui::Frame::NONE)
            .show_inside(ui, |ui| {
                self.top_ribbon.show(ui);
            });

        // 2. Main 3D Tactical Canvas
        egui::CentralPanel::default()
            .frame(egui::Frame::NONE.fill(Theme::BASE))
            .show_inside(ui, |ui| {
                self.tactical_canvas.show(ui);
            });

        // 3. Floating Overlays
        self.operator_card.show(ui.ctx());
        self.chat_overlay.show(ui.ctx());

        // 4. Developer Settings (Optional)
        if self.show_dev_settings {
            egui::Window::new("Telemetry Console")
                .show(ui.ctx(), |ui| {
                    ui.label(format!("Mic RMS: {:.4}", *self.mic_level_rx.borrow()));
                    ui.checkbox(&mut self.operator_card.is_muted, "Manual Mute");
                });
        }
    }
}
