use leptos::prelude::*;
use leptos_config::LeptosOptions;
use leptos_meta::provide_meta_context;

/// SSR shell for Axum/Leptos integration.
///
/// Registered via `resources::initialize()` → `register_shell_renderer`.
/// The path argument is the request's URL path, used to detect language
/// and pass to the page router.
pub fn shell_with_path(_options: LeptosOptions, path: Option<String>) -> impl IntoView {
    let current_path = path.unwrap_or_default();
    let package_name = std::env::var("LEPTOS_OUTPUT_NAME").unwrap_or_else(|_| "site".to_string());

    let path_for_app = current_path.clone();

    let app = move || {
        provide_meta_context();
        view! { <crate::app::AppComponent path=path_for_app.clone() /> }
    };

    view! {
      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="utf-8"/>
          <meta name="viewport" content="width=device-width, initial-scale=1"/>
          <title>"My Site"</title>
          <link rel="modulepreload" href={format!("/pkg/{}.js", package_name)} />
          <leptos_meta::MetaTags />
        </head>
        <body>
          {app()}
          <script id="leptos-hydration">
            {r#"
            globalThis.__RESOLVED_RESOURCES = {};
            globalThis.__INCOMPLETE_CHUNKS = [];
            window.__RESOLVED_RESOURCES = globalThis.__RESOLVED_RESOURCES;
            window.__INCOMPLETE_CHUNKS = globalThis.__INCOMPLETE_CHUNKS;
            "#}
          </script>
          <script type="module">
            {format!(
              r#"import * as w from '/pkg/{name}.js';
              async function run() {{ await w.default({{ module_or_path: '/pkg/{name}.wasm' }}); }}
              run();"#,
              name = package_name
            )}
          </script>
        </body>
      </html>
    }
}
