//! Nav login trigger. Fetches the login modal into `#modal-slot`.

/// Render the "Sign in" button (defaults to English).
pub fn render_login_button(label: &str) -> String {
    render_login_button_for_lang(label, "en")
}

/// Render the "Sign in" button with a language hint for the modal.
pub fn render_login_button_for_lang(label: &str, lang: &str) -> String {
    let ctx = minijinja::context! {
        label => label,
        lang => lang,
    };
    rustelo_pages_htmx::fragment_env()
        .and_then(|env| {
            env.get_template("partials/nav/login_button.j2")
                .and_then(|t| t.render(ctx))
                .ok()
        })
        .unwrap_or_else(|| {
            let endpoint = format!("/api/htmx/auth/login-modal?lang={}", html_escape::encode_double_quoted_attribute(lang));
            format!(
                r##"<button type="button" class="ds-btn-ghost-sm" hx-get="{ep}" hx-target="#modal-slot" hx-swap="outerHTML">{label}</button>"##,
                ep = html_escape::encode_double_quoted_attribute(&endpoint),
                label = html_escape::encode_text(label),
            )
        })
}

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

    #[test]
    fn triggers_modal_fetch() {
        let html = render_login_button("Sign in");
        assert!(html.contains("/api/htmx/auth/login-modal"));
        assert!(html.contains(r##"hx-target="#modal-slot""##));
    }

    #[test]
    fn passes_lang_query_param() {
        let html = render_login_button_for_lang("Entrar", "es");
        assert!(html.contains("lang=es"));
    }

    #[test]
    fn escapes_label() {
        let html = render_login_button("<x>");
        assert!(html.contains("&lt;x&gt;"));
    }
}
