//! Root application component
//!
//! This module contains the main App component that serves as the entry point
//! for the Leptos application. It sets up routing, theming, and global state.

use crate::components::{error_boundary::ErrorBoundary, footer::Footer, header::Header};
use crate::pages::{home::HomePage, not_found::NotFoundPage};
use crate::state::AppState;
use leptos::prelude::*;
use leptos_meta::*;
use leptos_router::{components::*, *};

/// Root application component
///
/// This component:
/// - Provides global application state via context
/// - Sets up routing with leptos_router
/// - Manages theme switching (light/dark)
/// - Provides metadata and document title
/// - Wraps the application in an error boundary
///
/// # Example
///
/// ```ignore
/// mount_to_body(|| view! { <App/> });
/// ```
#[component]
pub fn App() -> impl IntoView {
    // Provides metadata/title management
    provide_meta_context();

    // Create and provide global app state
    let app_state = AppState::new();
    provide_context(app_state);

    // Reactive effect to apply theme to document
    Effect::new(move |_| {
        let theme = app_state.theme.get();
        if let Some(window) = web_sys::window() {
            if let Some(document) = window.document() {
                if let Some(html) = document.document_element() {
                    let class_list = html.class_list();
                    let _ = class_list.remove_1("dark");
                    let _ = class_list.remove_1("light");
                    let _ = class_list.add_1(theme.as_str());
                }
            }
        }
    });

    view! {
        <Title text="Syntaxis Dashboard"/>
        <Meta name="description" content="Real-time syntaxis management dashboard"/>
        <Meta name="viewport" content="width=device-width, initial-scale=1.0"/>

        <ErrorBoundary>
            <div class="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors duration-200">
                <Router>
                    <Header/>
                    <main class="dash-container py-8">
                        <Routes fallback=NotFoundPage>
                            <Route path=path!("/") view=HomePage/>
                        </Routes>
                    </main>
                    <Footer/>
                </Router>
            </div>
        </ErrorBoundary>
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use dashboard_shared::Theme;

    #[test]
    fn test_app_state_provided() {
        // This test verifies that AppState can be created
        let state = AppState::new();
        assert_eq!(state.get_theme(), Theme::Light);
    }
}
