use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::components::{Route, Router, Routes};
use leptos_router::path;

use crate::components::main_layout::MainLayout;
use crate::components::theme::ThemeProvider;
use crate::config;
use crate::pages::*;

/// Main application component with routing
#[component]
pub fn App() -> impl IntoView {
    // Load configuration at startup
    Effect::new(move || {
        spawn_local(async {
            let cfg = config::load_config().await;
            config::init_config(cfg.clone());
            web_sys::console::log_1(
                &format!(
                    "🔧 Config initialized: orchestrator={}, kms={}",
                    cfg.api.orchestrator_url, cfg.features.enable_auth
                )
                .into(),
            );
        });
    });

    view! {
        <ThemeProvider>
            <Router>
                <MainLayout>
                    <Routes fallback=|| view! { <not_found::NotFound/> }>
                        <Route path=path!("/") view=dashboard::DashboardPage/>
                        <Route path=path!("/dashboard") view=dashboard::DashboardPage/>
                        <Route path=path!("/servers") view=servers::ServersPage/>
                        <Route path=path!("/clusters") view=clusters::ClustersPage/>
                        <Route path=path!("/taskservs") view=taskservs::TaskservsPage/>
                        <Route path=path!("/workflows") view=workflows::WorkflowsPage/>
                        <Route path=path!("/kms") view=kms::KmsPage/>
                        <Route path=path!("/detection") view=detection::DetectionDashboardPage/>
                        <Route path=path!("/rules") view=rules::RulesEditorPage/>
                        <Route path=path!("/deployment") view=deployment::DeploymentPreviewPage/>
                        <Route path=path!("/settings") view=settings::SettingsPage/>
                    </Routes>
                </MainLayout>
            </Router>
        </ThemeProvider>
    }
}
