//! Website client implementation
//!
//! This crate provides the WASM-compiled client-side functionality for the website.
//! It integrates with the Rustelo framework to provide reactive, SSR-compatible
//! web components with automatic hydration.

#![allow(unused_variables, dead_code)]
#![recursion_limit = "256"]

pub mod app;
pub mod page_provider;
pub mod policy;
pub mod theme;

// Re-export the main App component for server-side use
pub use app::AppComponent;

use leptos::prelude::*;

// All generated artifacts are listed in the aggregator produced by build.rs.
// This file is the single coupling point between lib.rs and the build output.
include!(concat!(env!("OUT_DIR"), "/generated_includes.rs"));

/// Initialize WASM resources to ensure consistency with server rendering
/// This populates registries with embedded configuration to avoid
/// hydration mismatches caused by different registry state on server vs client
fn initialize_wasm_resources() {
    use rustelo_core_lib::registration::{MENU_REGISTRY, THEME_REGISTRY};

    // Populate theme registry if not already present.
    // THEME_TOML is generated by client/build.rs from site/config/index.ncl [logo].
    if let Ok(registry) = THEME_REGISTRY.read() {
        if registry.get("default").is_none() {
            drop(registry); // Release read lock

            if let Ok(mut registry) = THEME_REGISTRY.write() {
                let _ = registry.insert("default".to_string(), crate::theme::THEME_TOML.to_string());
            }
        }
    }

    // Populate menu registries with compile-time embedded TOML content.
    // The generated function (from menu_registry_fn.rs) mirrors what
    // WebsiteResourceContributor does on the server, ensuring NavMenuClient
    // reads the same menu items during hydration.
    if let Ok(registry) = MENU_REGISTRY.read() {
        if registry.is_empty() {
            drop(registry); // Release read lock before write
            populate_wasm_menu_registry();
        }
    }

    // Populate footer registry with compile-time embedded TOML content.
    use rustelo_core_lib::registration::FOOTER_REGISTRY;
    if let Ok(registry) = FOOTER_REGISTRY.read() {
        if registry.is_empty() {
            drop(registry);
            populate_wasm_footer_registry();
        }
    }

    // Populate FTL registry with compile-time embedded translations for all languages.
    // This enables get_parsed_ftl_for_language() to work in WASM, so t_for_language()
    // returns the correct translations when switching language — not just the language
    // baked into the SSR HTML's <script id="i18n-data">.
    use rustelo_core_lib::registration::FTL_REGISTRY;
    if let Ok(registry) = FTL_REGISTRY.read() {
        if registry.is_empty() {
            drop(registry);
            populate_wasm_ftl_registry();
        }
    }

    // Register the build-time content URL so get_server_content_url() returns
    // the correct value in WASM (env vars are always absent in the browser).
    // config::CONTENT_URL is generated from rustelo.manifest.toml [deployment].content_url.
    rustelo_core_lib::routing::generated_access::register_server_content_url(config::CONTENT_URL);

    // Seed the route cache with build-time data so get_localized_route() works
    // without filesystem access. Must run before any routing call.
    crate::routes::seed_routes_cache();
}

/// WASM entry point with auto-start
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn main() {
    use leptos::prelude::*;

    web_sys::console::log_1(&"✅ Starting hydration...".into());

    // Initialize WASM resources before hydration
    initialize_wasm_resources();

    // Initialize page provider for dynamic component rendering
    let _ = page_provider::initialize();

    // Detect current path so language is correct on initial hydration
    let initial_path = web_sys::window()
        .and_then(|w| w.location().pathname().ok())
        .unwrap_or_default();

    // Hydrate the server-rendered HTML with client-side interactivity
    leptos::mount::hydrate_body(move || {
        view! { <crate::app::AppComponent initial_path=initial_path.clone() /> }
    });

    web_sys::console::log_1(&"✅ Hydration complete - application interactive".into());
}

/// Hydrate server-rendered HTML with client interactivity
fn hydrate_app() {
    use leptos::prelude::*;

    web_sys::console::log_1(&"✅ Starting hydration...".into());

    leptos::mount::hydrate_body(|| {
        view! { <crate::app::AppComponent /> }
    });

    web_sys::console::log_1(&"✅ Hydration complete - application interactive".into());
}
