//! Unified navigation menu — auth controls integrated inline after language
//! selector.
//!
//! Both desktop (avatar dropdown / sign-in button) and mobile (hamburger
//! submenu) auth surfaces live here.  `AuthControls` overlay in
//! `website_navmenu.rs` is removed.

use ::rustelo_core_lib::state::{use_current_language, AuthState};
use leptos::prelude::*;
use leptos::task::spawn_local;

#[cfg(target_arch = "wasm32")]
use crate::auth::server_add_bookmark;
use crate::auth::server_logout;

fn deny_path_matches(route: &str, deny_paths: &[String]) -> bool {
    deny_paths.iter().any(|pattern| {
        if let Some(prefix) = pattern.strip_suffix("/*") {
            route == prefix || route.starts_with(&format!("{}/", prefix))
        } else {
            route == pattern
        }
    })
}

fn avatar_initial(name: &Option<String>, email: &str) -> char {
    name.as_deref()
        .and_then(|n| n.chars().next())
        .or_else(|| email.chars().next())
        .unwrap_or('?')
        .to_uppercase()
        .next()
        .unwrap_or('?')
}

use crate::logo::unified::Logo;
use crate::theme::DarkModeToggle;

/// Main NavMenu component that delegates to `UnifiedNavMenu`
#[component]
pub fn NavMenu(
    #[prop(optional)] _set_path: Option<WriteSignal<String>>,
    #[prop(optional)] _path: Option<ReadSignal<String>>,
    #[prop(default = rustelo_core_lib::config::get_default_language().to_string())]
    #[allow(unused_variables)]
    language: String,
    #[prop(optional)]
    #[allow(unused_variables)]
    menu_items: Option<Vec<rustelo_core_lib::MenuItem>>,
    /// Optional login modal trigger — if `None`, sign-in navigates to `/login`.
    #[prop(default = None)]
    set_show_login: Option<WriteSignal<bool>>,
) -> impl IntoView {
    #[cfg(target_arch = "wasm32")]
    {
        match (_path, _set_path) {
            (Some(path), Some(set_path)) => view! {
                <UnifiedNavMenu
                    language=language
                    navigation_signals=(path, set_path)
                    menu_items=menu_items.unwrap_or_default()
                    set_show_login=set_show_login
                />
            }
            .into_any(),
            _ => view! {
                <UnifiedNavMenu
                    language=language
                    menu_items=menu_items.unwrap_or_default()
                    set_show_login=set_show_login
                />
            }
            .into_any(),
        }
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        view! {
            <UnifiedNavMenu
                language=language
                menu_items=menu_items.unwrap_or_default()
                set_show_login=set_show_login
            />
        }
        .into_any()
    }
}

/// Full navigation menu — avatar dropdown + sign-in button integrated after the
/// language selector.
#[component]
pub fn UnifiedNavMenu(
    #[prop(optional)] navigation_signals: Option<(ReadSignal<String>, WriteSignal<String>)>,
    #[prop(default = use_current_language().with(|lang| lang.clone()))] language: String,
    #[prop(optional, default = Default::default())] menu_items: Vec<rustelo_core_lib::MenuItem>,
    #[prop(optional)] content: Option<std::collections::HashMap<String, String>>,
    /// Optional login modal trigger — if `None`, sign-in navigates to `/login`.
    #[prop(default = None)]
    set_show_login: Option<WriteSignal<bool>>,
) -> impl IntoView {
    let current_language = language.clone();
    let lang_signal = use_current_language();

    let preloaded = if !menu_items.is_empty() {
        Some(menu_items)
    } else {
        None
    };

    let items_memo = Memo::new(move |_| {
        if let Some(ref items) = preloaded {
            return items.clone();
        }
        let lang = {
            #[cfg(target_arch = "wasm32")]
            {
                lang_signal.get()
            }
            #[cfg(not(target_arch = "wasm32"))]
            {
                lang_signal.get_untracked()
            }
        };
        match ::rustelo_core_lib::load_reactive_menu_for_language(&lang) {
            Ok(loaded) => loaded,
            Err(e) => {
                #[cfg(target_arch = "wasm32")]
                web_sys::console::warn_1(&format!("menu load failed: {e}").into());
                #[cfg(not(target_arch = "wasm32"))]
                tracing::warn!("menu load failed: {e}");
                Vec::new()
            }
        }
    });

    let nav_content = content.unwrap_or_else(|| {
        let mut map = std::collections::HashMap::new();
        let ftl_key = format!("{}_navigation", current_language);
        if let Some(ftl) = ::rustelo_core_lib::registration::get_ftl(&ftl_key) {
            for line in ftl.lines() {
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                if let Some(eq) = line.find('=') {
                    let k = line[..eq].trim();
                    let v = line[eq + 1..].trim();
                    if k.starts_with("nav-") || k.starts_with("lang-") {
                        map.insert(k.to_string(), v.to_string());
                    }
                }
            }
        }
        map.entry("nav-menu-aria-controls".into())
            .or_insert_with(|| "navbar-collapse".into());
        map.entry("nav-menu-aria-label".into())
            .or_insert_with(|| "Open navigation menu".into());
        map.entry("nav-mobile-controls".into())
            .or_insert_with(|| "Controls".into());
        map.entry("lang-selector-button".into())
            .or_insert_with(|| "Language Selector".into());
        map.entry("lang-en-display".into())
            .or_insert_with(|| "English".into());
        map.entry("lang-es-display".into())
            .or_insert_with(|| "Español".into());
        map
    });

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

    #[allow(unused_variables)]
    let (mobile_open, set_mobile_open) = signal(false);

    // Close mobile menu when viewport grows to md breakpoint (≥768px).
    // Prevents the menu from staying open after the user drags the window wider.
    #[cfg(target_arch = "wasm32")]
    {
        use wasm_bindgen::closure::Closure;
        use wasm_bindgen::JsCast as _;
        let resize_closure = Closure::wrap(Box::new(move || {
            if let Some(w) = web_sys::window() {
                let width = w.inner_width().ok().and_then(|v| v.as_f64()).unwrap_or(0.0);
                if width >= 768.0 {
                    set_mobile_open.set(false);
                }
            }
        }) as Box<dyn Fn()>);
        if let Some(w) = web_sys::window() {
            let _ = w.add_event_listener_with_callback(
                "resize",
                resize_closure.as_ref().unchecked_ref(),
            );
        }
        // Listener lives for the entire app lifetime — intentional.
        resize_closure.forget();
    }
    #[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");

    // Three clones: consumed by is_authenticated, desktop closure, mobile closure.
    let auth_state = use_context::<AuthState>();
    let auth_for_desktop = auth_state.clone();
    let auth_for_mobile = auth_state.clone();
    let is_authenticated = Signal::derive(move || {
        auth_state
            .as_ref()
            .map(|a| {
                #[cfg(target_arch = "wasm32")]
                {
                    a.authenticated.get()
                }
                #[cfg(not(target_arch = "wasm32"))]
                {
                    a.authenticated.get_untracked()
                }
            })
            .unwrap_or(false)
    });

    let deny_paths_signal = use_context::<leptos::prelude::RwSignal<Vec<String>>>();

    let menu_items_clone = Signal::derive(move || {
        let authed = is_authenticated.get();
        let deny = deny_paths_signal.map(|s| s.get()).unwrap_or_default();
        let items = {
            #[cfg(target_arch = "wasm32")]
            {
                items_memo.get()
            }
            #[cfg(not(target_arch = "wasm32"))]
            {
                items_memo.get_untracked()
            }
        };
        items
            .into_iter()
            .filter(|i| authed || !deny_path_matches(&i.route, &deny))
            .collect::<Vec<_>>()
    });
    let mobile_items = Signal::derive(move || {
        let authed = is_authenticated.get();
        let deny = deny_paths_signal.map(|s| s.get()).unwrap_or_default();
        let items = {
            #[cfg(target_arch = "wasm32")]
            {
                items_memo.get()
            }
            #[cfg(not(target_arch = "wasm32"))]
            {
                items_memo.get_untracked()
            }
        };
        items
            .into_iter()
            .filter(|i| authed || !deny_path_matches(&i.route, &deny))
            .collect::<Vec<_>>()
    });

    let lang_selector_content = nav_content.clone();

    let logo_config = use_context::<::rustelo_core_lib::defs::LogoConfig>().unwrap_or_default();
    let logo_home_url = ::rustelo_core_lib::localize_url("/", &current_language);
    let logo_nav_config = logo_config.clone();

    // Bookmark saved state — flips to true after server_add_bookmark succeeds,
    // resets on navigation.
    let bookmark_saved: RwSignal<bool> = RwSignal::new(false);
    let mobile_bookmark_saved: RwSignal<bool> = RwSignal::new(false);
    #[cfg(target_arch = "wasm32")]
    Effect::new(move |_| {
        if let Some((path_sig, _)) = navigation_signals {
            let _ = path_sig.get(); // track path changes
            bookmark_saved.set(false);
            mobile_bookmark_saved.set(false);
        }
    });

    view! {
        <nav
            class="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm"
            hx-boost="true"
            hx-target="body"
            hx-swap="outerHTML"
        >
            <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_nav_config.show_in_nav.then(move || {
                            let nav_sigs = navigation_signals;
                            let dest = logo_home_url.clone();
                            view! {
                                <a
                                    href={dest.clone()}
                                    class="flex-shrink-0 mr-4"
                                    on:click=move |ev| {
                                        if let Some((_, sp)) = nav_sigs {
                                            ev.prevent_default();
                                            #[cfg(target_arch = "wasm32")]
                                            ::rustelo_core_lib::utils::nav::anchor_navigate(sp, &dest);
                                            #[cfg(not(target_arch = "wasm32"))]
                                            sp.set(dest.clone());
                                        }
                                    }
                                >
                                    <Logo config=logo_nav_config class="h-8 w-auto".to_string() />
                                </a>
                            }
                        })}
                        <div class="hidden lg:block md:ml-6 md:flex md:space-x-8">
                            {move || menu_items_clone.get().into_iter().map(|item| {
                                let is_ext = item.is_external.unwrap_or(false);
                                let label = item.label.clone();
                                let dest = item.route.clone();
                                let dest_click = dest.clone();
                                view! {
                                    <a
                                        href=dest
                                        class="text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white px-3 py-2 rounded-md text-sm font-medium transition-colors no-underline"
                                        target={if is_ext { "_blank" } else { "_self" }}
                                        rel={if is_ext { "noopener noreferrer" } else { "" }}
                                        on:click=move |ev| {
                                            if !is_ext {
                                                if let Some((_, sp)) = navigation_signals {
                                                    ev.prevent_default();
                                                    #[cfg(target_arch = "wasm32")]
                                                    rustelo_core_lib::utils::nav::anchor_navigate(sp, &dest_click);
                                                    #[cfg(not(target_arch = "wasm32"))]
                                                    sp.set(dest_click.clone());
                                                }
                                            }
                                        }
                                    >
                                        {move || label.get_for_language(&{
                                            #[cfg(target_arch = "wasm32")]
                                            { lang_signal.get() }
                                            #[cfg(not(target_arch = "wasm32"))]
                                            { lang_signal.get_untracked() }
                                        }).cloned().unwrap_or_else(|| "Menu Item".to_string())}
                                    </a>
                                }
                            }).collect::<Vec<_>>()}
                        </div>
                    </div>

                    // Right side controls
                    <div class="flex items-center space-x-2">
                        // Desktop: dark mode + language selector + auth
                        <div class="hidden md:flex md:items-center md:space-x-2">
                            <div class="flex items-center space-x-2">
                                // Bookmark icon — authenticated users only
                                {move || {
                                    let authed = {
                                        #[cfg(target_arch = "wasm32")]
                                        { is_authenticated.get() }
                                        #[cfg(not(target_arch = "wasm32"))]
                                        { is_authenticated.get_untracked() }
                                    };
                                    if authed {
                                        let saved = {
                                            #[cfg(target_arch = "wasm32")]
                                            { bookmark_saved.get() }
                                            #[cfg(not(target_arch = "wasm32"))]
                                            { bookmark_saved.get_untracked() }
                                        };
                                        let fill = if saved { "currentColor" } else { "none" };
                                        view! {
                                            <button
                                                class="ds-btn-ghost-sm"
                                                aria-label="Bookmark this page"
                                                on:click=move |_| {
                                                    #[cfg(target_arch = "wasm32")]
                                                    {
                                                        let path = navigation_signals
                                                            .map(|(p, _)| p.get_untracked())
                                                            .or_else(|| {
                                                                web_sys::window()
                                                                    .and_then(|w| w.location().pathname().ok())
                                                            })
                                                            .unwrap_or_else(|| "/".to_string());
                                                        let url = path.clone();
                                                        spawn_local(async move {
                                                            let _ = server_add_bookmark(
                                                                "page".to_string(),
                                                                url.clone(),
                                                                None,
                                                                Some(url),
                                                            )
                                                            .await;
                                                            bookmark_saved.set(true);
                                                        });
                                                    }
                                                }
                                            >
                                                <svg
                                                    class="w-5 h-5"
                                                    viewBox="0 0 24 24"
                                                    fill=fill
                                                    stroke="currentColor"
                                                    stroke-width="2"
                                                    stroke-linecap="round"
                                                    stroke-linejoin="round"
                                                >
                                                    <path d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
                                                </svg>
                                            </button>
                                        }.into_any()
                                    } else {
                                        ().into_any()
                                    }
                                }}
                                <DarkModeToggle class="ds-btn-ghost-sm".to_string() />
                                <crate::navigation::language_selector::unified::LanguageSelector
                                    current_language={Some(current_language.clone())}
                                    content=lang_selector_content.clone()
                                    navigation_signals=navigation_signals
                                />
                                // Auth: avatar dropdown or sign-in button
                                {move || {
                                    let authed = {
                                        #[cfg(target_arch = "wasm32")]
                                        { is_authenticated.get() }
                                        #[cfg(not(target_arch = "wasm32"))]
                                        { is_authenticated.get_untracked() }
                                    };
                                    let current_lang = {
                                        #[cfg(target_arch = "wasm32")]
                                        { lang_signal.get() }
                                        #[cfg(not(target_arch = "wasm32"))]
                                        { lang_signal.get_untracked() }
                                    };
                                    let i18n = ::rustelo_core_lib::i18n::UnifiedI18n::new(&current_lang, "/");
                                    let sign_in_text = i18n.t("nav-sign-in");
                                    let sign_out_text = i18n.t("nav-sign-out");
                                    let dashboard_text = i18n.t("nav-dashboard");
                                    let user_url = ::rustelo_core_lib::localize_url("/user", &current_lang);
                                    let login_url = ::rustelo_core_lib::localize_url("/login", &current_lang);
                                    if authed {
                                        let (user_name, user_email, avatar_url) = auth_for_desktop
                                            .as_ref()
                                            .and_then(|a| {
                                                #[cfg(target_arch = "wasm32")]
                                                let u = a.user.get();
                                                #[cfg(not(target_arch = "wasm32"))]
                                                let u = a.user.get_untracked();
                                                u
                                            })
                                            .map(|u| (u.name.clone(), u.email.clone(), u.avatar_url.clone()))
                                            .unwrap_or_default();

                                        let initial = avatar_initial(&user_name, &user_email);
                                        let display_name = user_name
                                            .filter(|n| !n.is_empty())
                                            .unwrap_or_else(|| user_email.clone());

                                        let auth_for_logout = auth_for_desktop.clone();
                                        let set_path_logout = navigation_signals.map(|(_, sp)| sp);
                                        let on_logout = move |_| {
                                            #[cfg(target_arch = "wasm32")]
                                            {
                                                if let Some(a) = &auth_for_logout {
                                                    let name = a.user.get_untracked()
                                                        .as_ref()
                                                        .and_then(|u| {
                                                            let n = u.name.clone().unwrap_or_default();
                                                            if n.is_empty() { None } else { Some(n) }
                                                        })
                                                        .unwrap_or_default();
                                                    if let Some(storage) = web_sys::window()
                                                        .and_then(|w| w.session_storage().ok().flatten())
                                                    {
                                                        let _ = storage.set_item("goodbye_name", &name);
                                                    }
                                                }
                                            }
                                            if let Some(a) = &auth_for_logout {
                                                a.clear_auth();
                                            }
                                            spawn_local(async move {
                                                let _ = server_logout().await;
                                                if let Some(sp) = set_path_logout {
                                                    sp.set("/signout".to_string());
                                                }
                                            });
                                        };

                                        let nav_user_url = user_url.clone();
                                        let nav_user_url_click = nav_user_url.clone();
                                        let sp_dashboard = navigation_signals.map(|(_, sp)| sp);
                                        let sign_out = sign_out_text.clone();
                                        let dashboard = dashboard_text.clone();

                                        view! {
                                            <div class="dropdown dropdown-end">
                                                <div
                                                    tabindex="0"
                                                    role="button"
                                                    class="btn btn-ghost btn-circle"
                                                    aria-label=display_name.clone()
                                                >
                                                    {if let Some(url) = avatar_url.filter(|u| !u.is_empty()) {
                                                        view! {
                                                            <img src=url alt=display_name.clone() class="w-9 h-9 object-cover rounded-full" />
                                                        }.into_any()
                                                    } else {
                                                        view! {
                                                            <div class="bg-slate-700 dark:bg-slate-400 text-white dark:text-slate-900 rounded-full w-9 h-9 flex items-center justify-center text-sm font-bold select-none">
                                                                {initial.to_string()}
                                                            </div>
                                                        }.into_any()
                                                    }}
                                                </div>
                                                <ul
                                                    tabindex="0"
                                                    class="menu menu-sm dropdown-content mt-3 z-50 p-2 shadow-lg bg-base-100 rounded-box w-52 border border-base-300"
                                                >
                                                    <li class="menu-title px-2 py-1">
                                                        <span class="text-xs font-semibold text-base-content truncate block">
                                                            {display_name}
                                                        </span>
                                                    </li>
                                                    <div class="divider my-0" />
                                                    <li>
                                                        <a
                                                            href=nav_user_url.clone()
                                                            class="flex items-center gap-2"
                                                            on:click=move |ev| {
                                                                if let Some(sp) = sp_dashboard {
                                                                    ev.prevent_default();
                                                                    #[cfg(target_arch = "wasm32")]
                                                                    rustelo_core_lib::utils::nav::anchor_navigate(sp, &nav_user_url_click);
                                                                    #[cfg(not(target_arch = "wasm32"))]
                                                                    sp.set(nav_user_url_click.clone());
                                                                }
                                                            }
                                                        >
                                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                                            </svg>
                                                            {dashboard}
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <button
                                                            class="flex items-center gap-2 text-error w-full text-left"
                                                            on:click=on_logout
                                                        >
                                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                                                            </svg>
                                                            {sign_out}
                                                        </button>
                                                    </li>
                                                </ul>
                                            </div>
                                        }.into_any()
                                    } else {
                                        let sign_in = sign_in_text.clone();
                                        let _login = login_url.clone();
                                        view! {
                                            <button
                                                class="btn btn-ghost btn-sm rounded-full text-base-content text-[15px]"
                                                on:click=move |_| {
                                                    if let Some(setter) = set_show_login {
                                                        setter.set(true);
                                                    } else {
                                                        #[cfg(target_arch = "wasm32")]
                                                        if let Some(w) = web_sys::window() {
                                                            let _ = w.location().set_href(&_login);
                                                        }
                                                    }
                                                }
                                            >
                                                {sign_in}
                                            </button>
                                        }.into_any()
                                    }
                                }}
                            </div>
                        </div>

                        // Mobile hamburger button
                        <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 dropdown
                <div
                    class="md:hidden border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800"
                    id="navbar-collapse"
                    style:display=move || {
                        #[cfg(target_arch = "wasm32")]
                        { if mobile_open.get() { "block" } else { "none" } }
                        #[cfg(not(target_arch = "wasm32"))]
                        { "none" }
                    }
                >
                    <div class="px-2 pt-2 pb-3 space-y-1">
                        {move || mobile_items.get().into_iter().map(|item| {
                            let is_ext = item.is_external.unwrap_or(false);
                            let label = item.label.clone();
                            let dest = item.route.clone();
                            let dest_click = dest.clone();
                            view! {
                                <a
                                    href=dest
                                    class="block text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white px-3 py-2 rounded-md text-sm font-medium transition-colors no-underline"
                                    target={if is_ext { "_blank" } else { "_self" }}
                                    rel={if is_ext { "noopener noreferrer" } else { "" }}
                                    on:click=move |ev| {
                                        // Always close the mobile menu on any link tap.
                                        set_mobile_open.set(false);
                                        if !is_ext {
                                            if let Some((_, sp)) = navigation_signals {
                                                ev.prevent_default();
                                                #[cfg(target_arch = "wasm32")]
                                                rustelo_core_lib::utils::nav::anchor_navigate(sp, &dest_click);
                                                #[cfg(not(target_arch = "wasm32"))]
                                                sp.set(dest_click.clone());
                                            }
                                        }
                                    }
                                >
                                    {move || label.get_for_language(&{
                                        #[cfg(target_arch = "wasm32")]
                                        { lang_signal.get() }
                                        #[cfg(not(target_arch = "wasm32"))]
                                        { lang_signal.get_untracked() }
                                    }).cloned().unwrap_or_else(|| "Menu Item".to_string())}
                                </a>
                            }
                        }).collect::<Vec<_>>()}

                        // Mobile controls
                        <div class="px-3 py-2 border-t border-gray-200 dark:border-gray-700">
                            <div class="flex items-center justify-between">
                                <span class="text-sm text-gray-500 dark:text-gray-400">{nav_mobile_controls}</span>
                                <div class="flex items-center space-x-2">
                                    // Bookmark icon (mobile) — authenticated users only
                                    {move || {
                                        let authed = {
                                            #[cfg(target_arch = "wasm32")]
                                            { is_authenticated.get() }
                                            #[cfg(not(target_arch = "wasm32"))]
                                            { is_authenticated.get_untracked() }
                                        };
                                        if authed {
                                            let saved = {
                                                #[cfg(target_arch = "wasm32")]
                                                { mobile_bookmark_saved.get() }
                                                #[cfg(not(target_arch = "wasm32"))]
                                                { mobile_bookmark_saved.get_untracked() }
                                            };
                                            let fill = if saved { "currentColor" } else { "none" };
                                            view! {
                                                <button
                                                    class="ds-btn-ghost-sm"
                                                    aria-label="Bookmark this page"
                                                    on:click=move |_| {
                                                        #[cfg(target_arch = "wasm32")]
                                                        {
                                                            let path = navigation_signals
                                                                .map(|(p, _)| p.get_untracked())
                                                                .or_else(|| {
                                                                    web_sys::window()
                                                                        .and_then(|w| w.location().pathname().ok())
                                                                })
                                                                .unwrap_or_else(|| "/".to_string());
                                                            let url = path.clone();
                                                            spawn_local(async move {
                                                                let _ = server_add_bookmark(
                                                                    "page".to_string(),
                                                                    url.clone(),
                                                                    None,
                                                                    Some(url),
                                                                )
                                                                .await;
                                                                mobile_bookmark_saved.set(true);
                                                            });
                                                        }
                                                    }
                                                >
                                                    <svg
                                                        class="w-5 h-5"
                                                        viewBox="0 0 24 24"
                                                        fill=fill
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                    >
                                                        <path d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
                                                    </svg>
                                                </button>
                                            }.into_any()
                                        } else {
                                            ().into_any()
                                        }
                                    }}
                                    <DarkModeToggle class="ds-btn-ghost-sm".to_string() />
                                    <crate::navigation::language_selector::unified::LanguageSelector
                                        current_language={Some(current_language.clone())}
                                        content=lang_selector_content
                                        navigation_signals=navigation_signals
                                    />
                                </div>
                            </div>
                        </div>

                        // Mobile auth
                        {move || {
                            let authed = {
                                #[cfg(target_arch = "wasm32")]
                                { is_authenticated.get() }
                                #[cfg(not(target_arch = "wasm32"))]
                                { is_authenticated.get_untracked() }
                            };
                            let current_lang = {
                                #[cfg(target_arch = "wasm32")]
                                { lang_signal.get() }
                                #[cfg(not(target_arch = "wasm32"))]
                                { lang_signal.get_untracked() }
                            };
                            let i18n = ::rustelo_core_lib::i18n::UnifiedI18n::new(&current_lang, "/");
                            let mobile_dashboard = i18n.t("nav-dashboard");
                            let mobile_sign_out = i18n.t("nav-sign-out");
                            let mobile_sign_in = i18n.t("nav-sign-in");
                            let mobile_user_url = ::rustelo_core_lib::localize_url("/user", &current_lang);
                            let mobile_login_url = ::rustelo_core_lib::localize_url("/login", &current_lang);
                            if authed {
                                let dashboard = mobile_dashboard.clone();
                                let sign_out = mobile_sign_out.clone();
                                let user = mobile_user_url.clone();
                                let auth_clone = auth_for_mobile.clone();
                                let sp_mobile = navigation_signals.map(|(_, sp)| sp);
                                let on_mobile_logout = move |_| {
                                    if let Some(a) = &auth_clone {
                                        a.clear_auth();
                                    }
                                    spawn_local(async move {
                                        let _ = server_logout().await;
                                        if let Some(sp) = sp_mobile {
                                            sp.set("/signout".to_string());
                                        }
                                    });
                                };
                                view! {
                                    <div class="px-3 py-2 border-t border-gray-200 dark:border-gray-700 space-y-1">
                                        <a
                                            href=user
                                            class="block text-sm text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white py-1 no-underline"
                                        >
                                            {dashboard}
                                        </a>
                                        <button
                                            class="block text-sm text-error w-full text-left py-1"
                                            on:click=on_mobile_logout
                                        >
                                            {sign_out}
                                        </button>
                                    </div>
                                }.into_any()
                            } else {
                                let sign_in = mobile_sign_in.clone();
                                let login = mobile_login_url.clone();
                                view! {
                                    <div class="px-3 py-2 border-t border-gray-200 dark:border-gray-700">
                                        <a
                                            href=login
                                            class="block text-sm text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white py-1 no-underline"
                                        >
                                            {sign_in}
                                        </a>
                                    </div>
                                }.into_any()
                            }
                        }}
                    </div>
                </div>
            </div>
        </nav>
    }
}
