//! Simplified language selector component with no reactive complexity
//!
//! This module provides a language-agnostic implementation that uses the
//! LanguageRegistry to automatically discover available languages without
//! reactive state management.

use ::rustelo_core_lib::i18n::language_config::get_language_registry;
use leptos::ev::MouseEvent;
use leptos::prelude::*;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast;

/// Simple language selector component - SVG icon only, no reactive state
#[component]
pub fn LanguageSelector(
    #[prop(optional)] class: Option<String>,
    #[prop(default = Some(rustelo_core_lib::config::get_default_language().to_string()))]
    current_language: Option<String>,
    #[prop(optional)] _current_path: Option<String>,
    #[prop(optional)] content: Option<std::collections::HashMap<String, String>>,
    /// Navigation signals for client-side routing (None on SSR, Some on WASM)
    navigation_signals: Option<(ReadSignal<String>, WriteSignal<String>)>,
) -> impl IntoView {
    // current_language prop kept for call-site API compatibility; active state is
    // read reactively from the language context instead.
    let _ = current_language;
    let selector_class = class.unwrap_or_default();

    // Get language registry for auto-detection
    let registry = get_language_registry();
    let available_languages = registry.get_available_languages();

    // State for dropdown visibility
    let (_is_open, set_is_open) = signal(false);

    // Get language context for switching
    let language_context = rustelo_core_lib::state::use_language();

    // Setup i18n content with fallbacks
    let lang_content = content.unwrap_or_else(|| {
        tracing::warn!("No content provided to LanguageSelector, using empty HashMap");
        std::collections::HashMap::new()
    });

    // Simple content lookup function - clone to create multiple copies
    let content_lookup = |key: &str| -> String {
        lang_content.get(key).cloned().unwrap_or_else(|| {
            tracing::warn!(
                "Language selector i18n key not found: '{}', using fallback",
                key
            );
            match key {
                "lang-selector-button" => "Language selector".to_string(),
                _ => {
                    // For unknown language codes, return uppercase code
                    if key.starts_with("lang-") && key.ends_with("-display") {
                        let lang_code =
                            key.trim_start_matches("lang-").trim_end_matches("-display");
                        lang_code.to_uppercase()
                    } else {
                        key.to_string()
                    }
                }
            }
        })
    };

    // Get the button aria-label value early to avoid closure conflicts
    let aria_label = content_lookup("lang-selector-button");

    // Handle escape key to close dropdown
    #[cfg(target_arch = "wasm32")]
    {
        let set_is_open_clone = set_is_open;
        Effect::new(move |_| {
            let closure =
                wasm_bindgen::closure::Closure::wrap(Box::new(move |e: web_sys::KeyboardEvent| {
                    if e.key() == "Escape" {
                        set_is_open_clone.set(false);
                    }
                }) as Box<dyn FnMut(_)>);

            if let Some(window) = web_sys::window() {
                if let Some(document) = window.document() {
                    let _ = document.add_event_listener_with_callback(
                        "keydown",
                        closure.as_ref().unchecked_ref(),
                    );
                }
            }
            closure.forget();
        });
    }

    // Extract set_path from navigation_signals prop
    let set_path = navigation_signals.map(|(_, set_path)| set_path);

    // Generate dropdown items reactively from available languages
    // Build one button per language. All dynamic state (class, disabled, check
    // mark) uses reactive closures reading language_context.current directly —
    // this guarantees updates via fine-grained reactivity without relying on
    // tachys Vec reconciliation, which patches DOM attributes but never
    // replaces on:click handlers.
    let language_options: Vec<_> = available_languages
        .iter()
        .map(|lang_code| {
            let display_name = registry.get_display_name(lang_code, false);

            // Per-button signal reads — each needs its own clone of the context handle
            // and language code so the reactive closures can capture them by move.
            let lc_class = lang_code.clone();
            let ctx_class = language_context.clone();
            let lc_disabled = lang_code.clone();
            let ctx_disabled = language_context.clone();
            let lc_check = lang_code.clone();
            let ctx_check = language_context.clone();

            // Create the language option button
            view! {
                <button
                    class=move || {
                        let is_active = {
                            #[cfg(target_arch = "wasm32")]
                            { ctx_class.current.get() == lc_class }
                            #[cfg(not(target_arch = "wasm32"))]
                            { ctx_class.current.get_untracked() == lc_class }
                        };
                        if is_active {
                            "w-full text-left px-3 py-2 text-sm text-gray-400 cursor-not-allowed flex items-center"
                        } else {
                            "w-full text-left px-3 py-2 text-sm ds-text hover:ds-bg-hover flex items-center"
                        }
                    }
                    disabled=move || {
                        #[cfg(target_arch = "wasm32")]
                        { ctx_disabled.current.get() == lc_disabled }
                        #[cfg(not(target_arch = "wasm32"))]
                        { ctx_disabled.current.get_untracked() == lc_disabled }
                    }
                    data-language={lang_code.clone()}
                    hx-post={format!("/api/htmx/lang/{}", lang_code)}
                    hx-target="#lang-selector"
                    hx-swap="outerHTML"
                    on:click={
                        let _btn_lang_code = lang_code.clone();
                        let lang_code_clone = lang_code.clone();
                        let _set_path_signal = set_path;
                        let _current_path_clone = _current_path.clone();
                        let _lang_ctx = language_context.clone();
                        move |e: MouseEvent| {
                            // Read signal at click time — on:click is never replaced by
                            // tachys reconciliation, so we cannot rely on captured values.
                            let is_active_now = _lang_ctx.current.get_untracked() == _btn_lang_code;
                            #[cfg(target_arch = "wasm32")]
                            web_sys::console::log_1(&format!("🌍 Language Selector: Language button clicked - {}, is_active_now: {}", lang_code_clone, is_active_now).into());

                                if !is_active_now {
                                    e.prevent_default();
                                    set_is_open.set(false); // Close dropdown after selection

                                    // Save language preference in cookie before navigation
                                    #[cfg(target_arch = "wasm32")]
                                    {
                                        _lang_ctx.switch_language(&_btn_lang_code);
                                        // Store the language preference in cookie for persistence
                                        if let Some(_window) = web_sys::window() {
                                            let cookie_script = format!(
                                                "document.cookie = 'preferred_language={}; path=/; max-age={}; SameSite=Lax'",
                                                lang_code_clone,
                                                365 * 24 * 60 * 60 // 1 year in seconds
                                            );
                                            let _ = js_sys::eval(&cookie_script);
                                        }
                                    }

                                    // Get current path and navigate to localized version
                                    #[cfg(target_arch = "wasm32")]
                                    {
                                        if let Some(window) = web_sys::window() {
                                            if let Ok(pathname) = window.location().pathname() {
                                                // Debug logging in development builds only
                                                #[cfg(debug_assertions)]
                                                {
                                                    web_sys::console::log_1(&format!("🌍 Language Selector: Current path: '{}'", pathname).into());
                                                    web_sys::console::log_1(&format!("🌍 Language Selector: Target language: '{}'", lang_code_clone).into());
                                                }

                                                // Calculate new localized path
                                                let new_path = rustelo_core_lib::routing::utils::get_localized_route(&pathname, &lang_code_clone);

                                                #[cfg(debug_assertions)]
                                                web_sys::console::log_1(&format!("🌍 Language Selector: New path: '{}' -> '{}'", pathname, new_path).into());

                                                if let Some(set_path) = _set_path_signal {
                                                    #[cfg(debug_assertions)]
                                                    web_sys::console::log_1(&format!("🌍 Language Selector: Using anchor_navigate to: '{}'", new_path).into());

                                                    // Use anchor_navigate to properly update URL and apply transitions
                                                    rustelo_core_lib::utils::nav::anchor_navigate(set_path, &new_path);

                                                } else {
                                                    #[cfg(debug_assertions)]
                                                    web_sys::console::log_1(&format!("🌍 Language Selector: No set_path signal, using direct navigation to: '{}'", new_path).into());

                                                    // Fallback to direct navigation
                                                    let _ = window.location().set_pathname(&new_path);
                                                }
                                            }
                                        }
                                    }
                                    #[cfg(not(target_arch = "wasm32"))]
                                    {
                                        tracing::debug!("SSR: would navigate to language {}", lang_code_clone);
                                        if let Some(set_path) = _set_path_signal {
                                            let the_current_path = _current_path_clone.clone().unwrap_or_default();
                                            set_path.set(the_current_path);
                                        }
                                    }
                                }
                            }
                        }
                    >
                        <span class="mx-2 text-xs">
                            {move || {
                                let is_active = {
                                    #[cfg(target_arch = "wasm32")]
                                    { ctx_check.current.get() == lc_check }
                                    #[cfg(not(target_arch = "wasm32"))]
                                    { ctx_check.current.get_untracked() == lc_check }
                                };
                                if is_active { "✓ " } else { "" }
                            }}
                        </span>
                        <span>{display_name}</span>
                    </button>
                }
        })
        .collect();

    // Vec<View> is not Clone in Leptos 0.8 — render it directly.
    // All reactivity lives inside each button via reactive closures.

    #[cfg(target_arch = "wasm32")]
    let aria_expanded = move || _is_open.get();
    #[cfg(not(target_arch = "wasm32"))]
    let aria_expanded = false;

    // Interactive dropdown structure
    view! {
        <div id="lang-selector" class={format!("language-selector relative {}", selector_class)}>
            // Button with SVG icon only
            <button
                class="btn btn-ghost btn-sm btn-icon ds-text hover:ds-text-secondary flex items-center justify-center text-sm"
                aria-label={aria_label.clone()}
                aria-haspopup="true"
                aria-expanded={aria_expanded}
                on:click=move |_| {
                    #[cfg(target_arch = "wasm32")]
                    web_sys::console::log_1(&"🌍 Language Selector: Main button clicked, toggling dropdown".into());
                    set_is_open.update(|open| *open = !*open)
                }
            >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129"></path>
                </svg>
            </button>

            // Dropdown menu - shows when clicked
            <div
                class=move || {
                    let visibility = {
                        #[cfg(target_arch = "wasm32")]
                        { _is_open.get() }
                        #[cfg(not(target_arch = "wasm32"))]
                        { false } // SSR default: dropdown closed
                    };
                    format!(
                        "absolute right-0 mt-1 w-48 border border-gray-500 rounded-md shadow-lg z-10 transition-all duration-200 {}",
                        if visibility { "opacity-100 visible" } else { "opacity-0 invisible" }
                    )
                }
                role="menu"
                aria-label="Language selection"
            >
                <div class="py-1">
                    {language_options}
                </div>
            </div>
        </div>
    }
}

// LanguageToggle removed - only LanguageSelector dropdown is used
