//! Unified navigation menu with actual implementation
//!
//! This module contains the main navigation menu implementation that works
//! in both client-side and server-side contexts.

use crate::navigation::brand_header::BrandHeader;
use crate::theme::DarkModeToggle;
use leptos::prelude::*;

use ::rustelo_core_lib::state::use_current_language;

/// Main NavMenu component that delegates to appropriate wrapper
#[component]
pub fn NavMenu(
    /// Path setter for SPA navigation (client-side only)
    #[prop(optional)]
    _set_path: Option<WriteSignal<String>>,
    /// Current path signal (client-side only)
    #[prop(optional)]
    _path: Option<ReadSignal<String>>,
    /// Language for SSR context
    #[prop(default = rustelo_core_lib::config::get_default_language().to_string())]
    language: String,
) -> impl IntoView {
    // Use target_arch to determine execution context
    // Server-side (not WASM): delegate to SSR implementation
    #[cfg(not(target_arch = "wasm32"))]
    {
        tracing::info!("🔧 NavMenu: Server-side context, using SSR branch");
        view! { <crate::navigation::navmenu::ssr::NavMenuSSR language=language /> }.into_any()
    }

    // Client-side (WASM): delegate to client implementation if signals provided
    #[cfg(target_arch = "wasm32")]
    {
        web_sys::console::log_1(
            &format!(
                "🔧 NavMenu: WASM context - signals available: {}",
                _set_path.is_some() && _path.is_some()
            )
            .into(),
        );

        // Client context: use client wrapper
        if let (Some(set_path), Some(path)) = (_set_path, _path) {
            web_sys::console::log_1(
                &"🔧 NavMenu: Delegating to NavMenuClient with navigation signals".into(),
            );
            view! { <crate::navigation::navmenu::client::NavMenuClient set_path=set_path path=path /> }.into_any()
        } else {
            // Fallback if navigation signals not provided - render unified without signals
            web_sys::console::log_1(
                &"⚠️ NavMenu: Navigation signals not provided, showing empty menu for hydration"
                    .into(),
            );
            view! { <UnifiedNavMenu language=language /> }.into_any()
        }
    }
}

/// Unified navigation menu component with the actual implementation
#[component]
pub fn UnifiedNavMenu(
    /// Navigation signals for client-side routing (optional)
    #[prop(optional)]
    navigation_signals: Option<(ReadSignal<String>, WriteSignal<String>)>,
    /// Language for menu items
    #[prop(default = use_current_language().with(|lang| lang.clone()))]
    language: String,
    /// Menu items (if pre-loaded)
    #[prop(optional)]
    menu_items: Option<Vec<rustelo_core_lib::MenuItem>>,
    /// i18n content map
    #[prop(optional)]
    content: Option<std::collections::HashMap<String, String>>,
) -> impl IntoView {
    // Get current language - use static language prop only
    let current_language = language.clone();

    // Get menu items - use prop if provided (from server SSR)
    // During hydration, context is NOT available, so we use empty fallback
    // After hydration, effects can populate menus from context
    let items = menu_items.unwrap_or_default();

    // Setup i18n content from provided prop or load from FTL registry
    let nav_content = content.unwrap_or_else(|| {
        let mut content = std::collections::HashMap::new();

        // Try to load from registered FTL resources
        // FTL files are registered with language prefix: {language}_{filename}
        let ftl_key = format!("{}_{}", current_language, "navigation");
        if let Some(ftl_content) = ::rustelo_core_lib::registration::get_ftl(&ftl_key) {
            // Extract navigation keys from FTL content
            // FTL format: key = value
            for line in ftl_content.lines() {
                let line = line.trim();
                // Skip comments and empty lines
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                // Parse key = value format
                if let Some(eq_pos) = line.find('=') {
                    let key = line[..eq_pos].trim();
                    let value = line[eq_pos + 1..].trim();

                    // Include navigation and language selector keys
                    if key.starts_with("nav-") || key.starts_with("lang-") {
                        content.insert(key.to_string(), value.to_string());
                    }
                }
            }
        }

        // Fallback defaults if FTL not found or keys missing
        content
            .entry("nav-menu-aria-controls".to_string())
            .or_insert_with(|| "navbar-collapse".to_string());
        content
            .entry("nav-menu-aria-label".to_string())
            .or_insert_with(|| "Open navigation menu".to_string());
        content
            .entry("nav-mobile-controls".to_string())
            .or_insert_with(|| "Controls".to_string());
        content
            .entry("lang-selector-button".to_string())
            .or_insert_with(|| "Language Selector".to_string());
        content
            .entry("lang-en-display".to_string())
            .or_insert_with(|| "English".to_string());
        content
            .entry("lang-es-display".to_string())
            .or_insert_with(|| "Español".to_string());

        content
    });

    // Simple content lookup function
    let get_content = |key: &str| -> String {
        nav_content.get(key).cloned().unwrap_or_else(|| {
            tracing::warn!("i18n key not found: '{}'", key);
            String::new()
        })
    };

    // Mobile menu state - create signal with platform-specific initialization
    // On WASM/client: create reactive signal for interactivity
    // On SSR/server: create dummy signals that won't be used
    #[allow(unused_variables)]
    let (mobile_open, set_mobile_open) = {
        #[cfg(target_arch = "wasm32")]
        {
            signal(false)
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            // For SSR, create a dummy signal that will be optimized out
            // The signal is created but the view code won't actually use it
            // This ensures consistent compilation across both targets
            signal(false)
        }
    };

    // Clone current_language for use in menu rendering closures
    let current_language_clone = current_language.clone();

    // These are only used on WASM/client, but we need to get them for consistency
    #[allow(unused_variables)]
    let nav_menu_aria_controls = get_content("nav-menu-aria-controls");
    #[allow(unused_variables)]
    let nav_menu_aria_label = get_content("nav-menu-aria-label");
    #[allow(unused_variables)]
    let nav_mobile_controls = get_content("nav-mobile-controls");

    view! {
        <nav class="border-b border-gray-200 shadow-sm">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between h-16">
                    <div class="flex items-center">
                        // Brand header - consistent with footer
                        <div class="flex-shrink-0">
                            <BrandHeader
                                language={current_language.clone()}
                                class="h-8 w-auto text-xl font-bold".to_string()
                                is_footer=false
                            />
                        </div>

                        // Desktop menu
                        <div class="hidden lg:block md:ml-6 md:flex md:space-x-8">
                            {items.clone().into_iter().map(|item| {
                                let href = item.route.clone();
                                let is_external = item.is_external.unwrap_or(false);
                                let label_text = item
                                    .label
                                    .get_for_language(&current_language_clone)
                                    .cloned()
                                    .unwrap_or_else(|| "Menu Item".to_string());

                                view! {
                                    <a
                                        href={href.clone()}
                                        class="ds-text hover:ds-text-secondary px-3 py-2 rounded-md text-sm font-medium transition-colors no-underline"
                                        target={if is_external { "_blank" } else { "_self" }}
                                        rel={if is_external { "noopener noreferrer" } else { "" }}
                                        on:click={
                                            let href = href.clone();
                                            move |ev| {
                                                #[cfg(target_arch = "wasm32")]
                                                web_sys::console::log_1(&format!("🔧 NavMenu: Link clicked! href='{}', is_external={}, has_nav_signals={}", href, is_external, navigation_signals.is_some()).into());

                                                // Only use SPA routing for internal links
                                                if !is_external {
                                                    // Only handle click if navigation_signals are available (client-side)
                                                    if let Some((_, set_path)) = navigation_signals {
                                                        #[cfg(target_arch = "wasm32")]
                                                        web_sys::console::log_1(&format!("🔧 NavMenu: Click intercepted for href: '{}', preventing default and using SPA navigation", href).into());

                                                        ev.prevent_default();

                                                        // Use anchor_navigate to properly update URL and apply transitions
                                                        #[cfg(target_arch = "wasm32")]
                                                        {
                                                            rustelo_core_lib::utils::nav::anchor_navigate(set_path, &href);
                                                        }
                                                        #[cfg(not(target_arch = "wasm32"))]
                                                        {
                                                            set_path.set(href.clone());
                                                        }
                                                    } else {
                                                        #[cfg(target_arch = "wasm32")]
                                                        web_sys::console::log_1(&format!("⚠️ NavMenu: No navigation signals available for href: '{}', allowing default browser navigation", href).into());
                                                    }
                                                    // Otherwise, let the normal link behavior happen (SSR)
                                                } else {
                                                    #[cfg(target_arch = "wasm32")]
                                                    web_sys::console::log_1(&format!("🌐 NavMenu: External link detected for href: '{}', allowing default browser navigation", href).into());
                                                }
                                                // External links: let the browser handle navigation normally
                                            }
                                        }
                                    >
                                        {label_text}
                                    </a>
                                }
                            }).collect::<Vec<_>>()}
                        </div>
                    </div>

                    // Right side: Controls and Mobile menu button
                    <div class="flex items-center space-x-2">
                        // Desktop controls (hidden on mobile)
                        <div class="hidden md:flex md:items-center md:space-x-2">
                            <div class="flex items-center space-x-2">
                                <DarkModeToggle class="btn btn-ghost btn-sm".to_string() />
                                {
                                    if let Some(nav_signals) = navigation_signals {
                                        view! {
                                            <crate::navigation::language_selector::unified::LanguageSelector
                                                current_language={Some(current_language.clone())}
                                                content=nav_content.clone()
                                                navigation_signals=nav_signals
                                            />
                                        }.into_any()
                                    } else {
                                        view! {
                                            <crate::navigation::language_selector::unified::LanguageSelector
                                                current_language={Some(current_language.clone())}
                                                content=nav_content.clone()
                                            />
                                        }.into_any()
                                    }
                                }
                            </div>
                        </div>

                        // Mobile menu button - rendered on both SSR and client for hydration consistency
                        // On SSR, this is just static HTML that won't be interactive
                        // On client (WASM), this becomes interactive with proper click handlers
                        <div class="md:hidden flex items-center">
                            <button
                                aria-controls={nav_menu_aria_controls.clone()}
                                class="ds-mobile-menu-btn"
                                aria-expanded="false"
                                aria-label={nav_menu_aria_label.clone()}
                                on:click=move |_| {
                                    set_mobile_open.set(!mobile_open.get_untracked())
                                }
                            >
                                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>

                // Mobile menu - rendered on both SSR and client for hydration consistency
                // On SSR: just renders as static HTML, hidden via CSS
                // On client (WASM): becomes reactive with style:display controlled by signal
                <div
                    class="md:hidden border-t border-gray-200 bg-white"
                    id="navbar-collapse"
                    // style:display=move || {
                    //     if mobile_open.get() { "block" } else { "none" }
                    // }
                >
                    <div class="px-2 pt-2 pb-3 space-y-1">
                        // Mobile menu items
                        <div class="text-gray-500 text-sm p-3">
                            {items.clone().into_iter().map(|item| {
                                let href = item.route.clone();
                                let is_external = item.is_external.unwrap_or(false);
                                let label_text = item
                                    .label
                                    .get_for_language(&current_language_clone)
                                    .cloned()
                                    .unwrap_or_else(|| "Menu Item".to_string());

                                view! {
                                    <a
                                        href={href.clone()}
                                        class="ds-text hover:ds-text-secondary px-3 py-2 rounded-md text-sm font-medium transition-colors no-underline"
                                        target={if is_external { "_blank" } else { "_self" }}
                                        rel={if is_external { "noopener noreferrer" } else { "" }}
                                        on:click={
                                            let href = href.clone();
                                            move |ev| {
                                                #[cfg(target_arch = "wasm32")]
                                                web_sys::console::log_1(&format!("🔧 NavMenu: Link clicked! href='{}', is_external={}, has_nav_signals={}", href, is_external, navigation_signals.is_some()).into());

                                                // Only use SPA routing for internal links
                                                if !is_external {
                                                    // Only handle click if navigation_signals are available (client-side)
                                                    if let Some((_, set_path)) = navigation_signals {
                                                        #[cfg(target_arch = "wasm32")]
                                                        web_sys::console::log_1(&format!("🔧 NavMenu: Click intercepted for href: '{}', preventing default and using SPA navigation", href).into());

                                                        ev.prevent_default();

                                                        // Use anchor_navigate to properly update URL and apply transitions
                                                        #[cfg(target_arch = "wasm32")]
                                                        {
                                                            rustelo_core_lib::utils::nav::anchor_navigate(set_path, &href);
                                                        }
                                                        #[cfg(not(target_arch = "wasm32"))]
                                                        {
                                                            set_path.set(href.clone());
                                                        }
                                                    } else {
                                                        #[cfg(target_arch = "wasm32")]
                                                        web_sys::console::log_1(&format!("⚠️ NavMenu: No navigation signals available for href: '{}', allowing default browser navigation", href).into());
                                                    }
                                                    // Otherwise, let the normal link behavior happen (SSR)
                                                } else {
                                                    #[cfg(target_arch = "wasm32")]
                                                    web_sys::console::log_1(&format!("🌐 NavMenu: External link detected for href: '{}', allowing default browser navigation", href).into());
                                                }
                                                // External links: let the browser handle navigation normally
                                            }
                                        }
                                    >
                                        {label_text}
                                    </a>
                                }
                            }).collect::<Vec<_>>()}
                        </div>

                        // Mobile controls
                        <div class="px-3 py-2 border-t border-gray-200">
                            <div class="flex items-center justify-between">
                                <span class="text-sm text-gray-500">{nav_mobile_controls}</span>
                                <div class="flex items-center space-x-2">
                                    <div class="flex items-center space-x-2">
                                        <DarkModeToggle class="btn btn-ghost btn-sm".to_string() />
                                        {
                                            if let Some(nav_signals) = navigation_signals {
                                                view! {
                                                    <crate::navigation::language_selector::unified::LanguageSelector
                                                        current_language={Some(current_language.clone())}
                                                        content=nav_content.clone()
                                                        navigation_signals=nav_signals
                                                    />
                                                }.into_any()
                                            } else {
                                                view! {
                                                    <crate::navigation::language_selector::unified::LanguageSelector
                                                        current_language={Some(current_language)}
                                                        content=nav_content
                                                    />
                                                }.into_any()
                                            }
                                        }
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </nav>
    }
}
