//! website HTMX page renderers.
//!
//! Provides project-specific Minijinja page bodies. Call [`dispatch`] from the
//! server's HTMX page dispatcher to render static and product pages. Content
//! post pages (blog, projects, etc.) are handled by `rustelo_pages_htmx`.

mod pages;

use minijinja::Environment;

/// Path to this crate's `templates/` directory, set at build time.
pub const TEMPLATES_DIR: &str = env!("JPL_PAGES_HTMX_TEMPLATES");

/// Attempt to render the page body for `path` in `lang`.
///
/// Returns `Some(html)` for known project routes, `None` for unknown paths
/// so the caller can fall through to 404.
pub fn dispatch(env: &Environment, path: &str, lang: &str) -> Option<String> {
    match path {
        // Home
        "/" | "/inicio" | "/en" | "/es" => Some(pages::home::render(env, lang)),

        // Static pages — generic template with page_id for FTL key lookup
        "/about" | "/acerca-de" => Some(pages::static_page::render(env, "about", lang)),
        "/services" | "/servicios" => Some(pages::static_page::render(env, "services", lang)),
        "/contact" | "/contacto" => Some(pages::static_page::render(env, "contact", lang)),
        "/legal" => Some(pages::static_page::render(env, "legal", lang)),
        "/privacy" | "/privacidad" => Some(pages::static_page::render(env, "privacy", lang)),
        "/work-request" | "/solicitud-trabajo" => {
            Some(pages::static_page::render(env, "work-request", lang))
        }

        // Product pages
        "/syntaxis" => Some(pages::static_page::render(env, "syntaxis", lang)),
        "/vapora" => Some(pages::static_page::render(env, "vapora", lang)),
        "/rustelo" => Some(pages::static_page::render(env, "rustelo", lang)),
        "/provisioning-systems" => {
            Some(pages::static_page::render(env, "provisioning", lang))
        }
        "/stratumiops" => Some(pages::static_page::render(env, "stratumiops", lang)),
        "/kogral" => Some(pages::static_page::render(env, "kogral", lang)),
        "/typedialog" => Some(pages::static_page::render(env, "typedialog", lang)),
        "/ontoref" => Some(pages::static_page::render(env, "ontoref", lang)),
        "/secretumvault" => Some(pages::static_page::render(env, "secretumvault", lang)),

        // Auth pages served via HTMX modal — direct URL access shows a minimal shell
        "/login" | "/iniciar-sesion" => {
            Some(pages::static_page::render(env, "login", lang))
        }

        _ => None,
    }
}

#[cfg(test)]
mod ftl_parse_tests {
    use fluent_bundle::{FluentBundle, FluentResource};
    use unic_langid::LanguageIdentifier;

    fn load_combined_ftl(lang: &str) -> String {
        let base = concat!(env!("CARGO_MANIFEST_DIR"), "/../../site/i18n/locales");
        let lang_dir = format!("{}/{}", base, lang);
        let mut combined = String::new();

        for fname in &["common.ftl", "auth.ftl"] {
            let p = format!("{}/{}", lang_dir, fname);
            if std::path::Path::new(&p).exists() {
                combined.push_str(&std::fs::read_to_string(&p).unwrap());
                combined.push('\n');
            }
        }
        for subdir in &["pages", "components", "manager"] {
            let dir = format!("{}/{}", lang_dir, subdir);
            if let Ok(entries) = std::fs::read_dir(&dir) {
                let mut files: Vec<_> = entries
                    .filter_map(|e| e.ok())
                    .filter(|e| e.path().extension().map_or(false, |x| x == "ftl"))
                    .collect();
                files.sort_by_key(|e| e.file_name());
                for entry in &files {
                    combined.push_str(&std::fs::read_to_string(entry.path()).unwrap());
                    combined.push('\n');
                }
            }
        }
        combined
    }

    #[test]
    fn test_ftl_parse_en() {
        let content = load_combined_ftl("en");
        assert!(!content.is_empty(), "en FTL content is empty");
        match FluentResource::try_new(content) {
            Ok(_) => println!("en FTL: parse OK"),
            Err((_, errors)) => panic!("en FTL parse errors: {:?}", errors),
        }
    }

    #[test]
    fn test_ftl_bundle_en() {
        let content = load_combined_ftl("en");
        let resource = FluentResource::try_new(content).expect("en FTL should parse");
        let langid: LanguageIdentifier = "en".parse().unwrap();
        let mut bundle = FluentBundle::new(vec![langid]);
        match bundle.add_resource(resource) {
            Ok(_) => println!("en FTL: bundle add OK"),
            Err(errors) => panic!("en FTL bundle add errors: {:?}", errors),
        }
    }

    #[test]
    fn test_ftl_parse_es() {
        let content = load_combined_ftl("es");
        assert!(!content.is_empty(), "es FTL content is empty");
        match FluentResource::try_new(content) {
            Ok(_) => println!("es FTL: parse OK"),
            Err((_, errors)) => panic!("es FTL parse errors: {:?}", errors),
        }
    }

    #[test]
    fn test_ftl_bundle_es() {
        let content = load_combined_ftl("es");
        let resource = FluentResource::try_new(content).expect("es FTL should parse");
        let langid: LanguageIdentifier = "es".parse().unwrap();
        let mut bundle = FluentBundle::new(vec![langid]);
        match bundle.add_resource(resource) {
            Ok(_) => println!("es FTL: bundle add OK"),
            Err(errors) => panic!("es FTL bundle add errors: {:?}", errors),
        }
    }
}
