//! Client-side navigation menu component
//!
//! Reactive implementation of the navigation menu with SPA navigation capabilities.

use leptos::prelude::*;
// Fix Leptos macro conflicts with our 'core' crate
use std::{default::Default, marker::PhantomData};
use ::rustelo_core_lib::load_reactive_menu_for_language;

// Import unified components that work in both client and SSR contexts
use crate::logo::Logo;
use crate::theme::DarkModeToggle;  // This should use the unified version
use crate::navigation::LanguageSelector;

/// Client-side reactive navigation menu component
#[component]
pub fn NavMenuClient(_set_path: WriteSignal<String>, _path: ReadSignal<String>) -> impl IntoView {
    let i18n = use_i18n();

    // Create reactive memo using pattern-based key discovery
    let nav_content = Memo::new(move |_| i18n.clone().build_reactive_page_content_patterns(&["nav-"]));

    // Create reactive memo for current language using i18n context
    let current_lang_reactive = i18n.lang_code_reactive();
    let current_lang = move || current_lang_reactive.get();

    // Create reactive memo for menu items
    let menu_items = move || {
        let lang = current_lang();
        match load_reactive_menu_for_language(&lang) {
            Ok(items) => items,
            Err(_) => vec![], // Fallback to empty menu on error
        }
    };

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

    // SPA-aware menu item renderer
    move || {
        let items = menu_items();
        let items_mobile = items.clone();
        let mobile_open = false; // Simplified for now

        // Fetch content inside the closure to avoid ownership issues
        let nav_menu_aria_controls = get_lang_content("nav-menu-aria-controls");
        let nav_menu_aria_label = get_lang_content("nav-menu-aria-label");

        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">
                            // Logo (theme-aware and hydration-safe)
                            <div class="flex-shrink-0">
                                <Logo size="normal".to_string() />
                            </div>

                            // Desktop menu
                            <div class="hidden ds-text lg:block md:ml-6 md:flex md:space-x-8">
                                {items.into_iter().map(|item| {
                                    {menu_item_view(item)}
                                }).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() />
                                    <LanguageSelector
                                        class="".to_string()
                                        current_language=current_lang()
                                        navigation_signals=None
                                    />
                                </div>
                            </div>

                            // Mobile menu button (simplified)
                            <div class="md:hidden flex items-center">
                                <button
                                    aria-controls={nav_menu_aria_controls}
                                    class="lg:hidden grid place-items-center ds-border align-middle select-none font-sans font-medium text-center transition-all duration-300 ease-in disabled:opacity-50 disabled:shadow-none disabled:pointer-events-none ds-caption min-w-[34px] min-h-[34px] ds-rounded-md ds-bg ds-text hover:ds-bg hover:ds-border shadow-none hover:shadow-none ml-1"
                                    aria-expanded={if mobile_open { "true" } else { "false" }}
                                    aria-label={nav_menu_aria_label}
                                >
                                    <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 (simplified)
                    <div
                        class="md:hidden border-t border-gray-200 bg-white"
                        style={if mobile_open { "display: block;" } else { "display: none;" }}
                        id="navbar-collapse"
                    >
                        <div class="px-2 pt-2 pb-3 space-y-1">
                            // Mobile menu items
                            <div class="text-gray-500 text-sm p-3">
                                {items_mobile.into_iter().map(|item| {
                                    {menu_item_view(item)}
                                }).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">{get_lang_content("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() />
                                            <LanguageSelector
                                                class="text-xs".to_string()
                                                current_language=current_lang()
                                                navigation_signals=None
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </nav>
        }
    }
}

/// Helper function to render menu items with SPA navigation
// TODO: Define MenuItem type locally for now
// Using rustelo_core_lib::MenuItem instead of local definition

fn menu_item_view(item: rustelo_core_lib::MenuItem) -> impl IntoView {
    // TODO: Implement SPA-aware menu item rendering
    // This would use the navigation context to handle clicks
    let label_text = item.label.translations.get("en").unwrap_or(&item.route).clone();
    view! {
        <a href={item.route} class="nav-link">
            {label_text}
        </a>
    }
}

// TODO: Import use_i18n from the actual client crate location
// For now we'll use a placeholder that compiles
fn use_i18n() -> DummyI18n { DummyI18n }

#[derive(Clone, Copy)]
struct DummyI18n;
impl DummyI18n {
    fn build_reactive_page_content_patterns(&self, _patterns: &[&str]) -> std::collections::HashMap<String, String> {
        std::collections::HashMap::new()
    }
    fn lang_code_reactive(&self) -> leptos::prelude::ReadSignal<String> {
        let (lang, _) = signal("en".to_string());
        lang
    }
}
