// src/modes/handlers/mode_manager.rs

use crate::state::app::state::AppState;
use crate::modes::handlers::event::EventHandler;
use crate::pages::routing::{Router, Page};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode {
    /// General mode = when focus is outside any canvas
    /// (Intro, Admin, Login/Register buttons, AddTable/AddLogic menus, dialogs, etc.)
    General,

    /// Command overlay (":" or "ctrl+;"), available globally
    Command,
}

pub struct ModeManager;

impl ModeManager {
    /// Determine current mode:
    /// - If navigation palette is active → General
    /// - If command overlay is active → Command
    /// - If focus is inside a canvas (Form, Login, Register, AddTable, AddLogic) → let canvas handle its own mode
    /// - Otherwise → General
    pub fn derive_mode(
        app_state: &AppState,
        event_handler: &EventHandler,
        router: &Router,
    ) -> AppMode {
        // Navigation palette always forces General
        if event_handler.navigation_state.active {
            return AppMode::General;
        }

        // Explicit command overlay flag
        if event_handler.command_mode {
            return AppMode::Command;
        }

        // If focus is inside a canvas, we don't duplicate canvas modes here.
        // Canvas crate owns ReadOnly/Edit/Highlight internally.
        match &router.current {
            Page::Form(_)
            | Page::Login(_)
            | Page::Register(_)
            | Page::AddTable(_)
            | Page::AddLogic(_) if !app_state.ui.focus_outside_canvas => {
                // Canvas active → let canvas handle its own AppMode
                AppMode::General
            }
            _ => AppMode::General,
        }
    }

    /// Command overlay can be entered from anywhere (General or Canvas).
    pub fn can_enter_command_mode(_current_mode: AppMode) -> bool {
        true
    }
}
