use dioxus::prelude::*;

use crate::app::Route;
use crate::components::help_chat::HelpChat;
use crate::components::notification_bell::NotificationBell;
use crate::components::sidebar::Sidebar;
use crate::components::toast::{ToastContainer, Toasts};
use crate::infrastructure::auth_check::check_auth;

#[component]
pub fn AppShell() -> Element {
    use_context_provider(Toasts::new);

    let auth = use_server_future(check_auth)?;

    match auth() {
        Some(Ok(info)) if info.authenticated => {
            use_context_provider(|| Signal::new(info.clone()));
            rsx! {
                div { class: "app-shell",
                    Sidebar {}
                    main { class: "main-content",
                        Outlet::<Route> {}
                    }
                    NotificationBell {}
                    ToastContainer {}
                    HelpChat {}
                }
            }
        }
        Some(Ok(_)) | Some(Err(_)) => {
            // Not authenticated — redirect to Keycloak login
            rsx! {
                document::Script {
                    "window.location.href = '/auth';"
                }
            }
        }
        None => {
            rsx! {
                div { class: "flex items-center justify-center h-screen bg-gray-950",
                    p { class: "text-gray-400", "Loading..." }
                }
            }
        }
    }
}
