//! Leptos application root and router for public app.

use leptos::prelude::*;
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
use leptos_router::components::Router;

use crate::routes::UserRoutes;

#[cfg(feature = "ssr")]
use std::sync::Arc;

#[cfg(feature = "ssr")]
use crate::api::WebSocketState;

/// Application state for the public app.
#[cfg(feature = "ssr")]
#[derive(Clone)]
pub struct AppState {
    pub pool: sqlx::PgPool,
    pub leptos_options: LeptosOptions,
    pub ws_state: Arc<WebSocketState>,
}

#[cfg(feature = "ssr")]
impl axum::extract::FromRef<AppState> for sqlx::PgPool {
    fn from_ref(state: &AppState) -> Self {
        state.pool.clone()
    }
}

#[cfg(feature = "ssr")]
impl axum::extract::FromRef<AppState> for LeptosOptions {
    fn from_ref(state: &AppState) -> Self {
        state.leptos_options.clone()
    }
}

#[cfg(feature = "ssr")]
impl axum::extract::FromRef<AppState> for Arc<WebSocketState> {
    fn from_ref(state: &AppState) -> Self {
        state.ws_state.clone()
    }
}

/// Shell component for SSR.
pub fn shell(options: LeptosOptions) -> impl IntoView {
    view! {
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="utf-8" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <AutoReload options=options.clone() />
                <HydrationScripts options />
                <MetaTags />
            </head>
            <body class="bg-gray-900 text-white antialiased" data-app="user">
                <App />
            </body>
        </html>
    }
}

/// Main application component.
///
/// This wraps `UserRoutes` with a `Router` for standalone use.
/// For embedding in a combined app (e.g., chattyness-app), use `UserRoutes` directly.
#[component]
pub fn App() -> impl IntoView {
    // Provide meta context for title and meta tags
    provide_meta_context();

    view! {
        <Stylesheet id="leptos" href="/static/chattyness-app.css" />
        <Title text="Chattyness - Virtual Community Spaces" />

        <Router>
            <main>
                <UserRoutes />
            </main>
        </Router>
    }
}
