use leptos::prelude::*;
use rustelo_core_lib::i18n::content_helper::create_content_provider_reactive;

/// Async sleep helper (WASM-only; SSR countdown is never actually ticked).
#[cfg(target_arch = "wasm32")]
async fn sleep_secs(secs: u32) {
    gloo_timers::future::sleep(std::time::Duration::from_secs(u64::from(secs))).await;
}

/// Signout goodbye page.
///
/// SSR: renders a generic goodbye (no name, no countdown).
/// WASM: reads `goodbye_name` from `sessionStorage`, personalises the title,
///       and starts a 10-second countdown that redirects to `/`.
#[component]
pub fn UnifiedSignoutPage(
    #[prop(default = rustelo_core_lib::config::get_default_language().to_string())]
    _language: String,
    #[prop(optional)] lang_content: Option<std::collections::HashMap<String, String>>,
) -> impl IntoView {
    let content = create_content_provider_reactive(lang_content);

    // Reactive title — SSR stays generic; WASM may update it after reading
    // sessionStorage.
    let title = RwSignal::new(content.t("signout-title"));
    let countdown = RwSignal::new(10u32);
    let home_path = {
        let lang = _language.clone();
        if lang == "es" {
            "/inicio".to_string()
        } else {
            "/".to_string()
        }
    };

    #[cfg(target_arch = "wasm32")]
    {
        let content_clone = content.clone();
        let home = home_path.clone();
        let set_path = use_context::<WriteSignal<String>>();
        leptos::task::spawn_local(async move {
            // Personalise greeting from sessionStorage.
            let goodbye_name = web_sys::window()
                .and_then(|w| w.session_storage().ok().flatten())
                .and_then(|s| s.get_item("goodbye_name").ok().flatten());

            let t = match goodbye_name {
                Some(ref name) if !name.is_empty() => content_clone
                    .t("signout-title-with-name")
                    .replace("$name", name),
                _ => content_clone.t("signout-title"),
            };
            title.set(t);

            // 10-second countdown then navigate.
            let mut remaining = 10u32;
            while remaining > 0 {
                sleep_secs(1).await;
                remaining = remaining.saturating_sub(1);
                countdown.set(remaining);
            }
            if let Some(sp) = set_path {
                sp.set(home);
            } else if let Some(win) = web_sys::window() {
                let _ = win.location().set_href(&home);
            }
        });
    }

    let home = home_path.clone();
    let redirect_label = {
        let c = content.clone();
        move || {
            c.t("signout-redirect")
                .replace("$seconds", &countdown.get().to_string())
        }
    };

    view! {
        <div class="ds-bg-page min-h-screen flex items-center justify-center">
            <div class="text-center max-w-lg mx-auto px-6 py-16">
                <div class="text-6xl mb-6">"👋"</div>
                <h1 class="text-4xl font-bold ds-text mb-4">{move || title.get()}</h1>
                <p class="ds-text-secondary text-lg mb-8">{content.t("signout-subtitle")}</p>

                <div class="flex flex-col sm:flex-row gap-4 justify-center mb-8">
                    <a href={home.clone()} class="btn btn-primary">
                        {content.t("signout-home")}
                    </a>
                    <a href="/login" class="btn btn-ghost">
                        {content.t("signout-login-again")}
                    </a>
                </div>

                <p class="text-sm ds-text-secondary opacity-60">{redirect_label}</p>
            </div>
        </div>
    }
}
