//! Head fragments shared by both shells: CSS links, JS scripts, i18n data,
//! per-page content data. All return `String` so callers can splice them into
//! a `<head>` built by `format!`.

use rustelo_web::rustelo_core_lib::registration::get_parsed_ftl_for_language;
use rustelo_web::rustelo_core_lib::AssetMode;

use html_escape::encode_double_quoted_attribute;

/// Resolves the configured asset bundle (source vs bundled) and returns the
/// (css_paths, js_paths) slices.
pub fn asset_paths() -> (&'static [&'static str], &'static [&'static str]) {
    let mode = AssetMode::default_for_environment();
    if mode.is_source() {
        (crate::source_mode::CSS, crate::source_mode::JS)
    } else {
        (crate::bundled_mode::CSS, crate::bundled_mode::JS)
    }
}

/// `<link rel="stylesheet">` tags concatenated as a single string.
pub fn stylesheet_links() -> String {
    let (css_paths, _) = asset_paths();
    let mut out = String::new();
    for href in css_paths {
        out.push_str(&format!(r#"<link rel="stylesheet" href="{href}">"#));
    }
    out
}

/// Non-defer `<script>` tags for the active asset bundle.
pub fn bundle_scripts() -> String {
    let (_, js_paths) = asset_paths();
    let mut out = String::new();
    for src in js_paths {
        out.push_str(&format!(r#"<script src="{src}"></script>"#));
    }
    out
}

/// `<script id="i18n-data" type="application/json">` block embedding the FTL
/// payload for the active language.
pub fn i18n_script(language: &str) -> String {
    let json = get_parsed_ftl_for_language(language)
        .and_then(|lang_map| serde_json::to_string(&lang_map).ok())
        .map(|s| s.replace("</", "\\/"))
        .unwrap_or_default();
    format!(
        r#"<script id="i18n-data" type="application/json" data-lang="{}">{json}</script>"#,
        encode_double_quoted_attribute(language)
    )
}

/// Per-page content index JSON block, when the path maps to a content kind.
/// Returns empty string for non-content pages so callers can splice unconditionally.
pub fn content_data_script(path: &str, language: &str) -> String {
    let Some(content_type) = crate::get_content_type_for_path(path) else {
        return String::new();
    };
    let Ok(index) = rustelo_core_lib::load_content_index(content_type, language) else {
        return String::new();
    };
    let Ok(json) = serde_json::to_string(&index) else {
        return String::new();
    };
    let safe_json = json.replace("</", "\\/");
    format!(
        r#"<script id="content-data-{ct}-{lang}" type="application/json">{safe_json}</script>"#,
        ct = encode_double_quoted_attribute(content_type),
        lang = encode_double_quoted_attribute(language)
    )
}

/// Standard `<meta>` tags every shell emits (charset, viewport).
pub fn baseline_meta() -> &'static str {
    r#"<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">"#
}
