import html
import re

GREEK_LETTERS = {
    "alpha": "&alpha;", "beta": "&beta;", "gamma": "&gamma;", "delta": "&delta;",
    "epsilon": "&epsilon;", "varepsilon": "&epsilon;", "zeta": "&zeta;", "eta": "&eta;",
    "theta": "&theta;", "vartheta": "&thetasym;", "iota": "&iota;", "kappa": "&kappa;",
    "lambda": "&lambda;", "mu": "&mu;", "nu": "&nu;", "xi": "&xi;", "pi": "&pi;",
    "varpi": "&piv;", "rho": "&rho;", "varrho": "&rho;", "sigma": "&sigma;",
    "varsigma": "&sigmaf;", "tau": "&tau;", "upsilon": "&upsilon;", "phi": "&phi;",
    "varphi": "&phi;", "chi": "&chi;", "psi": "&psi;", "omega": "&omega;",
    "Gamma": "&Gamma;", "Delta": "&Delta;", "Theta": "&Theta;", "Lambda": "&Lambda;",
    "Xi": "&Xi;", "Pi": "&Pi;", "Sigma": "&Sigma;", "Upsilon": "&Upsilon;",
    "Phi": "&Phi;", "Psi": "&Psi;", "Omega": "&Omega;"
}

MATH_SYMBOLS = {
    "times": "&times;", "cdot": "&middot;", "div": "&divide;", "pm": "&plusmn;",
    "mp": "&#8723;", "le": "&le;", "leq": "&le;", "ge": "&ge;", "geq": "&ge;",
    "neq": "&ne;", "ne": "&ne;", "approx": "&asymp;", "equiv": "&equiv;",
    "infty": "&infin;", "partial": "&part;", "nabla": "&nabla;", "sum": "&sum;",
    "prod": "&prod;", "int": "&int;", "iint": "&#8748;", "iiint": "&#8749;",
    "oint": "&#8750;", "rightarrow": "&rarr;", "to": "&rarr;", "leftarrow": "&larr;",
    "Rightarrow": "&rArr;", "Leftarrow": "&lArr;", "Leftrightarrow": "&hArr;",
    "iff": "&hArr;", "implies": "&rArr;", "forall": "&forall;", "exists": "&exist;",
    "nexists": "&#8708;", "in": "&isin;", "notin": "&notin;", "subset": "&sub;",
    "subseteq": "&sube;", "supset": "&sup;", "supseteq": "&supe;", "cup": "&cup;",
    "cap": "&cap;", "setminus": "&#8726;", "circ": "&deg;", "degree": "&deg;",
    "ldots": "&hellip;", "cdots": "&#8943;", "vdots": "&#8942;", "ddots": "&#8945;",
    "quad": "&nbsp;&nbsp;&nbsp;&nbsp;", "qquad": "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",
    "sim": "~", "propto": "&prop;", "perp": "&perp;", "parallel": "&#8741;",
    "langle": "&lang;", "rangle": "&rang;", "lceil": "&lceil;", "rceil": "&rceil;",
    "lfloor": "&lfloor;", "rfloor": "&rfloor;", "dagger": "&dagger;", "star": "&#9733;",
    "checkmark": "&#10003;", "prime": "&prime;",
}

BLACKBOARD_BOLD = {
    "N": "&#8469;", "Z": "&#8484;", "Q": "&#8474;", "R": "&#8477;", "C": "&#8450;",
    "P": "&#8473;", "H": "&#8461;", "E": "&#120124;", "1": "&#120793;"
}


def extract_balanced_braces(text: str, start_index: int) -> tuple[str, int]:
    """
    Finds the content of balanced curly braces { ... } starting at start_index.
    Returns (content, next_index_after_closing_brace).
    """
    if start_index >= len(text) or text[start_index] != '{':
        return "", start_index

    depth = 0
    start = start_index + 1
    for i in range(start_index, len(text)):
        if text[i] == '{':
            depth += 1
        elif text[i] == '}':
            depth -= 1
            if depth == 0:
                return text[start:i], i + 1

    return text[start:], len(text)


def extract_balanced_brackets(text: str, start_index: int) -> tuple[str, int]:
    """
    Finds the content of balanced square brackets [ ... ] starting at start_index.
    """
    if start_index >= len(text) or text[start_index] != '[':
        return "", start_index

    depth = 0
    start = start_index + 1
    for i in range(start_index, len(text)):
        if text[i] == '[':
            depth += 1
        elif text[i] == ']':
            depth -= 1
            if depth == 0:
                return text[start:i], i + 1

    return text[start:], len(text)


def render_latex_math(expr: str, is_block: bool = False) -> str:
    """
    Recursively renders all LaTeX commands, fractions, matrices,
    nested boxed expressions, and symbols into rich styled HTML.
    """
    expr = expr.strip()
    if not expr:
        return ""

    # 1. Clean delimiters \left and \right
    expr = re.sub(r'\\left\s*([(\[{|.])', r'\1', expr)
    expr = re.sub(r'\\right\s*([)\]}|.])', r'\1', expr)

    # 2. Process \boxed{...} with nested brace support
    while r"\boxed" in expr:
        idx = expr.find(r"\boxed")
        brace_idx = expr.find("{", idx)
        if brace_idx != -1 and brace_idx - (idx + 6) <= 2:
            inner_content, next_idx = extract_balanced_braces(expr, brace_idx)
            rendered_inner = render_latex_math(inner_content, is_block=False)
            boxed_html = (
                f'<span style="display:inline-block; border:2px solid #818cf8; '
                f'padding:3px 10px; border-radius:8px; background-color:rgba(129,140,248,0.18); '
                f'font-weight:700; color:#ffffff; margin:2px 3px;">{rendered_inner}</span>'
            )
            expr = expr[:idx] + boxed_html + expr[next_idx:]
        else:
            break

    # 3. Process fractions: \frac, \dfrac, \tfrac, \cfrac with nested braces
    frac_patterns = [r"\dfrac", r"\tfrac", r"\cfrac", r"\frac"]
    found_frac = True
    while found_frac:
        found_frac = False
        for fp in frac_patterns:
            if fp in expr:
                idx = expr.find(fp)
                brace1_idx = expr.find("{", idx)
                if brace1_idx != -1 and brace1_idx - (idx + len(fp)) <= 2:
                    num_content, after_num = extract_balanced_braces(expr, brace1_idx)
                    brace2_idx = expr.find("{", after_num)
                    if brace2_idx != -1 and brace2_idx - after_num <= 2:
                        den_content, after_den = extract_balanced_braces(expr, brace2_idx)
                        rendered_num = render_latex_math(num_content, is_block=False)
                        rendered_den = render_latex_math(den_content, is_block=False)

                        frac_html = (
                            f'<span style="display:inline-block; vertical-align:middle; text-align:center; padding:0 3px; font-size:95%;">'
                            f'<span style="display:block; border-bottom:1.5px solid #94a3b8; padding-bottom:1px;">{rendered_num}</span>'
                            f'<span style="display:block; padding-top:1px;">{rendered_den}</span>'
                            f'</span>'
                        )
                        expr = expr[:idx] + frac_html + expr[after_den:]
                        found_frac = True
                        break

    # 4. Process \binom{n}{k}
    while r"\binom" in expr:
        idx = expr.find(r"\binom")
        brace1_idx = expr.find("{", idx)
        if brace1_idx != -1:
            top_c, after_top = extract_balanced_braces(expr, brace1_idx)
            brace2_idx = expr.find("{", after_top)
            if brace2_idx != -1:
                bot_c, after_bot = extract_balanced_braces(expr, brace2_idx)
                binom_html = (
                    f'<span style="display:inline-block; vertical-align:middle; text-align:center; padding:0 2px;">'
                    f'<span style="font-size:140%; vertical-align:middle;">(</span>'
                    f'<span style="display:inline-block; vertical-align:middle; text-align:center;">'
                    f'<span style="display:block;">{render_latex_math(top_c)}</span>'
                    f'<span style="display:block;">{render_latex_math(bot_c)}</span>'
                    f'</span>'
                    f'<span style="font-size:140%; vertical-align:middle;">)</span>'
                    f'</span>'
                )
                expr = expr[:idx] + binom_html + expr[after_bot:]
            else:
                break
        else:
            break

    # 5. Process \sqrt[n]{x} and \sqrt{x}
    while r"\sqrt" in expr:
        idx = expr.find(r"\sqrt")
        bracket_idx = expr.find("[", idx)
        brace_idx = expr.find("{", idx)
        if bracket_idx != -1 and (brace_idx == -1 or bracket_idx < brace_idx) and bracket_idx - (idx + 5) <= 2:
            deg, after_deg = extract_balanced_brackets(expr, bracket_idx)
            brace_idx2 = expr.find("{", after_deg)
            if brace_idx2 != -1:
                inner, after_inner = extract_balanced_braces(expr, brace_idx2)
                rendered_inner = render_latex_math(inner, is_block=False)
                sqrt_html = f'<sup>{deg}</sup>&radic;({rendered_inner})'
                expr = expr[:idx] + sqrt_html + expr[after_inner:]
            else:
                break
        elif brace_idx != -1 and brace_idx - (idx + 5) <= 2:
            inner, after_inner = extract_balanced_braces(expr, brace_idx)
            rendered_inner = render_latex_math(inner, is_block=False)
            sqrt_html = f'&radic;({rendered_inner})'
            expr = expr[:idx] + sqrt_html + expr[after_inner:]
        else:
            expr = expr.replace(r"\sqrt", "&radic;", 1)

    # 6. Process text styling: \text, \mathrm, \mathbf, \mathit, \mathbb, \mathcal
    style_commands = [
        (r"\text", r"\1"),
        (r"\mathrm", r"\1"),
        (r"\mathbf", r"<b>\1</b>"),
        (r"\textbf", r"<b>\1</b>"),
        (r"\mathit", r"<i>\1</i>"),
        (r"\textit", r"<i>\1</i>"),
        (r"\underline", r"<u>\1</u>"),
        (r"\overline", r"<span style='text-decoration:overline;'>\1</span>")
    ]
    for cmd, fmt in style_commands:
        while cmd in expr:
            idx = expr.find(cmd)
            brace_idx = expr.find("{", idx)
            if brace_idx != -1 and brace_idx - (idx + len(cmd)) <= 2:
                inner, after_inner = extract_balanced_braces(expr, brace_idx)
                rendered = fmt.replace(r"\1", inner)
                expr = expr[:idx] + rendered + expr[after_inner:]
            else:
                break

    # 7. Blackboard bold \mathbb{R} -> ℝ
    while r"\mathbb" in expr:
        idx = expr.find(r"\mathbb")
        brace_idx = expr.find("{", idx)
        if brace_idx != -1:
            letter, after_letter = extract_balanced_braces(expr, brace_idx)
            sym = BLACKBOARD_BOLD.get(letter.strip(), letter)
            expr = expr[:idx] + sym + expr[after_letter:]
        else:
            break

    # 8. Environments: \begin{cases} ... \end{cases}, \begin{matrix}, etc.
    def replace_cases(m):
        rows = m.group(1).split(r"\\")
        html_rows = []
        for r in rows:
            r_clean = render_latex_math(r.replace("&", "&nbsp;&nbsp;"), is_block=False)
            html_rows.append(f"<div style='margin:2px 0;'>{r_clean}</div>")
        return (
            f'<div style="display:inline-flex; align-items:center; vertical-align:middle; margin:4px 0;">'
            f'<span style="font-size:200%; margin-right:4px;">&#123;</span>'
            f'<div style="display:inline-block; text-align:left;">{"".join(html_rows)}</div>'
            f'</div>'
        )

    expr = re.sub(r'\\begin\{cases\}([\s\S]*?)\\end\{cases\}', replace_cases, expr)

    def replace_matrix(m):
        rows = m.group(2).split(r"\\")
        html_rows = []
        for r in rows:
            cols = [render_latex_math(c, is_block=False) for c in r.split("&")]
            row_html = "".join([f"<td style='padding:3px 8px; text-align:center;'>{c}</td>" for c in cols])
            html_rows.append(f"<tr>{row_html}</tr>")
        return (
            f'<table style="display:inline-table; vertical-align:middle; border-left:2px solid #818cf8; '
            f'border-right:2px solid #818cf8; margin:4px 6px; padding:0 2px;">{"".join(html_rows)}</table>'
        )

    expr = re.sub(r'\\begin\{(matrix|pmatrix|bmatrix|vmatrix)\}([\s\S]*?)\\end\{\1\}', replace_matrix, expr)

    # 9. Replace Greek Letters and Operators
    for name, sym in GREEK_LETTERS.items():
        expr = re.sub(r'\\' + name + r'\b', sym, expr)

    for op, sym in MATH_SYMBOLS.items():
        expr = re.sub(r'\\' + op + r'\b', sym, expr)

    # Spacing commands
    expr = expr.replace(r"\,", "&nbsp;").replace(r"\;", "&nbsp;&nbsp;").replace(r"\:", "&nbsp;").replace(r"\!", "")

    # Exponents: x^{...} or x^2
    while "^" in expr:
        idx = expr.find("^")
        if idx + 1 < len(expr) and expr[idx + 1] == '{':
            exp_content, after_exp = extract_balanced_braces(expr, idx + 1)
            rendered_exp = render_latex_math(exp_content, is_block=False)
            expr = expr[:idx] + f"<sup>{rendered_exp}</sup>" + expr[after_exp:]
        elif idx + 1 < len(expr) and expr[idx + 1].isalnum():
            expr = expr[:idx] + f"<sup>{expr[idx+1]}</sup>" + expr[idx + 2:]
        else:
            break

    # Subscripts: x_{...} or x_1
    while "_" in expr:
        idx = expr.find("_")
        if idx + 1 < len(expr) and expr[idx + 1] == '{':
            sub_content, after_sub = extract_balanced_braces(expr, idx + 1)
            rendered_sub = render_latex_math(sub_content, is_block=False)
            expr = expr[:idx] + f"<sub>{rendered_sub}</sub>" + expr[after_sub:]
        elif idx + 1 < len(expr) and expr[idx + 1].isalnum():
            expr = expr[:idx] + f"<sub>{expr[idx+1]}</sub>" + expr[idx + 2:]
        else:
            break

    # Clean leftover unhandled LaTeX command words (e.g. \displaystyle, \limits)
    expr = re.sub(r'\\(displaystyle|textstyle|limits|nolimits|rm|sf|tt|bf|it|cal)\b', '', expr)
    expr = re.sub(r'\\([a-zA-Z]+)', r'\1', expr)

    if is_block:
        return (
            f'<div style="display:block; text-align:center; margin:10px 0; padding:12px; '
            f'background-color:#161922; border:1px solid #282e3f; border-radius:8px; '
            f'font-family:\'Cambria Math\', \'Latin Modern Math\', \'STIX Two Math\', serif; '
            f'font-size:110%; color:#f1f5f9; overflow-x:auto;">{expr}</div>'
        )
    else:
        return (
            f'<span style="font-family:\'Cambria Math\', \'Latin Modern Math\', \'STIX Two Math\', serif; '
            f'color:#f1f5f9; padding:0 2px;">{expr}</span>'
        )


def format_markdown_and_latex(text: str) -> str:
    """
    Parses Markdown, code blocks, lists, and any LaTeX formulas ($$, $, \[, \(, \boxed, \frac, \mathbb, etc.),
    returning rich styled HTML.
    """
    if not text:
        return ""

    placeholders = []

    def store_placeholder(html_snippet: str) -> str:
        idx = len(placeholders)
        placeholders.append(html_snippet)
        return f"QQQMAGITOKEN{idx}ZZZ"

    # 0. Preserve pre-existing styled HTML cards (e.g. Sandbox output blocks)
    def handle_raw_html_card(m):
        return store_placeholder(m.group(0))

    text = re.sub(r'<!--MAGI_SANDBOX_START-->[\s\S]*?<!--MAGI_SANDBOX_END-->', handle_raw_html_card, text)
    text = re.sub(r'<div style="background-color:#141417;[\s\S]*?</div>', handle_raw_html_card, text)
    text = re.sub(r'<div style="background-color:#0c0f18;[\s\S]*?</div>', handle_raw_html_card, text)

    # 1. Code blocks (preserve exact content)
    def handle_code_block(m):
        code_text = html.escape(m.group(2))
        block_html = (
            f'<pre style="background-color:#0f1117; border:1px solid #232736; '
            f'padding:10px; border-radius:8px; font-family:Consolas, monospace; '
            f'font-size:12px; color:#a5b4fc; margin:8px 0; white-space:pre-wrap;">'
            f'<code>{code_text}</code></pre>'
        )
        return store_placeholder(block_html)

    text = re.sub(r'```([a-zA-Z0-9_-]*)\n?(.*?)```', handle_code_block, text, flags=re.DOTALL)

    # 2. Display LaTeX Blocks ($$...$$ and \[...\])
    def handle_block_math(m):
        math_html = render_latex_math(m.group(1), is_block=True)
        return store_placeholder(math_html)

    text = re.sub(r'\$\$([\s\S]*?)\$\$', handle_block_math, text)
    text = re.sub(r'\\\[([\s\S]*?)\\\]', handle_block_math, text)

    # 3. Inline LaTeX Math ($...$ and \(...\))
    def handle_inline_math(m):
        inner = m.group(1).strip()
        if "\n\n" in inner:
            return m.group(0)
        # Avoid treating plain currency or numbers like $25, $10.50 as LaTeX math
        if re.match(r'^\d+(\.\d+)?$', inner) or re.match(r'^\d+\s*(to|-)\s*\d+$', inner, re.IGNORECASE):
            return m.group(0)
        # Must contain letters, LaTeX symbols, operators, or backslashes to qualify as math
        if not re.search(r'[a-zA-Z\\_^=+<>\-*/()\[\]{}&]', inner):
            return m.group(0)
        math_html = render_latex_math(inner, is_block=False)
        return store_placeholder(math_html)

    text = re.sub(r'\$([^\$\n]+?)\$', handle_inline_math, text)
    text = re.sub(r'\\\(([\s\S]*?)\\\)', handle_inline_math, text)

    # 4. Standalone \boxed{...} with nested brace support
    while r"\boxed" in text:
        idx = text.find(r"\boxed")
        brace_idx = text.find("{", idx)
        if brace_idx != -1 and brace_idx - (idx + 6) <= 2:
            inner_c, after_idx = extract_balanced_braces(text, brace_idx)
            rendered_b = render_latex_math(r"\boxed{" + inner_c + r"}", is_block=False)
            placeholder = store_placeholder(rendered_b)
            text = text[:idx] + placeholder + text[after_idx:]
        else:
            break

    # 5. Standalone raw LaTeX math commands (when not enclosed in $)
    standalone_commands = [
        r"\dfrac", r"\tfrac", r"\cfrac", r"\frac", r"\binom", r"\sqrt",
        r"\mathbb", r"\mathbf", r"\mathrm", r"\mathit", r"\begin{cases}",
        r"\begin{matrix}", r"\begin{pmatrix}", r"\begin{bmatrix}"
    ]
    for cmd in standalone_commands:
        while cmd in text:
            idx = text.find(cmd)
            end_idx = idx + len(cmd)
            while end_idx < len(text) and (text[end_idx].isspace() or text[end_idx] in "{["):
                if text[end_idx] == '{':
                    _, end_idx = extract_balanced_braces(text, end_idx)
                elif text[end_idx] == '[':
                    _, end_idx = extract_balanced_brackets(text, end_idx)
                else:
                    end_idx += 1

            math_segment = text[idx:end_idx]
            rendered_seg = render_latex_math(math_segment, is_block=False)
            placeholder = store_placeholder(rendered_seg)
            text = text[:idx] + placeholder + text[end_idx:]

    # 6. Replace lone LaTeX symbols outside math blocks
    for name, sym in GREEK_LETTERS.items():
        text = re.sub(r'\\' + name + r'\b', sym, text)

    for op, sym in MATH_SYMBOLS.items():
        text = re.sub(r'\\' + op + r'\b', sym, text)

    text = re.sub(r'\\left\s*([(\[{|.])', r'\1', text)
    text = re.sub(r'\\right\s*([)\]}|.])', r'\1', text)

    # 6.5. Markdown Tables (parsed into styled HTML <table> and stored as placeholders)
    def parse_markdown_tables(src_text: str) -> str:
        lines = src_text.split("\n")
        new_lines = []
        i = 0
        while i < len(lines):
            line = lines[i].strip()
            if "|" in line and i + 1 < len(lines):
                sep_line = lines[i + 1].strip()
                if re.match(r'^\|?(\s*:?-+:?\s*\|)+\s*(:?-+:?\s*)?\|?$', sep_line) and "-" in sep_line:
                    def split_row(r):
                        r_clean = r.strip()
                        if r_clean.startswith("|"):
                            r_clean = r_clean[1:]
                        if r_clean.endswith("|"):
                            r_clean = r_clean[:-1]
                        return [c.strip() for c in r_clean.split("|")]

                    headers = split_row(line)
                    separators = split_row(sep_line)

                    alignments = []
                    for s in separators:
                        s = s.strip()
                        if s.startswith(":") and s.endswith(":"):
                            alignments.append("center")
                        elif s.endswith(":"):
                            alignments.append("right")
                        else:
                            alignments.append("left")

                    body_rows = []
                    j = i + 2
                    while j < len(lines):
                        row_line = lines[j].strip()
                        if not row_line or "|" not in row_line:
                            break
                        body_rows.append(split_row(row_line))
                        j += 1

                    num_cols = len(headers)

                    def format_cell(c: str) -> str:
                        c = re.sub(r'\*\*(.*?)\*\*', r'<strong style="color:#ffffff; font-weight:800;">\1</strong>', c)
                        c = re.sub(r'__(.*?)__', r'<strong style="color:#ffffff; font-weight:800;">\1</strong>', c)
                        c = re.sub(r'(?<!\*)\*(?!\*)(.*?)(?<!\*)\*(?!\*)', r'<i>\1</i>', c)
                        c = re.sub(r'`([^`]+)`', r'<code style="background-color:#1e2433; color:#f472b6; padding:1px 5px; border-radius:3px; font-family:Consolas, monospace; font-size:11px;">\1</code>', c)
                        return c

                    table_html = [
                        '<table style="border-collapse:collapse; width:100%; margin:8px 0; '
                        'background-color:#10131d; border:1px solid #283046; border-radius:8px; overflow:hidden;">'
                    ]
                    # Header
                    table_html.append('<thead><tr style="background-color:#181f2e;">')
                    for idx, h in enumerate(headers):
                        align = alignments[idx] if idx < len(alignments) else "left"
                        cell_fmt = format_cell(h)
                        table_html.append(
                            f'<th style="border:1px solid #283046; padding:7px 12px; text-align:{align}; '
                            f'color:#ffffff; font-weight:bold; font-size:12px;">{cell_fmt}</th>'
                        )
                    table_html.append('</tr></thead>')

                    # Body
                    table_html.append('<tbody>')
                    for r_idx, row in enumerate(body_rows):
                        bg_color = "#10131d" if r_idx % 2 == 0 else "#151a27"
                        table_html.append(f'<tr style="background-color:{bg_color};">')
                        for idx in range(num_cols):
                            cell_content = row[idx] if idx < len(row) else ""
                            align = alignments[idx] if idx < len(alignments) else "left"
                            cell_fmt = format_cell(cell_content)
                            table_html.append(
                                f'<td style="border:1px solid #283046; padding:6px 12px; text-align:{align}; '
                                f'color:#e2e8f0; font-size:12px;">{cell_fmt}</td>'
                            )
                        table_html.append('</tr>')
                    table_html.append('</tbody></table>')

                    new_lines.append(store_placeholder("".join(table_html)))
                    i = j
                    continue
            new_lines.append(lines[i])
            i += 1
        return "\n".join(new_lines)

    text = parse_markdown_tables(text)

    # 7. Standard Markdown Formats
    # Bold **text** (thick/heavy bold styling)
    text = re.sub(r'\*\*(.*?)\*\*', r'<strong style="color:#ffffff; font-weight:800; font-size:102%;">\1</strong>', text)
    text = re.sub(r'__(.*?)__', r'<strong style="color:#ffffff; font-weight:800; font-size:102%;">\1</strong>', text)

    # Italic *text*
    text = re.sub(r'(?<!\*)\*(?!\*)(.*?)(?<!\*)\*(?!\*)', r'<i>\1</i>', text)

    # Inline Code `code`
    def handle_inline_code(m):
        code_snip = html.escape(m.group(1))
        snip_html = (
            f'<code style="background-color:#1e2433; color:#f472b6; padding:2px 6px; '
            f'border-radius:4px; font-family:Consolas, monospace; font-size:12px;">{code_snip}</code>'
        )
        return store_placeholder(snip_html)

    text = re.sub(r'`([^`]+)`', handle_inline_code, text)

    # Headers
    text = re.sub(r'^### (.*?)$', r'<h4 style="color:#ffffff; margin:10px 0 4px 0; font-size:14px;">\1</h4>', text, flags=re.MULTILINE)
    text = re.sub(r'^## (.*?)$', r'<h3 style="color:#ffffff; margin:12px 0 6px 0; font-size:15px;">\1</h3>', text, flags=re.MULTILINE)
    text = re.sub(r'^# (.*?)$', r'<h2 style="color:#ffffff; margin:14px 0 8px 0; font-size:16px;">\1</h2>', text, flags=re.MULTILINE)

    # Lists
    text = re.sub(r'^\s*[-*+]\s+(.*?)$', r'<div style="margin-left:12px; margin-top:3px; color:#f1f5f9;">• \1</div>', text, flags=re.MULTILINE)
    text = re.sub(r'^\s*(\d+)\.\s+(.*?)$', r'<div style="margin-left:12px; margin-top:3px; color:#f1f5f9;"><b>\1.</b> \2</div>', text, flags=re.MULTILINE)

    # Line breaks
    text = text.replace("\n", "<br>")

    # Clean redundant br tags
    text = re.sub(r'(<br>\s*)+', r'<br>', text)

    # 8. Restore all placeholders iteratively (resolves nested placeholders such as math or code inside tables)
    for _ in range(6):
        replaced_any = False
        for idx, snippet in enumerate(placeholders):
            token = f"QQQMAGITOKEN{idx}ZZZ"
            if token in text:
                text = text.replace(token, snippet)
                replaced_any = True
        if not replaced_any:
            break

    return text
