use std::{borrow::Cow, fmt::Write};

use tracing::instrument;

use crate::{config::Config, state::FileId, vfs::VPath};

use super::{navmap::NavigationMap, EscapeAttribute};

#[instrument(skip(config, navigation_map))]
pub fn breadcrumbs_to_html(
    config: &Config,
    navigation_map: &NavigationMap,
    file_id: FileId,
) -> String {
    let mut s = String::new();

    if let Some(path) = navigation_map.paths.get(&file_id) {
        for (i, element) in path.iter().enumerate() {
            // Skip the index because it's implied by the logo on the left.
            if &**element != VPath::new_const("index") {
                s.push_str("<li class=\"breadcrumb\">");
                {
                    let short_element = path
                        .get(i - 1)
                        .map(|p| format!("{p}/"))
                        .and_then(|prefix| {
                            element
                                .as_str()
                                .strip_prefix(prefix.as_str())
                                .map(Cow::Borrowed)
                        })
                        .unwrap_or_else(|| Cow::Owned(format!("/{element}")));
                    write!(
                        s,
                        "<a href=\"{site}/{element}\">{short_element}</a>",
                        site = EscapeAttribute(&config.site),
                        element = EscapeAttribute(element.as_str())
                    )
                    .unwrap();
                }
                s.push_str("</li>");
            }
        }
    }

    s
}
