//! Navigation management for the routing engine
//!
//! This module handles navigation item generation and caching
//! for different languages.

use std::collections::HashMap;

use super::types::{NavigationItem, NavigationTarget};
use crate::components::RoutesConfig;

/// Generate navigation items for a language from TOML routes
pub fn generate_navigation_items(
    toml_config: &RoutesConfig,
    language: &str,
    cache: &mut HashMap<String, Vec<NavigationItem>>,
) -> Vec<NavigationItem> {
    if let Some(cached) = cache.get(language) {
        return cached.clone();
    }

    let mut items = Vec::new();

    // Generate navigation from TOML routes
    for route in &toml_config.routes {
        if !route.enabled || route.language != language {
            continue;
        }

        // Only include routes that should appear in menus
        if route.menu_group.is_some() {
            // Determine the correct navigation target based on route type
            let target = if route.is_external.unwrap_or(false) || route.path.starts_with("http") {
                NavigationTarget::External(route.path.clone())
            } else if route.path.starts_with("mailto:") {
                NavigationTarget::Email(
                    route
                        .path
                        .strip_prefix("mailto:")
                        .unwrap_or(&route.path)
                        .to_string(),
                )
            } else if route.path.starts_with("tel:") {
                NavigationTarget::Phone(
                    route
                        .path
                        .strip_prefix("tel:")
                        .unwrap_or(&route.path)
                        .to_string(),
                )
            } else {
                NavigationTarget::Route(route.path.clone())
            };

            let item = NavigationItem {
                label: route.title_key.clone(), // Would be resolved by i18n system
                target,
                icon: route.menu_icon.clone(),
                group: route.menu_group.clone(),
                order: route.menu_order.unwrap_or(0),
                active: false,
                classes: None,
            };
            items.push(item);
        }
    }

    // Sort by order within groups
    items.sort_by(|a, b| a.order.cmp(&b.order));

    cache.insert(language.to_string(), items.clone());
    items
}
