//! Unified brand header component
//!
//! Provides consistent branding (logo or title) with identical behavior
//! across navigation menu and footer components.

use ::rustelo_core_lib::{get_theme, load_reactive_footer_for_language};
use leptos::prelude::*;

/// Extract logo configuration from registered theme
///
/// This function reads from the registered theme resources (loaded at server startup
/// from config/themes/default.toml) to get configuration-driven logo paths.
/// PAP-compliant: Uses registered resources, no hardcoding.
fn get_logo_config() -> (String, String, String) {
    // Get theme - available in both SSR and client contexts
    // On WASM: registry will be populated from embedded constants
    // On server: registry is populated at startup from ResourceContributor
    let theme_result = get_theme("default");

    if let Some(theme_toml) = theme_result {
        let logo_light = extract_toml_value(&theme_toml, "logo_light");
        let logo_dark = extract_toml_value(&theme_toml, "logo_dark");
        let mut logo_alt = extract_toml_value(&theme_toml, "logo_alt");

        if !logo_light.is_empty() {
            // Use extracted alt text, or default to "Logo"
            if logo_alt.is_empty() {
                logo_alt = "Logo".to_string();
            }
            return (logo_light, logo_dark, logo_alt);
        }
    }

    // Fallback when theme unavailable
    (String::new(), String::new(), "Logo".to_string())
}

/// Helper to extract TOML values from theme content using simple string parsing
/// This avoids adding toml dependency to rustelo_components
fn extract_toml_value(content: &str, key: &str) -> String {
    // Look for key = "value" pattern in [assets] section
    let pattern = format!("{} = \"", key);
    if let Some(start) = content.find(&pattern) {
        let start_pos = start + pattern.len();
        if let Some(end) = content[start_pos..].find('"') {
            return content[start_pos..start_pos + end].to_string();
        }
    }
    String::new()
}

/// Unified brand header that works consistently in nav and footer
#[component]
#[allow(unused_variables)]
pub fn BrandHeader(
    /// Language for loading configuration
    #[prop(optional)]
    language: Option<String>,
    /// CSS classes for the brand element
    #[prop(default = "text-xl font-bold".to_string())]
    class: String,
    /// Force show/hide logo (overrides config)
    #[prop(optional)]
    force_logo: Option<bool>,
    /// Use footer logo settings instead of nav settings
    #[prop(default = false)]
    is_footer: bool,
) -> impl IntoView {
    // Get logo configuration
    let (logo_light, logo_dark, logo_alt) = get_logo_config();

    // Get site title from footer config or environment
    let site_title = {
        // Try to load from footer config first
        let lang = language.as_deref().unwrap_or("en");
        let config_title = load_reactive_footer_for_language(lang)
            .ok()
            .map(|footer| footer.title)
            .filter(|title| !title.is_empty());

        // Fallback to environment variables
        config_title.unwrap_or_else(|| {
            std::env::var("SITE_TITLE")
                .or_else(|_| std::env::var("SITE_LOGO_ALT"))
                .unwrap_or_else(|_| "Site".to_string())
        })
    };

    // Determine if we should show logo (from config or override)
    let show_logo = force_logo.unwrap_or(true);
    let render_logo = show_logo && !logo_light.is_empty();
    let has_dark_logo = !logo_dark.is_empty();
    view! {
        <a href="/" class=format!("{} transition-colors flex items-center gap-2", class)>
            {
                if render_logo {
                    // Render logo images if available
                    if has_dark_logo {
                        view! {
                            <>
                                <img
                                    src=logo_light.clone()
                                    alt=logo_alt.clone()
                                    class="h-10 object-contain dark:hidden"
                                    loading="eager"
                                />
                                <img
                                    src=logo_dark.clone()
                                    alt=logo_alt.clone()
                                    class="h-10 object-contain hidden dark:block"
                                    loading="eager"
                                />
                            </>
                        }.into_any()
                    } else {
                        view! {
                            <img
                                src=logo_light.clone()
                                alt=logo_alt.clone()
                                class="h-10 object-contain"
                                loading="eager"
                            />
                        }.into_any()
                    }
                } else {
                    // Render text fallback
                    view! {
                        <span class="ds-text">{site_title.clone()}</span>
                    }.into_any()
                }
            }
        </a>
    }
}
