//! Leptos-hydration shell. Builds the SSR HTML matched to the WASM client
//! tree emitted by `crates/client/`. SEO comes from `super::seo`; head bundles
//! from `super::common`.

use leptos::prelude::*;
use leptos_config::LeptosOptions;
use leptos_meta::provide_meta_context;
use rustelo_web::rustelo_core_lib::routing::utils::detect_language_from_path;
use rustelo_web::rustelo_core_lib::state::LanguageContext;

use super::{common, seo};

/// Render the full Leptos-hydration page as a complete HTML document.
pub fn render(_options: LeptosOptions, path: Option<String>) -> String {
    let current_path = path.unwrap_or_default();
    let language = detect_language_from_path(&current_path);
    let package_name =
        std::env::var("LEPTOS_OUTPUT_NAME").unwrap_or_else(|_| "website".to_string());

    let base_url = seo::site_base_url();
    let page_seo = seo::build_page_seo(&current_path, &language, &base_url);
    let head_tags = rustelo_seo::render_head_tags(&page_seo).unwrap_or_else(|err| {
        tracing::error!("SEO render failed: {err}");
        String::new()
    });

    let body_html = {
        let owner = Owner::new();
        let path_for_body = current_path.clone();
        let lang_for_body = language.clone();
        let lang_for_nav = language.clone();
        let lang_for_footer = language.clone();
        owner.with(|| {
            provide_meta_context();
            let lang_ctx = LanguageContext::new();
            lang_ctx.current.set(lang_for_body.clone());
            provide_context(lang_ctx);
            provide_context(crate::theme::load_logo_config());

            let (show_login, set_show_login) = signal(false);
            view! {
                <body>
                    <rustelo_components_leptos::theme::ThemeProvider>
                        <div class="min-h-screen ds-bg-page flex flex-col">
                            <rustelo_components_leptos::navigation::NavMenu language=lang_for_nav.clone() />
                            <main id="main-content" class="max-w-7xl mx-auto py-2 sm:ds-container flex-grow page-content fade-out">
                                { let p = path_for_body.clone(); let l = lang_for_body.clone();
                                  move || crate::render_website_page_ssr(&p, &l) }
                            </main>
                            <rustelo_components_leptos::navigation::Footer language=lang_for_footer.clone() />
                            <rustelo_components_leptos::LoginModal show=show_login set_show=set_show_login />
                            <rustelo_components_leptos::CookieBanner
                                policy_page="/privacy".to_string()
                                detail_mode="page".to_string()
                            />
                            <rustelo_components_leptos::ToastContainer />
                        </div>
                    </rustelo_components_leptos::theme::ThemeProvider>
                </body>
            }
            .to_html()
        })
    };

    let hydration_bootstrap = r#"<script id="leptos-hydration">
globalThis.__RESOLVED_RESOURCES = {};
globalThis.__INCOMPLETE_CHUNKS = [];
window.__RESOLVED_RESOURCES = globalThis.__RESOLVED_RESOURCES;
window.__INCOMPLETE_CHUNKS = globalThis.__INCOMPLETE_CHUNKS;
</script>"#;
    let hydration_module = format!(
        r#"<script type="module">
import * as wasmModule from '/pkg/{pn}.js';
async function run() {{
  try {{
    await wasmModule.default({{ module_or_path: '/pkg/{pn}.wasm' }});
    if (typeof wasmModule.rustelo_push_toast === 'function') {{
      window.rustelo_push_toast = wasmModule.rustelo_push_toast;
    }}
  }} catch (err) {{
    console.error('[HYDRATION] Error:', err);
  }}
}}
run();
</script>"#,
        pn = package_name
    );
    let modulepreload = format!(
        r#"<link rel="modulepreload" href="/pkg/{pn}.js">"#,
        pn = package_name
    );

    let mut html = String::with_capacity(8 * 1024);
    html.push_str("<!DOCTYPE html>");
    html.push_str(&format!(r#"<html lang="{}">"#, language));
    html.push_str("<head>");
    html.push_str(common::baseline_meta());
    html.push_str(&head_tags);
    html.push_str(&common::stylesheet_links());
    html.push_str(&modulepreload);
    html.push_str(&common::bundle_scripts());
    html.push_str(r#"<script src="/public/console-logger.js"></script>"#);
    html.push_str(&common::i18n_script(&language));
    html.push_str(&common::content_data_script(&current_path, &language));
    html.push_str("</head>");
    // body_html already contains <body>...</body>
    html.push_str(&body_html);
    // Insert hydration bootstrap + module before </body> closing.
    if let Some(idx) = html.rfind("</body>") {
        html.insert_str(idx, &format!("{hydration_bootstrap}{hydration_module}"));
    } else {
        html.push_str(hydration_bootstrap);
        html.push_str(&hydration_module);
    }
    html.push_str("</html>");
    html
}
