//! Language selector — dropdown using native `<details>` so it opens/closes
//! without JavaScript. Mirrors the Leptos `LanguageSelector` look (globe icon
//! summary, panel of options) but the options are HTMX `hx-post` triggers
//! that go to `/api/htmx/lang/{code}`. The server responds with the new
//! selector fragment + `HX-Redirect` to the localised URL.

use crate::primitives::htmx_path;

/// Render the language selector for the currently active language.
pub fn render_lang_selector(current_lang: &str) -> String {
    let languages: [(&str, &str); 2] = [("en", "English"), ("es", "Español")];
    let langs: Vec<minijinja::Value> = languages
        .iter()
        .map(|(code, label)| {
            let endpoint = htmx_path(&format!("lang/{code}"));
            minijinja::context! {
                code => code,
                label => label,
                endpoint => endpoint,
                is_active => *code == current_lang,
            }
        })
        .collect();

    let ctx = minijinja::context! { languages => langs };
    rustelo_pages_htmx::fragment_env()
        .and_then(|env| {
            env.get_template("partials/nav/lang_selector.j2")
                .and_then(|t| t.render(ctx))
                .ok()
        })
        .unwrap_or_else(|| fallback_lang_selector(current_lang, &languages))
}

fn fallback_lang_selector(current_lang: &str, languages: &[(&str, &str)]) -> String {
    let mut options = String::new();
    for (code, label) in languages {
        let endpoint = htmx_path(&format!("lang/{code}"));
        let active = if *code == current_lang {
            r#" aria-current="true" disabled"#
        } else {
            ""
        };
        options.push_str(&format!(
            r##"<button type="button" hx-post="{ep}" hx-target="#lang-selector" hx-swap="outerHTML"{active} data-lang="{code}">{label}</button>"##,
            ep = html_escape::encode_double_quoted_attribute(&endpoint),
        ));
    }
    format!(
        r##"<details id="lang-selector" class="language-selector relative"><summary aria-label="Language">🌐</summary><div class="absolute right-0 mt-1 w-48 ds-bg border rounded-md shadow-lg z-10"><div class="py-1">{options}</div></div></details>"##
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn emits_two_buttons() {
        let html = render_lang_selector("en");
        assert_eq!(html.matches("<button").count(), 2);
    }

    #[test]
    fn marks_active_language() {
        let html = render_lang_selector("es");
        assert!(html.contains(r#"aria-current="true" disabled"#));
        assert!(html.contains(r#"data-lang="es""#));
    }

    #[test]
    fn endpoints_target_correct_paths() {
        let html = render_lang_selector("en");
        assert!(html.contains(r#"hx-post="/api/htmx/lang/en""#));
        assert!(html.contains(r#"hx-post="/api/htmx/lang/es""#));
    }

    #[test]
    fn uses_native_details_dropdown() {
        let html = render_lang_selector("en");
        assert!(html.contains("<details"));
    }

    #[test]
    fn target_matches_wrapper_id() {
        let html = render_lang_selector("en");
        assert!(html.contains(r##"id="lang-selector""##));
        assert!(html.contains(r##"hx-target="#lang-selector""##));
    }
}
