#![cfg_attr(docsrs, feature(doc_cfg))]

//! mdfrier - Deep fry markdown for [mdfried](https://crates.io/crates/mdfried).
//!
//! This crate's goal is to render markdown as close to the source text as possible, while also
//! wrapping and also allowing for mapping to a custom style.
//!
//! 1. Parse into raw lines with nodes.
//! 2. Map (or strip) the node's markdown decorator symbols but preserve some internal marker.
//! 3. Wrap the lines of nodes to a maximum width.
//! 4. Apply styles such as emphasis or color.
//!
//! At step 4, the users of this library will typically convert the wrapped lines of nodes with
//! their style information to whatever the target is: ANSI escape sequences, or whatever some
//! their library expects.
//!
//! There is a `ratatui` feature that enables the [`ratatui`] module, which does exactly this, for
//! [ratatui](https://ratatui.rs).
//!
//! The [`Mapper`] trait controls decorator symbols (e.g., blockquote bar, link brackets).
//! The optional `ratatui` feature provides the [`ratatui::Theme`] trait that combines [`Mapper`]
//! with [`ratatui::style::Style`](https://docs.rs/ratatui/latest/ratatui/style/struct.Style.html) conversion.
//!
//! # Examples
//!
//! [`StyledMapper`] is the default goal of this crate. It heavily maps markdown symbols, and
//! strips many, with the intention of adding syles (color, bold, italics...) later, after wrapping.
//! That is, it does not "stylize" the markdown, but is intented *for* stylizing later.
//!
//! The styles should be applied when iterating over the [`Line`]'s [`Span`]s.
//! ```
//! use mdfrier::{MdFrier, Line, Span, Mapper, Modifier, DefaultMapper, StyledMapper};
//!
//! let mut frier = MdFrier::new().unwrap();
//!
//! // StyledMapper removes decorators (for use with colors/bold/italic styling)
//! let text: String = frier.parse(80, "*emphasis* and **strong**", &StyledMapper).unwrap()
//!     .flat_map(|l: Line| l.spans.into_iter().map(|s: Span|
//!         if s.modifiers.contains(Modifier::Emphasis) {
//!             format!("\033[31m{}\033[0m", s.content)
//!         } else if s.modifiers.contains(Modifier::StrongEmphasis) {
//!             format!("\033[33m{}\033[0m", s.content)
//!         } else {
//!             s.content
//!         }
//!     ))
//!     .collect();
//! assert_eq!(text, "\033[31memphasis\033[0m and \033[33mstrong\033[0m");
//! ```
//!
//! A custom mapper should implement the [`Mapper`] trait. For example, here we replace some
//! markdown delimiters with fancy symbols.
//! ```
//! use mdfrier::{MdFrier, Mapper};
//!
//! struct FancyMapper;
//! impl Mapper for FancyMapper {
//!     fn emphasis_open(&self) -> &str { "♥" }
//!     fn emphasis_close(&self) -> &str { "♥" }
//!     fn strong_open(&self) -> &str { "✦" }
//!     fn strong_close(&self) -> &str { "✦" }
//!     fn blockquote_bar(&self) -> &str { "➤ " }
//! }
//!
//! let mut frier = MdFrier::new().unwrap();
//!
//! let lines = frier.parse(80, "Hello *world*!\n\n> Quote\n\n**Bold**", &FancyMapper).unwrap();
//! let mut output = String::new();
//! for line in lines {
//!     for span in line.spans {
//!         output.push_str(&span.content);
//!     }
//!     output.push('\n');
//! }
//! assert_eq!(output, "Hello ♥world♥!\n\n➤ Quote\n\n✦Bold✦\n");
//! ```
//!
//! A [`DefaultMapper`] exists, which *could* be used to only style, preserving the markdown
//! content. It's used only for unit tests.
//! Note that it would be much more efficient to use the
//! [`tree-sitter-md`](https://crates.io/crates/tree-sitter-md) crate directly instead,
//! since it operates with byte-ranges of the original text. Think editor syntax highlighting.
//! ```
//! use mdfrier::{MdFrier, DefaultMapper};
//!
//! let mut frier = MdFrier::new().unwrap();
//!
//! let text: String = frier.parse(80, "*emphasis* and **strong**", &DefaultMapper).unwrap()
//!     .flat_map(|l| l.spans.into_iter().map(|s| s.content))
//!     .collect();
//! assert_eq!(text, "*emphasis* and **strong**");
//!
//! ```

mod lines;
pub mod link_tracker;
pub mod mapper;
mod markdown;
mod wrap;

#[cfg(feature = "ratatui")]
pub mod ratatui;

use std::fmt::Display;

use tree_sitter::Parser;

pub use lines::LineIterator;
pub use mapper::{DefaultMapper, Mapper, StyledMapper};
pub use markdown::BulletStyle;
pub use markdown::{Modifier, SourceContent, Span};

use crate::link_tracker::TrackedUrl;
use crate::markdown::MdIterator;

// ============================================================================
// Public output types
// ============================================================================

/// A single output line from the markdown parser.
///
/// This is the final, flattened representation with all decorators applied
/// and nesting converted to prefix spans.
#[derive(Debug, PartialEq)]
pub struct Line {
    /// The text spans making up this line, including any prefix spans
    /// (blockquote bars, list markers) that were added from nesting.
    pub spans: Vec<Span>,
    /// The kind of content this line represents.
    pub kind: LineKind,
    /// Any links and images found *ending* on this line.
    pub urls: Vec<TrackedUrl>,
}

/// The kind of content a line represents.
#[derive(Debug, Clone, PartialEq)]
pub enum LineKind {
    /// Regular text paragraph.
    Paragraph,
    /// Header line with tier (1-6).
    Header(u8),
    /// Code block line with language.
    CodeBlock { language: String },
    /// Horizontal rule (content is in spans).
    HorizontalRule,
    /// Table data row.
    TableRow { is_header: bool },
    /// Table border/separator.
    TableBorder,
    /// Image reference.
    Image(MarkdownLink),
    /// Link reference definitions, e.g. `[reference]: http://example.com`, has `LinkDescription`
    /// and `LinkUrl` [`Modifier`]s, respectively.
    LinkReferenceDefinitions,
}

#[cfg(test)]
impl Display for Line {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.spans
                .iter()
                .map(|s| s.content.clone())
                .collect::<Vec<String>>()
                .join("")
        )
    }
}

#[cfg(test)]
impl Line {
    fn to_strings<T>(lines: T) -> Vec<String>
    where
        T: IntoIterator,
        T::Item: Display,
    {
        lines
            .into_iter()
            .map(|s| s.to_string())
            .collect::<Vec<String>>()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct MarkdownLink {
    pub url: String,
    pub description: String,
}

impl Display for MarkdownLink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}]({})", self.description, self.url)
    }
}

/// Failed to parse markdown.
#[derive(Debug)]
pub struct MarkdownParseError;

impl Display for MarkdownParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Failed to parse markdown")
    }
}

impl std::error::Error for MarkdownParseError {}

/// The main markdown parser struct.
///
/// Wraps tree-sitter parsers and provides a simple interface for parsing
/// markdown text into lines.
pub struct MdFrier {
    parser: Parser,
    inline_parser: Parser,
}

impl MdFrier {
    /// Create a new MdFrier instance.
    pub fn new() -> Result<Self, MarkdownParseError> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_md::LANGUAGE.into())
            .ok()
            .ok_or(MarkdownParseError)?;

        let mut inline_parser = Parser::new();
        inline_parser
            .set_language(&tree_sitter_md::INLINE_LANGUAGE.into())
            .ok()
            .ok_or(MarkdownParseError)?;

        Ok(Self {
            parser,
            inline_parser,
        })
    }

    /// Parse markdown text and return an iterator of `Line` items.
    ///
    /// The mapper controls how decorators are rendered (link brackets,
    /// blockquote bars, list markers, etc.). Use `DefaultMapper` for
    /// plain ASCII output, or implement your own `Mapper` for custom symbols.
    ///
    /// # Arguments
    ///
    /// * `width` - The terminal width for line wrapping
    /// * `text` - The markdown text to parse
    /// * `mapper` - The mapper to use for content transformation
    pub fn parse<'a, M: Mapper>(
        &'a mut self,
        width: u16,
        text: &'a str,
        mapper: &'a M,
    ) -> Result<LineIterator<'a, M>, MarkdownParseError> {
        let tree = self.parser.parse(text, None).ok_or(MarkdownParseError)?;
        let mut iter = MdIterator::new(tree, &mut self.inline_parser, text);
        iter.preserve_list_ordinals(mapper.preserve_list_ordinals());
        Ok(LineIterator::new(iter, width, mapper))
    }
}

#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    /// Convert MdLines to a string representation for testing.
    /// With the new flat API, all prefix spans are included in spans.
    fn lines_to_string(lines: &[Line]) -> String {
        lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|s| s.content.as_str())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn parse_simple_text() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "Hello world!", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        assert_eq!(line.spans.len(), 1);
        assert_eq!(line.spans[0].content, "Hello world!");
    }

    #[test]
    fn parse_styled_text() {
        let mut frier = MdFrier::new().unwrap();
        // DefaultMapper preserves decorators around emphasis
        let lines: Vec<_> = frier
            .parse(80, "Hello *world*!", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        // Spans: "Hello " + "*" (open) + "world" (emphasis) + "*" (close) + "!"
        assert_eq!(line.spans.len(), 5);
        assert_eq!(line.spans[0].content, "Hello ");
        assert_eq!(line.spans[1].content, "*");
        assert!(line.spans[1].modifiers.contains(Modifier::EmphasisWrapper));
        assert_eq!(line.spans[2].content, "world");
        assert!(line.spans[2].modifiers.contains(Modifier::Emphasis));
        assert_eq!(line.spans[3].content, "*");
        assert!(line.spans[3].modifiers.contains(Modifier::EmphasisWrapper));
        assert_eq!(line.spans[4].content, "!");
    }

    #[test]
    fn parse_header() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "# Hello\n", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        assert!(matches!(line.kind, LineKind::Header(1)));
    }

    #[test]
    fn parse_code_block() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "```rust\nlet x = 1;\n```\n", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        assert!(matches!(line.kind, LineKind::CodeBlock { .. }));
        // First span is the code content
        assert!(line.spans[0].content.starts_with("let x = 1;"));
    }

    #[test]
    fn parse_blockquote() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "> Hello world", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        // With flat API, first span should be the blockquote bar
        assert!(line.spans[0].modifiers.contains(Modifier::BlockquoteBar));
        assert_eq!(line.spans[0].content, "> ");
    }

    #[test]
    fn parse_list() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "- Item 1\n- Item 2", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn paragraph_breaks() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(10, "longline1\nlongline2", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].spans[0].content, "longline1");
        assert_eq!(lines[1].spans[0].content, "longline2");
    }

    #[test]
    fn soft_break_with_styling() {
        let mut frier = MdFrier::new().unwrap();
        // DefaultMapper preserves decorators
        let lines: Vec<_> = frier
            .parse(80, "This\n*is* a test.", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].spans[0].content, "This");
        assert_eq!(lines[0].spans[1].content, " ");
        // Second line: "*" (open) + "is" (emphasis) + "*" (close) + " a test."
        assert_eq!(lines[0].spans[2].content, "*");
        assert!(
            lines[0].spans[2]
                .modifiers
                .contains(Modifier::EmphasisWrapper)
        );
        assert_eq!(lines[0].spans[3].content, "is");
        assert!(lines[0].spans[3].modifiers.contains(Modifier::Emphasis));
        assert_eq!(lines[0].spans[4].content, "*");
        assert!(
            lines[0].spans[4]
                .modifiers
                .contains(Modifier::EmphasisWrapper)
        );
    }

    #[test]
    fn code_block_spacing() {
        let input = "Paragraph before.
```rust
let x = 1;
```
Paragraph after.";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn code_block_before_list_spacing() {
        let input = "```rust
let x = 1;
```
- list item";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn separate_blockquotes_have_blank_lines() {
        let input = r#"> Blockquotes are very handy in email to emulate reply text.
> 
> This line is part of the same quote.

Quote break.

> This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote.

> Blockquotes can also be nested...
>> ...by using additional greater-than signs right next to each other...
> > > ...or with spaces between arrows."#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn bare_url_line_broken() {
        let mut frier = MdFrier::new().unwrap();
        let lines = frier
            .parse(15, "See https://example.com/path ok?", &DefaultMapper)
            .unwrap();

        assert_eq!(
            lines.map(|line| line.spans).collect::<Vec<Vec<Span>>>(),
            vec![
                vec![Span::from("See")],
                vec![
                    Span::with("https://", Modifier::BareLink | Modifier::LinkURL),
                    Span::with("       ", Modifier::BareLink | Modifier::LinkURL),
                ],
                vec![
                    Span::with("example.com/", Modifier::BareLink | Modifier::LinkURL),
                    Span::with("   ", Modifier::BareLink | Modifier::LinkURL),
                ],
                vec![
                    Span::with("path", Modifier::BareLink | Modifier::LinkURL),
                    Span::from(" ok?"),
                ],
            ]
        );
    }

    #[test]
    fn list_marker_mapping() {
        let input = r#"1. First ordered list item
2. Another item
   - Unordered sub-list.
3. Actual numbers don't matter, just that it's a number
   1. Ordered sub-list
4. And another item.

- Create a list by starting a line with `+`, `-`, or `*`
- Sub-lists are made by indenting 2 spaces:
  - Marker character change forces new list start:
    - Ac tristique libero volutpat at
    * Facilisis in pretium nisl aliquet
    - Nulla volutpat aliquam velit
  - Task lists
    - [x] Finish my changes
    - [ ] Push my commits to GitHub
    - [ ] Open a pull request
    - [x] @mentions, #refs, [links](), **formatting**, and <del>tags</del> supported
    - [x] list syntax required (any unordered or ordered list supported)
    - [ ] this is a complete item with a long line that should definitely 100% get wrapped at some point
    - [ ] this is an incomplete item
+ Very easy!
"#;

        let mut frier = MdFrier::new().unwrap();
        struct RomanListMapper;
        impl Mapper for RomanListMapper {
            fn ordered_marker(&self, num: u32) -> String {
                match num {
                    1 => "I.   ",
                    2 => "II.  ",
                    3 => "III. ",
                    4 => "IV.  ",
                    _ => "?.   ",
                }
                .to_owned()
            }
            fn unordered_bullet(&self, _style: BulletStyle) -> &str {
                "✝ "
            }
            fn task_checked(&self) -> &str {
                "☒ "
            }
            fn task_unchecked(&self) -> &str {
                "☐ "
            }
        }
        let mapper = RomanListMapper {};
        let lines: Vec<_> = frier.parse(80, input, &mapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn list_preserve_formatting() {
        let input = r#"1. First ordered list item
2. Another item
   - Unordered sub-list.
3. Actual numbers don't matter, just that it's a number
   1. Ordered sub-list
4. And another item.

   You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).

   To have a line break without a paragraph, you will need to use two trailing spaces.
   Note that this line is separate, but within the same paragraph.
   (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)

- Unordered list can use asterisks
  And can also have continuations.

* Or minuses

- Or pluses

1. Make my changes
   1. Fix bug
   2. Improve formatting
      - Make the headings bigger
2. Push my commits to GitHub
3. Open a pull request
   - Describe my changes
   - Mention all the members of my team
     - Ask for feedback

- Create a list by starting a line with `+`, `-`, or `*`
- Sub-lists are made by indenting 2 spaces:
  - Marker character change forces new list start:
    - Ac tristique libero volutpat at
    * Facilisis in pretium nisl aliquet
    - Nulla volutpat aliquam velit
  - Task lists
    - [x] Finish my changes
    - [ ] Push my commits to GitHub
    - [ ] Open a pull request
    - [x] @mentions, #refs, [links](), **formatting**, and <del>tags</del> supported
    - [x] list syntax required (any unordered or ordered list supported)
    - [ ] this is a complete item
    - [ ] this is an incomplete item
- Very easy!
"#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn list_preserve_continuations() {
        let input = r#"1. First ordered list item
2. Another item  

   Continuation of item.
   Carry on.

   Further continuation.
3. Last item
"#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    struct PreserveMapper;
    impl Mapper for PreserveMapper {
        fn preserve_list_ordinals(&self) -> bool {
            true
        }
    }

    #[test]
    fn ordinals_preserved() {
        // preserve_list_ordinals = true: source numbers are kept exactly as written
        let input = "1. a\n3. b\n5. c\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &PreserveMapper).unwrap().collect();
        assert_eq!(lines_to_string(&lines), "1. a\n3. b\n5. c");
    }

    #[test]
    fn ordinals_preserved_nested() {
        // preserve mode must not renumber items in nested structures
        let input = "3. a\n   - inner\n7. b\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &PreserveMapper).unwrap().collect();
        assert_eq!(lines_to_string(&lines), "3. a\n   - inner\n7. b");
    }

    #[test]
    fn ordinals_sequential_from_1() {
        // Non-sequential source numbers are renumbered starting from the first item's number
        let input = "1. a\n3. b\n5. c\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        assert_eq!(lines_to_string(&lines), "1. a\n2. b\n3. c");
    }

    #[test]
    fn ordinals_sequential_from_first() {
        // Renumbering starts from the first item's number, not always 1
        let input = "2. a\n7. b\n4. c\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        assert_eq!(lines_to_string(&lines), "2. a\n3. b\n4. c");
    }

    #[test]
    fn ordinals_sequential_nested() {
        // Each nested ordered list has its own counter independent of the outer list.
        // Note: tree-sitter-markdown only recognises a tight nested ordered sub-list when
        // it starts at 1. A sub-list starting at any other number is parsed as paragraph
        // continuation text of the parent item, so we use 1 here to get a real sub-list.
        let input = "3. a\n   1. inner-a\n   9. inner-b\n7. b\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        // inner 9 → 2 (continues from 1), outer 7 → 4 (continues from 3)
        assert_eq!(
            lines_to_string(&lines),
            "3. a\n   1. inner-a\n   2. inner-b\n4. b"
        );
    }

    #[test]
    fn ordinals_sequential_nested_unordered() {
        // A nested unordered list must not reset the outer ordered counter.
        let input = "3. a\n   - inner-a\n   - inner-b\n7. b\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        // outer 7 → 4 (continues from 3, despite the nested unordered items)
        assert_eq!(
            lines_to_string(&lines),
            "3. a\n   - inner-a\n   - inner-b\n4. b"
        );
    }

    #[test]
    fn ordinals_complex_nested() {
        // Exercises sequential renumbering and preserve mode together across:
        // - an outer ordered list starting at a non-1 number
        // - a nested unordered sub-list (must not disturb the outer counter)
        // - a nested ordered sub-list with a non-sequential source item (9 → 2)
        // - a two-digit outer item (11 → 5)
        //
        // Inner ordered sub-list starts at 1 because tree-sitter-markdown parses
        // tight nested ordered sub-lists as paragraph continuation when they start
        // at any other number.
        let input = "\
3. outer-a
   - unordered-1
   - unordered-2
7. outer-b
   1. inner-1
   9. inner-2
11. outer-c
";
        let mut frier = MdFrier::new().unwrap();

        let seq_lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        assert_eq!(
            lines_to_string(&seq_lines),
            "3. outer-a\n   - unordered-1\n   - unordered-2\n4. outer-b\n   1. inner-1\n   2. inner-2\n5. outer-c",
        );

        let pre_lines: Vec<_> = frier.parse(80, input, &PreserveMapper).unwrap().collect();
        assert_eq!(
            lines_to_string(&pre_lines),
            "3. outer-a\n   - unordered-1\n   - unordered-2\n7. outer-b\n   1. inner-1\n   9. inner-2\n11. outer-c",
        );
    }

    #[test]
    fn code_block_wrapping() {
        // Test that code blocks wrap at width boundary
        let input = "```\nabcdefghij\n```\n";

        let mut frier = MdFrier::new().unwrap();
        // Width of 5 should wrap "abcdefghij" into two lines
        let lines: Vec<_> = frier.parse(5, input, &DefaultMapper).unwrap().collect();
        assert_eq!(lines.len(), 2);
        // First line should be 5 chars
        assert_eq!(lines[0].spans[0].content, "abcde");
        // Second line should be remaining 5 chars
        assert_eq!(lines[1].spans[0].content, "fghij");
    }

    #[test]
    fn code_block_no_wrap_when_fits() {
        // Test that code blocks don't wrap when they fit
        let input = "```\nabcde\n```\n";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(5, input, &DefaultMapper).unwrap().collect();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].spans[0].content, "abcde");
    }

    #[test]
    fn hide_urls() {
        let mut frier = MdFrier::new().unwrap();
        struct HideUrlsMapper;
        impl Mapper for HideUrlsMapper {
            fn hide_urls(&self) -> bool {
                true
            }
        }
        let mapper = HideUrlsMapper {};
        let lines: Vec<_> = frier
            .parse(80, "[desc](https://url)", &mapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        assert_eq!(
            lines[0].spans,
            vec![
                Span::with("[", Modifier::Link | Modifier::LinkDescriptionWrapper),
                Span::with("desc", Modifier::Link | Modifier::LinkDescription,),
                Span::with("]", Modifier::Link | Modifier::LinkDescriptionWrapper),
                Span::with("", Modifier::Link | Modifier::LinkURLWrapper,),
                Span::with("https://url", Modifier::Link | Modifier::LinkURL),
                Span::with("", Modifier::Link | Modifier::LinkURLWrapper,),
            ]
        );
    }

    #[test]
    fn inline_image_surrounding_text() {
        let input = r#"This a paragraph.  
Here we have an "inline" image, ![inline](./notfound.img), and trailing text.  
Should be split up nicely.
"#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn html() {
        let input = r#"<div style="color: green">
    I want to put in HTML in markdown for some reason.
</div>
"#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn wrapping_indented_list_continuation() {
        let input = "\
- Mermaid diagram rendering.  
  A code block annotated as `mermaid` gets rendered either via builtin `mermaid-rs-renderer` (can
  be disabled with the `mermaid` feature), or via external command in config,
  e.g. `mermaid = \"mmdc -i - -o - -e png\"`.";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(88, input, &StyledMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        assert_eq!(
            output,
            "- Mermaid diagram rendering.\
\n  A code block annotated as mermaid gets rendered either via builtin mermaid-rs-renderer\
\n  (can be disabled with the mermaid feature), or via external command in config, e.g.\
\n  mermaid = \"mmdc -i - -o - -e png\"."
        );
    }

    #[test]
    fn non_wrapping_simple_list_items() {
        let input = "\
* A
  * B
  * C";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(88, input, &StyledMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        assert_eq!(
            output,
            "* A\
\n  * B\
\n  * C"
        );
    }

    #[test]
    fn wrapping_indented_sublist_inline_code() {
        let input = "\
* Rust cargo: `cargo install mdfried`
  * Needs a chafa package with development headers, usually called something like `libchafa-dev`, `libchafa-devel`, or just `libchafa`, or even just `chafa`.";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(88, input, &StyledMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        assert_eq!(
            output,
            "* Rust cargo: cargo install mdfried\
\n  * Needs a chafa package with development headers, usually called something like\
\n    libchafa-dev, libchafa-devel, or just libchafa, or even just chafa."
        );
    }

    #[test]
    fn nested_image_link() {
        let input = "[![test image](http://example.com/image.png)](http://example.com/link)";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();

        assert_eq!(
            lines[0].spans,
            vec![
                Span::with("[", Modifier::Link | Modifier::LinkDescriptionWrapper),
                Span::with(
                    "![",
                    Modifier::Link | Modifier::LinkDescription | Modifier::Image
                ),
                Span::with(
                    "test image",
                    Modifier::Link | Modifier::LinkDescription | Modifier::Image
                ),
                Span::with(
                    "](",
                    Modifier::Link | Modifier::LinkDescription | Modifier::Image
                ),
                Span::with(
                    "http://example.com/image.png",
                    Modifier::Link
                        | Modifier::LinkDescription
                        | Modifier::LinkURL
                        | Modifier::Image,
                ),
                Span::with(
                    ")",
                    Modifier::Link | Modifier::LinkDescription | Modifier::Image
                ),
                Span::with("]", Modifier::Link | Modifier::LinkDescriptionWrapper),
                Span::with("(", Modifier::Link | Modifier::LinkURLWrapper,),
                Span::with(
                    "http://example.com/link",
                    Modifier::Link | Modifier::LinkURL
                ),
                Span::with(")", Modifier::Link | Modifier::LinkURLWrapper,),
            ]
        );
    }
}
