mod links;
mod render;
mod scanner;

use crate::ParseOptions;
use crate::entities;
use crate::html::escape_html_into;
use rustc_hash::FxHashMap;
use std::borrow::Cow;

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct LinkReference {
    pub href: String,
    pub title: Option<String>,
}

pub(crate) type LinkRefMap = FxHashMap<String, LinkReference>;

pub(crate) fn normalize_reference_label(label: &str) -> Cow<'_, str> {
    let trimmed = label.trim();
    let bytes = trimmed.as_bytes();

    {
        let mut simple = true;
        let mut prev_space = false;
        for &b in bytes {
            if b >= b'A' && b <= b'Z' {
                simple = false;
                break;
            }
            if b == b' ' {
                if prev_space {
                    simple = false;
                    break;
                }
                prev_space = true;
            } else if b == b'\t' || b == b'\n' || b == b'\r' || b >= 0x80 {
                simple = false;
                break;
            } else {
                prev_space = false;
            }
        }
        if simple {
            return Cow::Borrowed(trimmed);
        }
    }

    let mut out = String::with_capacity(trimmed.len());
    let mut in_space = false;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b < 0x80 {
            if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' {
                if !in_space {
                    out.push(' ');
                    in_space = true;
                }
                i += 1;
            } else {
                out.push(if b >= b'A' && b <= b'Z' {
                    (b + 32) as char
                } else {
                    b as char
                });
                in_space = false;
                i += 1;
            }
        } else {
            let ch = &trimmed[i..];
            let c = ch.chars().next().unwrap();
            let clen = c.len_utf8();
            if c.is_whitespace() {
                if !in_space {
                    out.push(' ');
                    in_space = true;
                }
            } else {
                match c {
                    'ß' | 'ẞ' => out.push_str("ss"),
                    _ => {
                        for lc in c.to_lowercase() {
                            out.push(lc);
                        }
                    }
                }
                in_space = false;
            }
            i += clen;
        }
    }
    Cow::Owned(out)
}

static ASCII_CHAR_STRS: [&str; 128] = {
    const fn make() -> [&'static str; 128] {
        [
            "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\x09", "\x0A",
            "\x0B", "\x0C", "\x0D", "\x0E", "\x0F", "\x10", "\x11", "\x12", "\x13", "\x14", "\x15",
            "\x16", "\x17", "\x18", "\x19", "\x1A", "\x1B", "\x1C", "\x1D", "\x1E", "\x1F", " ",
            "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1",
            "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B",
            "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
            "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d",
            "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
            "v", "w", "x", "y", "z", "{", "|", "}", "~", "\x7F",
        ]
    }
    make()
};

const SPECIAL_ANY: u8 = 1;
const SPECIAL_COMPLEX: u8 = 2;

static SPECIAL: [u8; 256] = {
    let mut t = [0u8; 256];
    t[b'*' as usize] = SPECIAL_ANY;
    t[b'_' as usize] = SPECIAL_ANY;
    let both = SPECIAL_ANY | SPECIAL_COMPLEX;
    t[b'\\' as usize] = both;
    t[b'`' as usize] = both;
    t[b'!' as usize] = both;
    t[b'[' as usize] = both;
    t[b']' as usize] = both;
    t[b'<' as usize] = both;
    t[b'&' as usize] = both;
    t[b'\n' as usize] = both;
    t[b'~' as usize] = both;
    t[b'=' as usize] = both;
    t[b'+' as usize] = both;
    t[b':' as usize] = both;
    t[b'@' as usize] = both;
    t
};

#[inline]
pub(crate) fn parse_inline_pass(
    out: &mut String,
    raw: &str,
    refs: &LinkRefMap,
    opts: &ParseOptions,
    bufs: &mut InlineBuffers,
) {
    let bytes = raw.as_bytes();

    let mut first_pos = usize::MAX;
    let mut complex_mask: u8 = 0;
    for (i, &b) in bytes.iter().enumerate() {
        let s = SPECIAL[b as usize];
        if s == 0 {
            continue;
        }
        if first_pos == usize::MAX {
            first_pos = i;
        }
        if s & SPECIAL_COMPLEX != 0 {
            if b == b'\n' || b == b'\\' {
                complex_mask |= 1;
            } else {
                complex_mask = 3;
                break;
            }
        }
    }
    if first_pos == usize::MAX {
        escape_html_into(out, raw);
        return;
    }

    let first_byte = bytes[first_pos];
    if (first_byte == b'*' || first_byte == b'_') && complex_mask == 0 {
        emit_emphasis_only(out, raw, bytes);
        return;
    }

    if complex_mask == 1 {
        emit_breaks_and_emphasis(out, raw, bytes, opts);
        return;
    }

    out.reserve(raw.len());
    if bufs.items.capacity() == 0 {
        bufs.items.reserve(raw.len() / 20 + 4);
    }
    let mut p = InlineScanner::new_with_bufs(raw, refs, opts, bufs);
    p.scan_all();
    if !p.delims.is_empty() {
        p.process_emphasis(0);
    }
    p.render_to_html(out, opts);
}

#[derive(Clone, Copy)]
struct EmDelim {
    orig_start: u32,
    orig_end: u32,
    cur_start: u32,
    cur_end: u32,
    marker: u8,
    can_open: bool,
    can_close: bool,
    active: bool,
    open_em: [u8; 4],
    open_em_len: u8,
    close_em: [u8; 4],
    close_em_len: u8,
}

const EMPTY_DELIM: EmDelim = EmDelim {
    orig_start: 0,
    orig_end: 0,
    cur_start: 0,
    cur_end: 0,
    marker: 0,
    can_open: false,
    can_close: false,
    active: true,
    open_em: [0; 4],
    open_em_len: 0,
    close_em: [0; 4],
    close_em_len: 0,
};

/// Shared emphasis processing: resolve opener/closer pairs in a slice of EmDelim.
#[inline(never)]
fn process_em_delims(delims: &mut [EmDelim]) {
    let mut closer_idx = 0usize;
    while closer_idx < delims.len() {
        if !delims[closer_idx].active
            || !delims[closer_idx].can_close
            || delims[closer_idx].cur_end == delims[closer_idx].cur_start
        {
            closer_idx += 1;
            continue;
        }
        let cmarker = delims[closer_idx].marker;
        let ccount = (delims[closer_idx].cur_end - delims[closer_idx].cur_start) as u16;

        let mut found = false;
        let mut oi = closer_idx;
        while oi > 0 {
            oi -= 1;
            if !delims[oi].active || delims[oi].marker != cmarker || !delims[oi].can_open {
                continue;
            }
            let ocount = (delims[oi].cur_end - delims[oi].cur_start) as u16;
            if ocount == 0 {
                continue;
            }
            if (delims[oi].can_close || delims[closer_idx].can_open)
                && (ocount + ccount) % 3 == 0
                && (ocount % 3 != 0 || ccount % 3 != 0)
            {
                continue;
            }
            let use_count: u16 = if ocount >= 2 && ccount >= 2 { 2 } else { 1 };
            let tag = use_count as u8;

            delims[oi].cur_end -= use_count as u32;
            let idx = delims[oi].open_em_len as usize;
            if idx < 4 {
                delims[oi].open_em[idx] = tag;
                delims[oi].open_em_len += 1;
            }

            delims[closer_idx].cur_start += use_count as u32;
            let idx = delims[closer_idx].close_em_len as usize;
            if idx < 4 {
                delims[closer_idx].close_em[idx] = tag;
                delims[closer_idx].close_em_len += 1;
            }

            for k in (oi + 1)..closer_idx {
                delims[k].active = false;
            }

            if delims[oi].cur_end == delims[oi].cur_start {
                delims[oi].active = false;
            }
            if delims[closer_idx].cur_end == delims[closer_idx].cur_start {
                delims[closer_idx].active = false;
            }

            found = true;
            break;
        }
        if !found {
            closer_idx += 1;
        }
    }
}

/// Render emphasis tags for a delimiter.
#[inline(always)]
fn render_em_delim(out: &mut String, d: &EmDelim) {
    for j in 0..d.close_em_len as usize {
        if d.close_em[j] == 2 {
            out.push_str("</strong>");
        } else {
            out.push_str("</em>");
        }
    }
    if d.cur_start < d.cur_end {
        let marker = d.marker as char;
        for _ in 0..(d.cur_end - d.cur_start) {
            out.push(marker);
        }
    }
    for j in (0..d.open_em_len as usize).rev() {
        if d.open_em[j] == 2 {
            out.push_str("<strong>");
        } else {
            out.push_str("<em>");
        }
    }
}

struct EmDelimBuf {
    stack: [EmDelim; 16],
    heap: Vec<EmDelim>,
    count: usize,
}

impl EmDelimBuf {
    #[inline(always)]
    fn new() -> Self {
        Self {
            stack: [EMPTY_DELIM; 16],
            heap: Vec::new(),
            count: 0,
        }
    }
    #[inline(always)]
    fn push(&mut self, d: EmDelim) {
        if self.count < 16 {
            self.stack[self.count] = d;
        } else {
            if self.heap.is_empty() {
                self.heap.extend_from_slice(&self.stack);
            }
            self.heap.push(d);
        }
        self.count += 1;
    }
    #[inline(always)]
    fn as_mut_slice(&mut self) -> &mut [EmDelim] {
        if self.count == 0 {
            &mut []
        } else if self.count <= 16 {
            &mut self.stack[..self.count]
        } else {
            &mut self.heap[..]
        }
    }
}

/// Scan emphasis delimiter runs, skipping backslash escapes.
fn scan_em_delims(raw: &str, bytes: &[u8], skip_escapes: bool) -> EmDelimBuf {
    let len = bytes.len();
    let mut buf = EmDelimBuf::new();
    let mut i = 0;
    while i < len {
        let b = bytes[i];
        if skip_escapes && b == b'\\' && i + 1 < len && crate::is_ascii_punctuation(bytes[i + 1]) {
            i += 2;
            continue;
        }
        if b == b'*' || b == b'_' {
            let run_start = i;
            while i < len && bytes[i] == b {
                i += 1;
            }
            let before = if run_start > 0 {
                char_before(raw, run_start)
            } else {
                ' '
            };
            let after = if i < len { char_at(raw, i) } else { ' ' };
            let (can_open, can_close) = flanking(b, before, after);
            buf.push(EmDelim {
                orig_start: run_start as u32,
                orig_end: i as u32,
                cur_start: run_start as u32,
                cur_end: i as u32,
                marker: b,
                can_open,
                can_close,
                active: true,
                open_em: [0; 4],
                open_em_len: 0,
                close_em: [0; 4],
                close_em_len: 0,
            });
        } else {
            i += 1;
        }
    }
    buf
}

fn emit_emphasis_only(out: &mut String, raw: &str, bytes: &[u8]) {
    let mut buf = scan_em_delims(raw, bytes, false);
    if buf.count == 0 {
        escape_html_into(out, raw);
        return;
    }
    let delims = buf.as_mut_slice();
    process_em_delims(delims);

    let mut text_pos = 0usize;
    for d in delims.iter() {
        if text_pos < d.orig_start as usize {
            escape_html_into(out, &raw[text_pos..d.orig_start as usize]);
        }
        render_em_delim(out, d);
        text_pos = d.orig_end as usize;
    }
    if text_pos < bytes.len() {
        escape_html_into(out, &raw[text_pos..]);
    }
}

/// Fast path for content with only emphasis markers, newlines, and backslash escapes.
fn emit_breaks_and_emphasis(out: &mut String, raw: &str, bytes: &[u8], opts: &ParseOptions) {
    let mut buf = scan_em_delims(raw, bytes, true);
    let delims = buf.as_mut_slice();
    if !delims.is_empty() {
        process_em_delims(delims);
    }

    let len = bytes.len();
    let mut text_pos = 0usize;
    let mut di = 0usize;

    while text_pos < len {
        let next_delim_pos = if di < delims.len() {
            delims[di].orig_start as usize
        } else {
            len
        };
        emit_text_with_breaks(out, raw, bytes, &mut text_pos, next_delim_pos, opts);

        if di < delims.len() && text_pos == delims[di].orig_start as usize {
            render_em_delim(out, &delims[di]);
            text_pos = delims[di].orig_end as usize;
            di += 1;
        }
    }
}

/// Emit text from bytes[text_pos..end], handling newlines and backslash escapes.
#[inline]
fn emit_text_with_breaks(
    out: &mut String,
    raw: &str,
    bytes: &[u8],
    text_pos: &mut usize,
    end: usize,
    opts: &ParseOptions,
) {
    let mut seg_start = *text_pos;
    let mut i = *text_pos;
    while i < end {
        let b = bytes[i];
        if b == b'\n' {
            let mut text_end = i;
            let is_hard = (i >= seg_start + 2 && bytes[i - 1] == b' ' && bytes[i - 2] == b' ')
                || (i > seg_start && bytes[i - 1] == b'\\');
            if is_hard && i > seg_start && bytes[i - 1] == b'\\' {
                text_end = i - 1;
            } else {
                while text_end > seg_start && bytes[text_end - 1] == b' ' {
                    text_end -= 1;
                }
            }
            if seg_start < text_end {
                escape_html_into(out, &raw[seg_start..text_end]);
            }
            if is_hard || opts.hard_breaks {
                out.push_str("<br />\n");
            } else {
                out.push('\n');
            }
            i += 1;
            seg_start = i;
        } else if b == b'\\' && i + 1 < end {
            let next = bytes[i + 1];
            if next == b'\n' {
                i += 1;
                continue;
            }
            if crate::is_ascii_punctuation(next) {
                if seg_start < i {
                    escape_html_into(out, &raw[seg_start..i]);
                }
                match next {
                    b'&' => out.push_str("&amp;"),
                    b'<' => out.push_str("&lt;"),
                    b'>' => out.push_str("&gt;"),
                    b'"' => out.push_str("&quot;"),
                    _ => out.push_str(&raw[i + 1..i + 2]),
                }
                i += 2;
                seg_start = i;
            } else {
                i += 1;
            }
        } else {
            i += 1;
        }
    }
    if seg_start < end {
        escape_html_into(out, &raw[seg_start..end]);
    }
    *text_pos = end;
}

pub(crate) struct InlineBuffers {
    items: Vec<InlineItem>,
    delims: Vec<usize>,
    brackets: Vec<BracketInfo>,
    links: Vec<LinkInfo>,
}

impl InlineBuffers {
    pub(crate) fn new() -> Self {
        Self {
            items: Vec::new(),
            delims: Vec::new(),
            brackets: Vec::new(),
            links: Vec::new(),
        }
    }
}

#[derive(Clone, Debug)]
struct SmallEmVec {
    data: [u8; 4],
    len: u8,
}

impl SmallEmVec {
    #[inline(always)]
    const fn new() -> Self {
        Self {
            data: [0; 4],
            len: 0,
        }
    }
    #[inline(always)]
    fn push(&mut self, val: u8) {
        if (self.len as usize) < 4 {
            self.data[self.len as usize] = val;
            self.len += 1;
        }
    }
    #[inline(always)]
    fn as_slice(&self) -> &[u8] {
        &self.data[..self.len as usize]
    }
}

#[derive(Clone, Debug)]
enum LinkDest {
    Range(u32, u32),
    Owned(String),
}

#[derive(Clone, Debug)]
struct LinkInfo {
    dest: LinkDest,
    title: Option<String>,
    is_image: bool,
}

#[derive(Clone, Debug)]
enum InlineItem {
    TextRange(usize, usize),
    TextOwned(String),
    TextStatic(&'static str),
    TextInline {
        buf: [u8; 8],
        len: u8,
    },
    RawHtml(usize, usize),
    /// Autolink: (content_start, content_end, is_email)
    Autolink(u32, u32, bool),
    Code(String),
    HardBreak,
    SoftBreak,
    DelimRun {
        kind: u8,
        count: u16,
        can_open: bool,
        can_close: bool,
        open_em: SmallEmVec,
        close_em: SmallEmVec,
    },
    BracketOpen {
        is_image: bool,
    },
    LinkStart(u16),
    LinkEnd,
}

#[derive(Clone, Debug)]
struct BracketInfo {
    item_idx: usize,
    is_image: bool,
    delim_bottom: usize,
    active: bool,
    text_pos: usize,
}

struct InlineScanner<'a> {
    input: &'a str,
    bytes: &'a [u8],
    pos: usize,
    refs: &'a LinkRefMap,
    opts: &'a ParseOptions,
    items: &'a mut Vec<InlineItem>,
    delims: &'a mut Vec<usize>,
    brackets: &'a mut Vec<BracketInfo>,
    links: &'a mut Vec<LinkInfo>,
}

impl<'a> InlineScanner<'a> {
    fn new_with_bufs(
        input: &'a str,
        refs: &'a LinkRefMap,
        opts: &'a ParseOptions,
        bufs: &'a mut InlineBuffers,
    ) -> Self {
        bufs.items.clear();
        bufs.delims.clear();
        bufs.brackets.clear();
        bufs.links.clear();
        Self {
            input,
            bytes: input.as_bytes(),
            pos: 0,
            refs,
            opts,
            items: &mut bufs.items,
            delims: &mut bufs.delims,
            brackets: &mut bufs.brackets,
            links: &mut bufs.links,
        }
    }
}

pub(super) use crate::is_ascii_punctuation;
pub(super) use crate::utf8_char_len;

#[inline(always)]
fn is_punctuation_char(c: char) -> bool {
    if c.is_ascii() {
        return is_ascii_punctuation(c as u8);
    }
    matches!(c as u32,
        0x00A0..=0x00BF | 0x2000..=0x206F | 0x2E00..=0x2E7F |
        0x3000..=0x303F | 0xFE30..=0xFE6F | 0xFF01..=0xFF0F |
        0xFF1A..=0xFF20 | 0xFF3B..=0xFF40 | 0xFF5B..=0xFF65 |
        0x2100..=0x214F | 0x2190..=0x21FF | 0x2200..=0x22FF |
        0x2300..=0x23FF | 0x2500..=0x257F | 0x25A0..=0x25FF |
        0x2600..=0x26FF | 0x2700..=0x27BF | 0x20A0..=0x20CF
    )
}

/// Compute flanking rules for a delimiter run.
/// Returns (can_open, can_close).
#[inline(always)]
fn flanking(marker: u8, before: char, after: char) -> (bool, bool) {
    let left_flanking = !after.is_whitespace()
        && (!is_punctuation_char(after) || before.is_whitespace() || is_punctuation_char(before));
    let right_flanking = !before.is_whitespace()
        && (!is_punctuation_char(before) || after.is_whitespace() || is_punctuation_char(after));
    if marker == b'_' {
        (
            left_flanking && (!right_flanking || is_punctuation_char(before)),
            right_flanking && (!left_flanking || is_punctuation_char(after)),
        )
    } else {
        (left_flanking, right_flanking)
    }
}

#[inline(always)]
fn char_before(s: &str, byte_pos: usize) -> char {
    if byte_pos == 0 {
        return ' ';
    }
    let bytes = s.as_bytes();
    let prev = bytes[byte_pos - 1];
    if prev < 0x80 {
        return prev as char;
    }
    let mut i = byte_pos - 1;
    while i > 0 && (bytes[i] & 0xC0) == 0x80 {
        i -= 1;
    }
    s[i..byte_pos].chars().next().unwrap_or(' ')
}

#[inline(always)]
fn char_at(s: &str, byte_pos: usize) -> char {
    if byte_pos >= s.len() {
        return ' ';
    }
    let b = s.as_bytes()[byte_pos];
    if b < 0x80 {
        return b as char;
    }
    let len = utf8_char_len(b);
    let end = (byte_pos + len).min(s.len());
    s[byte_pos..end].chars().next().unwrap_or(' ')
}

fn is_email_autolink(s: &str) -> bool {
    let bytes = s.as_bytes();
    let at = bytes.iter().position(|&b| b == b'@');
    let Some(at) = at else {
        return false;
    };
    if at == 0 || at + 1 >= bytes.len() {
        return false;
    }
    for &b in &bytes[..at] {
        if !(b.is_ascii_alphanumeric()
            || matches!(
                b,
                b'.' | b'!'
                    | b'#'
                    | b'$'
                    | b'%'
                    | b'&'
                    | b'\''
                    | b'*'
                    | b'+'
                    | b'/'
                    | b'='
                    | b'?'
                    | b'^'
                    | b'_'
                    | b'`'
                    | b'{'
                    | b'|'
                    | b'}'
                    | b'~'
                    | b'-'
            ))
        {
            return false;
        }
    }
    for &b in &bytes[at + 1..] {
        if !(b.is_ascii_alphanumeric() || b == b'-' || b == b'.') {
            return false;
        }
    }
    true
}
