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

use ::rustelo_core_lib::load_reactive_footer_for_language;
use leptos::prelude::*;

use crate::logo::unified::Logo;
#[cfg(target_arch = "wasm32")]
use crate::navigation::footer::client::FooterClient;
#[cfg(not(target_arch = "wasm32"))]
use crate::navigation::footer::ssr::FooterSSR;

/// Main Footer component that delegates to appropriate wrapper
#[component]
pub fn Footer(
    /// 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,
    /// Custom CSS class
    #[prop(optional)]
    class: Option<String>,
    /// Show social links
    #[prop(default = true)]
    show_social: bool,
    /// Show scroll to top button
    #[prop(default = true)]
    show_scroll_to_top: bool,
) -> impl IntoView {
    #[cfg(not(target_arch = "wasm32"))]
    {
        // SSR context: use SSR wrapper
        view! {
            <FooterSSR
                language=language
                class=class.unwrap_or_default()
                show_social=show_social
                show_scroll_to_top=show_scroll_to_top
            />
        }
        .into_any()
    }

    #[cfg(target_arch = "wasm32")]
    {
        if let (Some(set_path), Some(path)) = (_set_path, _path) {
            // Client context: use unified footer directly to avoid reactive stack overflow
            view! {
                <FooterClient
                    set_path=set_path
                    path=path
                    _language=language
                    class=class.unwrap_or_default()
                    show_social=show_social
                    show_scroll_to_top=show_scroll_to_top
                />
            }
            .into_any()
        } else {
            view! { <div class="nav-error">"Navigation unavailable"</div> }.into_any()
        }
    }
}

/// Unified footer component with the actual implementation
#[component]
pub fn UnifiedFooter(
    language: String,
    /// Custom CSS class
    #[prop(optional)]
    class: Option<String>,
    /// Show social links
    #[prop(default = true)]
    show_social: bool,
    /// Show scroll to top button
    #[prop(default = true)]
    show_scroll_to_top: bool,
    /// Footer content from i18n (optional)
    #[prop(optional)]
    lang_content: Option<std::collections::HashMap<String, String>>,
    /// Navigation signals for SPA routing (optional)
    #[prop(optional)]
    navigation_signals: Option<(ReadSignal<String>, WriteSignal<String>)>,
) -> impl IntoView {
    // Use static language from props - no reactive closure needed
    let current_lang = language.clone();

    // Load footer configuration from TOML files using static language
    let footer_config = match load_reactive_footer_for_language(&current_lang) {
        Ok(config) => config,
        Err(_) => {
            tracing::warn!(
                "Failed to load footer config for language: {}",
                current_lang
            );
            // Create fallback config
            rustelo_core_lib::defs::FooterConfig::new()
        }
    };

    // Setup footer content from loaded config and optional override
    let footer_content = lang_content.unwrap_or_default();

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

    // Scroll to top handler
    let scroll_to_top = move |_| {
        #[cfg(target_arch = "wasm32")]
        {
            // Try multiple scroll approaches
            if let Some(window) = web_sys::window() {
                // Method 1: Use window.scrollTo (most reliable)
                let _ = window.scroll_to_with_x_and_y(0.0, 0.0);

                // Method 2: Use document.documentElement.scrollTop (fallback)
                if let Some(document) = window.document() {
                    if let Some(element) = document.document_element() {
                        element.set_scroll_top(0);
                    }
                }
            }
        }
    };

    // Logo config provided by the app root via provide_context — no env vars, no
    // filesystem reads
    let logo_config = use_context::<::rustelo_core_lib::defs::LogoConfig>().unwrap_or_default();
    let home_url = ::rustelo_core_lib::localize_url("/", &current_lang);

    let base_class = "ds-bg-surface border-t border-gray-200 mt-auto";
    let footer_class = format!("{} {}", base_class, class.unwrap_or_default());

    let render_footer_link = |link: rustelo_core_lib::FooterLink| {
        let link_label = link.label.get_with_fallback(&current_lang, "en");
        let is_external = link.is_external.unwrap_or(false);
        let href = link.route.clone();

        view! {
            <li>
                <a href={href.clone()}
                    class="ds-text-secondary hover:ds-text transition-colors no-underline"
                    target={if is_external { "_blank" } else { "_self" }}
                    rel={if is_external { "noopener noreferrer" } else { "" }}
                    on:click=move |ev| {
                        ev.prevent_default();
                        // 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 {
                                ev.prevent_default();
                                #[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!("⚠️ FooterLink: No navigation signals available for href: '{}', allowing default browser footer", href).into());
                            }
                            // Otherwise, let the normal link behavior happen (SSR)
                        } else {
                            #[cfg(target_arch = "wasm32")]
                            web_sys::console::log_1(&format!("🌐 FooterLink: External link detected for href: '{}', allowing default browser footer", href).into());
                        }
                    }>
                    {link_label}
                </a>
            </li>
        }
    };

    view! {
        <footer class={footer_class}>
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                    // Company info from footer config - consistent with navigation
                    <div class="col-span-1">
                        // Logo — SPA-navigates to home page on click
                        {logo_config.show_in_footer.then(move || {
                            let nav_sigs = navigation_signals;
                            let dest = home_url.clone();
                            let logo_footer_config = logo_config.clone();
                            view! {
                                <a
                                    href={dest.clone()}
                                    class="inline-block mb-4"
                                    on:click=move |ev| {
                                        if let Some((_, set_path)) = nav_sigs {
                                            ev.prevent_default();
                                            #[cfg(target_arch = "wasm32")]
                                            ::rustelo_core_lib::utils::nav::anchor_navigate(set_path, &dest);
                                            #[cfg(not(target_arch = "wasm32"))]
                                            set_path.set(dest.clone());
                                        }
                                    }
                                >
                                    <Logo config=logo_footer_config class="h-8 w-auto".to_string() />
                                </a>
                            }
                        })}
                        <p class="ds-text-secondary text-sm mb-4">
                            {footer_config.company_desc}
                        </p>
                        <p class="text-sm ds-text-secondary">
                            {footer_config.copyright_text}
                        </p>
                    </div>

                    // Dynamic footer sections from TOML
                    {footer_config.sections.clone().into_iter().map(|section| {
                        let section_title = section.title.get_with_fallback(&current_lang, "en");

                        view! {
                            <div>
                                <h4 class="font-semibold ds-text mb-3">{section_title}</h4>
                                <ul class="space-y-2 text-sm">
                                    {section.links.into_iter().map(render_footer_link).collect::<Vec<_>>()}
                                </ul>
                            </div>
                        }
                    }).collect::<Vec<_>>()}

                    // Dynamic social links (if enabled and defined)
                    {(show_social && !footer_config.social_links.is_empty()).then(|| view! {
                        <div>
                            <h4 class="font-semibold ds-text mb-3">{get_content("footer-social-links")}</h4>
                            <div class="flex flex-col space-y-3">
                                {footer_config.social_links.into_iter().map(|social| {
                                    let name = social.name.clone();
                                    // Extract icon class for proper rendering
                                    let icon_html = match social.icon_class.as_str() {
                                        icon if icon.contains("github") => r#"<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315 .225 .69 .825 .57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>"#.to_string(),
                                        icon if icon.contains("linkedin") => r#"<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>"#.to_string(),
                                        _ => format!(r#"<i class="{}" aria-hidden="true"></i>"#, social.icon_class),
                                    };

                                    view! {
                                        <a href={social.url.clone()}
                                           target="_blank"
                                           rel="noopener noreferrer"
                                           class="ds-text-secondary hover:ds-text transition-colors"
                                           aria-label={name.clone()}>
                                           <span inner_html={icon_html}></span>
                                        </a>
                                    }
                                }).collect::<Vec<_>>()}
                            </div>
                        </div>
                    })}
                </div>

                // "Built with Rustelo" attribution bar
                {
                    let built_label = get_content("footer-built-with");
                    let rustelo_route = "/rustelo".to_string();
                    let rustelo_route_click = rustelo_route.clone();
                    let nav_sigs = navigation_signals;
                    view! {
                        <div class="border-t border-base-300 mt-8 pt-5 flex justify-center items-center gap-2 text-sm ds-text-secondary">
                            <span>{built_label}</span>
                            <a
                                href={rustelo_route}
                                class="inline-flex items-center gap-1.5 hover:opacity-80 transition-opacity no-underline"
                                on:click=move |ev| {
                                    if let Some((_, set_path)) = nav_sigs {
                                        ev.prevent_default();
                                        #[cfg(target_arch = "wasm32")]
                                        ::rustelo_core_lib::utils::nav::anchor_navigate(set_path, &rustelo_route_click);
                                        #[cfg(not(target_arch = "wasm32"))]
                                        set_path.set(rustelo_route_click.clone());
                                    }
                                }
                            >
                                <img
                                    src="/images/logos/rustelo-img.svg"
                                    alt="Rustelo"
                                    class="h-5 w-auto"
                                />
                                <span class="text-gray-700 dark:text-gray-500">Rustelo</span>
                            </a>
                        </div>
                    }
                }
            </div>
        </footer>

        // Scroll to top button (if enabled) - small fixed position button
        {show_scroll_to_top.then(|| view! {
            <button
                class="fixed bottom-4 right-4 w-10 h-10 bg-gray-800 dark:bg-gray-600 text-white rounded-full shadow-lg hover:shadow-xl hover:bg-gray-700 dark:hover:bg-gray-500 transition-all duration-300 flex items-center justify-center z-50"
                on:click=scroll_to_top
                aria-label="Scroll to top"
                title="Scroll to top"
            >
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7-7m0 0l7 7m-7-7v18"></path>
                </svg>
            </button>
        })}
    }
}
