-- Define table-related environments
local table_environments = {
    "tabular", "tabularx", "tabulary", "longtable", "supertabular",
    "xtabular", "mpsupertabular", "threeparttable", "talltable",
    "longtabu", "tabu", "ltxtable", "xtabular*", "themultirow",
    "tabulary*", "tabularht", "tabular*", "NiceTabular", "NiceTabular*",
    "tblr", "booktabs", "table", "table*", "sidewaystable",
    "threeparttablex", "xltabular", "TableNotes", "ctable",
    "deluxetable", "deluxetable*", "splitdeluxetable", "rotatetable",
    "floatrow", "wrapfloat", "wraptable", "wrapfigure"
}

-- Helper function to check if the LaTeX block contains any table-related keywords
local function contains_table_keyword(text)
    for _, keyword in ipairs(table_environments) do
        if string.find(text, "\\begin{" .. keyword .. "%*?}") or string.find(text, "\\end{" .. keyword .. "%*?}") then
            return true
        end
    end
    return false
end

-- Filter for block-level LaTeX content
function RawBlock(el)
    if el.format == "latex" then
        -- Check if the LaTeX block contains any table-related keywords
        if contains_table_keyword(el.text) then
            return pandoc.RawBlock("markdown", "```latex\n" .. el.text .. "\n```")
        else
            return pandoc.Plain {} -- Remove the block by replacing it with an empty block
        end
    end
    return el -- Return unchanged if it's not LaTeX
end

-- Filter for inline LaTeX content
function RawInline(el)
    if el.format == "latex" then
        -- Check if the inline LaTeX contains any table-related keywords
        if contains_table_keyword(el.text) then
            return el             -- Keep the inline if it contains table-related keywords
        else
            return pandoc.Str("") -- Remove the inline LaTeX by returning an empty string
        end
    end
    return el -- Return unchanged if it's not LaTeX
end

-- Filter table elements by removing the <div> container
function Div(el)
    -- Check if the div has the class "table" or any id attribute (like id="tab:stat")
    if el.identifier or el.classes:includes("table") then
        -- Return the content inside the div, effectively removing the div wrapper
        return el.content
    end
end

-- Filter figure elements
function Figure(el)
    return {}
end

-- Filter header references
function Header(el)
    -- Check if the header has an identifier
    if el.identifier then
        -- Return the header without the identifier
        return pandoc.Header(el.level, el.content)
    end
end

-- Make code block more beautiful, converting ```{=latex}``` to ```latex```
function CodeBlock(el)
    print(el)
    if el.classes[1] == "latex" then
        el.classes = {}
    end
    return el
end