//! Shared types and utilities for filter components
//!
//! This module contains types and utilities that are shared between
//! client and server filter implementations.

use std::collections::HashMap;
use std::sync::{LazyLock, RwLock};
use std::time::SystemTime;

use serde::{Deserialize, Serialize};

/// Filter item with name, count, and emoji
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterItem {
    pub name: String,
    pub count: u32,
    #[serde(default = "default_emoji")]
    pub emoji: String,
}

fn default_emoji() -> String {
    "🏷️".to_string()
}

/// Cache entry for filter items with timestamp
#[derive(Debug, Clone)]
pub struct CachedFilterItems {
    pub items: Vec<FilterItem>,
    pub timestamp: SystemTime,
}

/// Global cache for filter items to avoid repeated file reads
pub static FILTER_CACHE: LazyLock<RwLock<HashMap<String, CachedFilterItems>>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));

/// Cache duration before checking for file updates (5 minutes in development, 1
/// hour in production)
pub const CACHE_DURATION_SECS: u64 = if cfg!(debug_assertions) { 300 } else { 3600 };

/// Load filter items from JSON content
pub fn load_filter_items_from_json(
    content: &str,
    array_key: &str,
) -> Result<Vec<FilterItem>, Box<dyn std::error::Error>> {
    let index: serde_json::Value = serde_json::from_str(content)?;

    if let Some(items_array) = index.get(array_key).and_then(|v| v.as_array()) {
        let items: Vec<FilterItem> = items_array
            .iter()
            .filter_map(|item| {
                let name = item.get("name")?.as_str()?.to_string();
                let count = item.get("count")?.as_u64()? as u32;
                let emoji = item
                    .get("emoji")
                    .and_then(|e| e.as_str())
                    .unwrap_or("🏷️")
                    .to_string();

                Some(FilterItem { name, count, emoji })
            })
            .collect();

        return Ok(items);
    }

    Ok(Vec::new())
}

/// Clear all cached filter items (useful for development/testing)
pub fn clear_filter_cache() {
    if let Ok(mut cache) = FILTER_CACHE.write() {
        cache.clear();
    }
}

/// Generate CSS classes for filter buttons
pub fn get_active_button_classes() -> &'static str {
    "ds-btn-content-category-filter px-4 py-2 border rounded-full transition-colors duration-200 \
     border-blue-500 text-blue-400 hover:text-white active"
}

pub fn get_inactive_button_classes() -> &'static str {
    "ds-btn-content-category-filter px-4 py-2 border rounded-full transition-colors duration-200 \
     border-gray-400 text-gray-400 hover:border-blue-400"
}
