//! Common utilities for page components

use std::collections::HashMap;

use leptos::prelude::*;
use reactive_graph::traits::Get;
use rustelo_core_lib::{
    i18n::{
        helpers::build_page_content_patterns,
        unified::{use_unified_i18n, UnifiedI18n},
    },
    state::language::use_language,
};

/// Get unified i18n instance for both SSR and client contexts
pub fn use_i18n() -> UnifiedI18n {
    use_unified_i18n()
}

/// Create a reactive memo for i18n page content with specified patterns
///
/// This eliminates the repetitive boilerplate found in client page components.
/// Instead of 20+ lines of memo creation code, use a single function call.
///
/// # Arguments
/// * `patterns` - Static patterns that will be cloned into the memo
///
/// # Returns
/// A `Memo<HashMap<String, String>>` that reactively updates when language
/// changes
///
/// # Example
/// ```rust
/// use rustelo_pages::common::use_page_i18n;
/// let page_content = use_page_i18n(vec!["contact-"]);
/// ```
pub fn use_page_i18n(patterns: Vec<&'static str>) -> Memo<HashMap<String, String>> {
    let language_context = use_language();

    Memo::new(move |_| {
        // Trigger reactivity on language change (even though we don't use the value
        // directly)
        let _ = language_context.current.get();
        // Use the context i18n instead of creating a new one
        let i18n = use_unified_i18n();
        let pattern_refs: Vec<&str> = patterns.iter().copied().collect();
        build_page_content_patterns(&i18n, &pattern_refs)
    })
}

/// Create a reactive memo for i18n page content with dynamic patterns
///
/// This version supports runtime-generated patterns, useful for content types
/// that are determined at runtime.
///
/// # Arguments
/// * `base_patterns` - Static base patterns
/// * `dynamic_patterns` - Function that generates additional patterns
///
/// # Returns
/// A `Memo<HashMap<String, String>>` that reactively updates when language
/// changes
pub fn use_page_i18n_dynamic<F>(
    base_patterns: Vec<&'static str>,
    dynamic_patterns: F,
) -> Memo<HashMap<String, String>>
where
    F: Fn() -> Vec<String> + Send + Sync + 'static,
{
    let language_context = use_language();

    Memo::new(move |_| {
        let _ = language_context.current.get();
        // Use the context i18n instead of creating a new one
        let i18n = use_unified_i18n();

        // Combine static and dynamic patterns
        let mut all_pattern_strings: Vec<String> =
            base_patterns.iter().map(|&p| p.to_string()).collect();
        all_pattern_strings.extend(dynamic_patterns());

        let content_patterns: Vec<&str> = all_pattern_strings.iter().map(|s| s.as_str()).collect();

        build_page_content_patterns(&i18n, &content_patterns)
    })
}

/// Macro for creating i18n page content memos with simple patterns
///
/// This macro generates the reactive memo code for pages with fixed patterns.
/// It eliminates the need for 20+ lines of boilerplate in each client page.
///
/// # Usage
/// ```rust
/// use rustelo_pages::page_i18n_memo;
/// // Simple single pattern
/// let page_content = page_i18n_memo!(["contact-"]);
///
/// // Multiple patterns
/// let page_content = page_i18n_memo!(["user-", "profile-"]);
/// ```
#[macro_export]
macro_rules! page_i18n_memo {
    ([$($pattern:expr),+ $(,)?]) => {
        $crate::common::use_page_i18n(vec![$($pattern),+])
    };
}

/// Macro for creating i18n page content memos with dynamic patterns
///
/// This macro supports both static and runtime-generated patterns,
/// useful for content-driven pages that need dynamic pattern generation.
///
/// # Usage
/// ```rust
/// use rustelo_pages::page_i18n_memo_dynamic;
/// // With dynamic content type patterns
/// let page_content = page_i18n_memo_dynamic!(
///     ["post-viewer-"],
///     || {
///         rustelo_core_lib::content_resolver::get_available_content_types().iter()
///             .map(|t| format!("{}-", t))
///             .collect()
///     }
/// );
/// ```
#[macro_export]
macro_rules! page_i18n_memo_dynamic {
    ([$($base_pattern:expr),+ $(,)?], $dynamic_fn:expr) => {
        $crate::common::use_page_i18n_dynamic(vec![$($base_pattern),+], $dynamic_fn)
    };
}
