//! Minijinja `Environment` setup for HTMX page rendering.
//!
//! Call [`setup`] on an `Environment` after creating it and configuring a
//! loader. This registers common filters and sets HTML auto-escape so all
//! `{{ expr }}` outputs are escaped by default; use the `|safe` filter for
//! pre-rendered HTML content.

use minijinja::Environment;

/// Register framework filters and configure HTML auto-escape on `env`.
///
/// Must be called before the first render. The caller is responsible for
/// attaching a loader (e.g. `env.set_loader(minijinja::path_loader(dir))`).
pub fn setup(env: &mut Environment) {
    env.set_auto_escape_callback(|_| minijinja::AutoEscape::Html);
    env.add_filter("truncate_words", filter_truncate_words);
    env.add_filter("slugify", filter_slugify);
}

fn filter_truncate_words(
    value: &str,
    args: &[minijinja::Value],
) -> Result<String, minijinja::Error> {
    let max: usize = args.first().and_then(|v| v.as_usize()).unwrap_or(30);
    let words: Vec<&str> = value.split_whitespace().collect();
    if words.len() <= max {
        return Ok(value.to_string());
    }
    Ok(format!("{} …", words[..max].join(" ")))
}

fn filter_slugify(value: &str, _args: &[minijinja::Value]) -> Result<String, minijinja::Error> {
    let slug = value
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect::<String>();
    // Collapse consecutive dashes and strip leading/trailing.
    let slug = slug
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-");
    Ok(slug)
}
