//! Unified Content Category Page - works with any content type category
//! dynamically
//!
//! This component is fully configuration-driven and works with any content type
//! defined in content-kinds.toml without hardcoded logic.
//!
//! Uses safe, non-reactive patterns to avoid hydration issues and panics.

// Simple language validation function
fn validate_language(lang: &str) -> bool {
    // Simple validation - check if language is not empty and has reasonable length
    !lang.is_empty() && lang.len() <= 5 && lang.chars().all(|c| c.is_alphabetic() || c == '-')
}
// use rustelo_core_lib::content::traits::*;
use leptos::prelude::*;
use rustelo_components_leptos::content::grid::UnifiedContentGrid;

//#[cfg(not(target_arch = "wasm32"))]
// use rustelo_core_lib::fluent::loaders::load_content_index;

/// Unified Content Category Page for any content type with proper hydration
/// support
///
/// This component automatically determines content type from the current route
/// and displays the appropriate category filtering (blog, recipes, or any
/// future content types) Uses the UnifiedContentCategoryPageComplete component
/// that ensures proper SSR/client hydration
#[component]
pub fn ContentCategoryPage(
    #[prop(into)] content_type: String,
    category: String,
    #[prop(into)] _language: String,
) -> impl IntoView {
    #[cfg(not(target_arch = "wasm32"))]
    {
        // SSR context: use static implementation
        view! {
            <crate::content::category::ssr::ContentCategoryPageSSR
                content_type=content_type.clone()
                category=category
                _language=_language
            />
        }
    }

    #[cfg(target_arch = "wasm32")]
    {
        // Client context: use reactive implementation with language
        view! {
            <crate::content::category::client::ContentCategoryPageClient
                content_type=content_type
                category=category
                _language=_language
            />
        }
    }
}

/// Complete unified content category page using configuration-driven
/// architecture
///
/// This component renders a category-filtered content page that adapts based on
/// the content type properties. Uses safe, non-reactive patterns and is
/// completely configuration-driven.
#[component]
pub fn UnifiedContentCategoryPage(
    #[allow(unused_variables)]
    #[prop(into)]
    content_type: String,
    #[allow(unused_variables)]
    #[prop(into)]
    category: String,
    #[allow(unused_variables)]
    #[prop(optional)]
    _language: String,
    #[prop(optional)] lang_content: Option<std::collections::HashMap<String, String>>,
    //  #[prop(optional)] all_categories: Option<Vec<String>>,
) -> impl IntoView {
    // Validate inputs early with safe fallbacks using configuration
    let safe_content_type_key = content_type.clone();
    // let safe_content_type_key = if validate_content_type_key(&content_type_key) {
    //     content_type_key
    // } else {
    //     tracing::warn!(
    //         "Invalid content_type_key: '{}', using default",
    //         content_type_key
    //     );
    //     "content".to_string()
    // };

    let safe_language = if validate_language(&_language) {
        _language
    } else {
        tracing::warn!("Invalid language: '{}', using default", _language.clone());
        rustelo_core_lib::config::get_default_language().to_string()
    };

    let safe_category = category.clone();
    // let safe_category = if validate_category(&category) {
    //     category
    // } else {
    //     tracing::warn!("Invalid category: '{}', using 'all'", category);
    //     "all".to_string()
    // };

    // // Get content configuration using registry (configuration-driven)
    let content_registry = rustelo_core_lib::create_content_kind_registry();
    let _config = content_registry
        .kinds
        .get(&safe_content_type_key)
        .cloned()
        .unwrap_or_else(|| {
            tracing::warn!(
                "No config found for content type '{}', using default",
                safe_content_type_key
            );
            rustelo_core_lib::ContentConfig::from_env()
        });

    // // Build navigation URLs using configuration
    // let _main_url = if safe_language == "en" {
    //     format!("/{}", safe_content_type_key)
    // } else {
    //     format!("/{}/{}", safe__language, safe_content_type_key)
    // };

    // let _home_url = if safe_language == "en" {
    //     "/".to_string()
    // } else {
    //     format!("/{}", safe_language)
    // };

    // let _home_label_key = "nav-home";
    // let _main_label_key = format!("{}-page-title", safe_content_type_key);
    // let _current_label = if config.features.use_emojis {
    //     format!(
    //         "{} {}",
    //         rustelo_core_lib::get_category_emoji(&safe_content_type_key,
    // &safe__language, &safe_category),         safe_category
    //     )
    // } else {
    //     safe_category.clone()
    // };

    // Always use empty content during hydration to prevent mismatches
    // Content will be loaded after hydration is complete
    let content_translations = lang_content.unwrap_or_default();

    // Content getter function with consistent fallbacks
    let get_content = |key: &str| {
        content_translations.get(key).cloned().unwrap_or_else(|| {
            // During hydration, use the key itself as fallback to ensure consistency
            // This prevents hydration mismatches by ensuring identical output
            #[cfg(target_arch = "wasm32")]
            {
                // On client, provide predictable fallback that matches server
                key.to_string()
            }
            #[cfg(not(target_arch = "wasm32"))]
            {
                // On server, ensure same fallback as client
                key.to_string()
            }
        })
    };

    // // Pre-compute all titles and descriptions
    // let _page_title = build_page_title(
    //     &safe_content_type_key,
    //     Some(&safe_category),
    //     &safe__language,
    //     get_content,
    // );
    // let _page_description =
    //     build_page_description(&safe_content_type_key, Some(&safe_category),
    // get_content);

    // // Pre-compute navigation data - use empty during hydration to prevent
    // mismatches let _categories_nav = all_categories
    //     .as_ref()
    //     .map(|cats| cats.clone())
    //     .unwrap_or_default();

    // // Always hide categories nav during initial render to prevent hydration
    // mismatches // Categories will be loaded after hydration completes
    // let _show_categories_nav = false;
    // let _show_content_links = false; // TODO: Implement content links from config

    // // Calculate grid classes based on style mode
    // let _grid_classes = build_grid_classes(&config.features.style_mode);

    // // For hydration consistency, always start with empty content on both server
    // and client during initial render // Content will be loaded after
    // hydration to prevent mismatches // #[cfg(target_arch = "wasm32")]
    // let (loaded_content, filtered_content, has_content) = {
    //     // Client-side: Always start with empty content during hydration
    //     let empty_content:
    // Option<Vec<crate::content::index::unified::GenericContentItem>> = None;
    //     let empty_filtered:
    // Vec<crate::content::index::unified::GenericContentItem> = Vec::new();
    //     (empty_content, empty_filtered, false)
    // };

    // #[cfg(not(target_arch = "wasm32"))]
    // let (loaded_content, filtered_content, has_content) = {
    //     // Server-side: For now, also use empty content to match client during
    // SSR     // This prevents hydration mismatches. Content will load after
    // hydration.     let empty_content:
    // Option<Vec<crate::content::index::unified::GenericContentItem>> = None;
    //     let empty_filtered:
    // Vec<crate::content::index::unified::GenericContentItem> = Vec::new();
    //     (empty_content, empty_filtered, false)
    // };

    // Render consistent loading state to prevent hydration mismatches
    view! {
        <div class="ds-bg-page">
            <div class="ds-container py-8">
                <div class="text-center mb-8">
                    <h1 class="text-4xl font-bold ds-text mb-4">
                        {if true { // Default emojis enabled
                            format!(
                                "{} {} Category",
                                rustelo_core_lib::get_category_emoji(&safe_content_type_key, &safe_language, &safe_category),
                                safe_category
                            )
                        } else {
                            format!("{} Category", &safe_category)
                        }}
                    </h1>
                    <p class="ds-text-secondary text-lg">
                        {get_content("category-description")}
                    </p>
                </div>

                <section class="py-ds-6">
                    <div class="ds-container">
                        <UnifiedContentGrid
                            content_type=safe_content_type_key.clone()
                            language=safe_language.clone()
                            show_categories=false
                            category_filter=safe_category.clone()
                            limit=12
                        />
                    </div>
                </section>
            </div>
        </div>
    }
}
