use crate::ui::theme::pal;
use rune::Span;

pub fn spans(text: &str, ghost: Option<(usize, usize)>) -> Vec<Span> {
    let p = pal();
    let (mut out, mut pos, mut fence) = (vec![], 0, false);
    for line in text.split_inclusive('\n') {
        let body = line.trim_end_matches('\n');
        let t = body.trim_start();
        let heading = !fence && t.starts_with('#');
        let muted = if t.starts_with("```") {
            fence = !fence;
            true
        } else {
            fence || t.starts_with("![") || t.starts_with("[![") || t.starts_with('>')
        };
        let span = Span::new(pos, pos + body.len());
        if !body.is_empty() && heading {
            out.push(span.color(p.strong).weight(500.0));
        } else if !body.is_empty() && muted {
            out.push(span.color(p.muted));
        }

        pos += line.len();
    }
    if let Some((a, b)) = ghost.filter(|(a, b)| a < b && *b <= text.len()) {
        out.push(Span::new(a, b).color(p.faint).italic());
    }
    out
}

#[cfg(test)]
mod tests {
    #[test]
    fn styles_headings_fences_and_images() {
        let s = super::spans(
            "# Title\ntext\n```\ncode\n```\n![a](b.png)\n",
            Some((8, 12)),
        );
        let ranges: Vec<(u32, u32)> = s.iter().map(|s| (s.start, s.end)).collect();
        assert_eq!(
            ranges,
            vec![(0, 7), (13, 16), (17, 21), (22, 25), (26, 37), (8, 12)]
        );
    }
}
