//! Client-side language selector component
//!
//! Reactive implementation with i18n content loading

use ::rustelo_core_lib::i18n::{build_page_content_patterns, SsrTranslator};
use leptos::prelude::*;

/// Client-side reactive language button
#[component]
pub fn LanguageButton(
    code: String,
    native_name: String,
    is_current: bool,
    on_select: impl Fn(String) + 'static + Copy,
) -> impl IntoView {
    let code_clone = code.clone();

    view! {
        <button
            type="button"
            class="w-full px-3 py-2 text-left text-sm ds-bg hover:ds-bg-hover ds-text transition-colors duration-200"
            class:opacity-50=is_current
            class:cursor-not-allowed=is_current
            class:pointer-events-none=is_current
            disabled=is_current
            on:click=move |_| {
                if !is_current {
                    on_select(code_clone.clone());
                }
            }
        >
            <div class="flex items-center">
                <div class="w-4 h-4 mr-2">
                    {if is_current { "✓" } else { "" }}
                </div>
                {native_name.clone()}
            </div>
        </button>
    }
}

/// Client-side reactive language selector component
#[component]
pub fn LanguageSelectorClient(
    #[prop(optional)] class: Option<String>,
    #[prop(optional)] current_language: Option<String>,
) -> impl IntoView {
    // Get current language from URL or browser detection
    let current_lang = current_language.unwrap_or_else(|| {
        #[cfg(target_arch = "wasm32")]
        {
            if let Some(window) = web_sys::window() {
                if let Ok(pathname) = window.location().pathname() {
                    return rustelo_core_lib::routing::utils::detect_language_from_path(&pathname);
                }
            }
        }
        rustelo_core_lib::config::get_default_language().to_string()
    });

    // Load i18n content for language selector
    let translator = SsrTranslator::new(current_lang.clone());
    let lang_content = build_page_content_patterns(&translator, &["lang-"]);

    view! {
        <crate::navigation::language_selector::unified::LanguageSelector
            class=class.unwrap_or_default()
            current_language=Some(current_lang)
            content=lang_content
            navigation_signals=None
        />
    }
}
