//! Server-side rendering (SSR) implementations for filter components
//!
//! These components render filter UI during server-side rendering,
//! providing initial HTML structure before client-side hydration.

// use crate::{get_active_button_classes, get_inactive_button_classes};

use super::unified::UnifiedCategoryFilter;
use leptos::prelude::*;

/// SSR-only Content Category Filter Component
///
/// Renders the initial HTML structure for category filtering during SSR.
/// Client-side functionality is handled by the client-side component after hydration.
#[component]
pub fn CategoryFilterSSR(
    content_type: String,
    language: String,
    #[prop(optional)] all_emoji: Option<String>,
) -> impl IntoView {
    view! {
        <div class="mb-8">
            <UnifiedCategoryFilter
                content_type=content_type.clone()
                language=language.clone()
                _all_emoji=all_emoji.unwrap_or_else(|| "".to_string())
            />
        </div>
    }
}

// SSR-compatible helper functions that also work in WASM for hydration consistency

/// Generic content filtering by category - SSR compatible version
#[cfg(target_arch = "wasm32")]
fn filter_content_by_category(content_type: &str, category: &str) {
    // Navigate to category URL when not "All"
    if category != "All" {
        navigate_to_category_url(content_type, category);
        return; // Let the URL change handle the content filtering
    }

    // For "All" category, navigate back to main content page
    navigate_to_main_content_url(content_type);
}

/// Navigate to the appropriate category URL based on content type and language
#[cfg(target_arch = "wasm32")]
fn navigate_to_category_url(content_type: &str, category: &str) {
    // Use the current language context to determine the language
    let language = rustelo_core_lib::state::language::use_current_language().get();

    // Build the correct category URL using the routing system dynamically
    let base_path = format!("/{}", content_type);
    // First get the localized base path, then append the category
    let localized_base = rustelo_core_lib::routing::rustelo_utils::get_localized_route(&base_path, &language);
    let category_url = format!("{}/{}", localized_base, category);

    tracing::debug!(
        "SPA Navigation: Navigating to category URL: {}",
        category_url
    );

    // Use the proper navigation system instead of location.set_href() to maintain SPA behavior
    if let Some(navigate) = try_get_navigate() {
        let success = navigate(&category_url);
        if !success {
            tracing::warn!(
                "SPA navigation failed for: {}, falling back to page reload",
                category_url
            );
            // Fallback to page reload if SPA navigation fails
            if let Some(window) = web_sys::window() {
                let location = window.location();
                let _ = location.set_href(&category_url);
            }
        }
    } else {
        tracing::warn!(
            "Navigation context not available, using page reload for: {}",
            category_url
        );
        // Fallback to page reload if navigation context is not available
        if let Some(window) = web_sys::window() {
            let location = window.location();
            let _ = location.set_href(&category_url);
        }
    }
}

/// Navigate to main content page (when "All" is selected)
#[cfg(target_arch = "wasm32")]
fn navigate_to_main_content_url(content_type: &str) {
    // Use the current language context to determine the language
    let language = rustelo_core_lib::state::language::use_current_language().get();

    // Build the correct main URL using the routing system dynamically
    let base_path = format!("/{}", content_type);
    let main_url = rustelo_core_lib::routing::rustelo_utils::get_localized_route(&base_path, &language);

    tracing::debug!(
        "SPA Navigation: Navigating to main content URL: {}",
        main_url
    );

    // Use the proper navigation system instead of location.set_href() to maintain SPA behavior
    if let Some(navigate) = try_get_navigate() {
        let success = navigate(&main_url);
        if !success {
            tracing::warn!(
                "SPA navigation failed for: {}, falling back to page reload",
                main_url
            );
            // Fallback to page reload if SPA navigation fails
            if let Some(window) = web_sys::window() {
                let location = window.location();
                let _ = location.set_href(&main_url);
            }
        }
    } else {
        tracing::warn!(
            "Navigation context not available, using page reload for: {}",
            main_url
        );
        // Fallback to page reload if navigation context is not available
        if let Some(window) = web_sys::window() {
            let location = window.location();
            let _ = location.set_href(&main_url);
        }
    }
}

/// Update content filter button visual states
#[cfg(target_arch = "wasm32")]
fn update_content_filter_button_states(content_type: &str, selected_category: &str) {
    use wasm_bindgen::prelude::*;
    use web_sys::{window, HtmlElement};

    let window = match window() {
        Some(w) => w,
        None => return,
    };

    let document = match window.document() {
        Some(d) => d,
        None => return,
    };

    // Update all content filter buttons
    let buttons = document.get_elements_by_class_name("content-category-filter-btn");

    for i in 0..buttons.length() {
        if let Some(element) = buttons.item(i) {
            if let Ok(button) = element.dyn_into::<HtmlElement>() {
                let button_content_type = button
                    .get_attribute("data-content-type")
                    .unwrap_or_default();
                let category = button.get_attribute("data-category").unwrap_or_default();

                // Only update buttons for the matching content type
                if button_content_type == content_type {
                    if category == selected_category {
                        // Active button style
                        let _ = button.set_class_name(crate::get_active_button_classes());
                    } else {
                        // Inactive button style
                        let _ = button.set_class_name(crate::get_inactive_button_classes());
                    }
                }
            }
        }
    }

    // Update status text
    let status_id = format!("{}-filter-status", content_type);
    if let Some(status_element) = document.get_element_by_id(&status_id) {
        if let Ok(status) = status_element.dyn_into::<HtmlElement>() {
            let status_text = if selected_category == "All" {
                format!("Showing all {} content", content_type)
            } else {
                format!("Showing {}: {}", content_type, selected_category)
            };
            status.set_inner_text(&status_text);
        }
    }
}

/// Try to get the navigation function, handling cases where the context is not available
#[cfg(target_arch = "wasm32")]
fn try_get_navigate() -> Option<impl Fn(&str) -> bool> {
    use std::panic;

    // Try to get the navigation context safely
    let result = panic::catch_unwind(|| rustelo_core_lib::state::navigation::use_navigate());

    match result {
        Ok(navigate_fn) => Some(navigate_fn),
        Err(_) => {
            tracing::debug!("Navigation context not available, will use page reload fallback");
            None
        }
    }
}
