var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React, { useCallback, useEffect, useRef, useState, } from "react";
// https://github.com/remarkjs/react-markdown
import ReactMarkdown from "react-markdown";
// https://github.com/remarkjs/remark-gfm
import remarkGfm from "remark-gfm";
import SyntaxHighlighter from "react-syntax-highlighter/dist/esm/prism-light";
import { vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism";
import javascript from "react-syntax-highlighter/dist/esm/languages/prism/javascript";
import typescript from "react-syntax-highlighter/dist/esm/languages/prism/typescript";
import jsx from "react-syntax-highlighter/dist/esm/languages/prism/jsx";
import tsx from "react-syntax-highlighter/dist/esm/languages/prism/tsx";
import python from "react-syntax-highlighter/dist/esm/languages/prism/python";
import bash from "react-syntax-highlighter/dist/esm/languages/prism/bash";
import json from "react-syntax-highlighter/dist/esm/languages/prism/json";
import yaml from "react-syntax-highlighter/dist/esm/languages/prism/yaml";
import sql from "react-syntax-highlighter/dist/esm/languages/prism/sql";
import go from "react-syntax-highlighter/dist/esm/languages/prism/go";
import java from "react-syntax-highlighter/dist/esm/languages/prism/java";
import css from "react-syntax-highlighter/dist/esm/languages/prism/css";
import markup from "react-syntax-highlighter/dist/esm/languages/prism/markup";
import markdown from "react-syntax-highlighter/dist/esm/languages/prism/markdown";
import docker from "react-syntax-highlighter/dist/esm/languages/prism/docker";
import rust from "react-syntax-highlighter/dist/esm/languages/prism/rust";
import c from "react-syntax-highlighter/dist/esm/languages/prism/c";
import cpp from "react-syntax-highlighter/dist/esm/languages/prism/cpp";
import csharp from "react-syntax-highlighter/dist/esm/languages/prism/csharp";
import ruby from "react-syntax-highlighter/dist/esm/languages/prism/ruby";
import php from "react-syntax-highlighter/dist/esm/languages/prism/php";
import graphql from "react-syntax-highlighter/dist/esm/languages/prism/graphql";
import http from "react-syntax-highlighter/dist/esm/languages/prism/http";
SyntaxHighlighter.registerLanguage("javascript", javascript);
SyntaxHighlighter.registerLanguage("js", javascript);
SyntaxHighlighter.registerLanguage("typescript", typescript);
SyntaxHighlighter.registerLanguage("ts", typescript);
SyntaxHighlighter.registerLanguage("jsx", jsx);
SyntaxHighlighter.registerLanguage("tsx", tsx);
SyntaxHighlighter.registerLanguage("python", python);
SyntaxHighlighter.registerLanguage("bash", bash);
SyntaxHighlighter.registerLanguage("shell", bash);
SyntaxHighlighter.registerLanguage("json", json);
SyntaxHighlighter.registerLanguage("yaml", yaml);
SyntaxHighlighter.registerLanguage("yml", yaml);
SyntaxHighlighter.registerLanguage("sql", sql);
SyntaxHighlighter.registerLanguage("go", go);
SyntaxHighlighter.registerLanguage("java", java);
SyntaxHighlighter.registerLanguage("css", css);
SyntaxHighlighter.registerLanguage("markup", markup);
SyntaxHighlighter.registerLanguage("html", markup);
SyntaxHighlighter.registerLanguage("xml", markup);
SyntaxHighlighter.registerLanguage("markdown", markdown);
SyntaxHighlighter.registerLanguage("md", markdown);
SyntaxHighlighter.registerLanguage("docker", docker);
SyntaxHighlighter.registerLanguage("dockerfile", docker);
SyntaxHighlighter.registerLanguage("rust", rust);
SyntaxHighlighter.registerLanguage("c", c);
SyntaxHighlighter.registerLanguage("cpp", cpp);
SyntaxHighlighter.registerLanguage("csharp", csharp);
SyntaxHighlighter.registerLanguage("ruby", ruby);
SyntaxHighlighter.registerLanguage("php", php);
SyntaxHighlighter.registerLanguage("graphql", graphql);
SyntaxHighlighter.registerLanguage("http", http);
import mermaid from "mermaid";
import DOMPurify from "dompurify";
import OneUptimeDate from "../../../Types/Date";
/*
 * ISO 8601 timestamps produced by OneUptimeDate.toString() — the
 * backend-generated root cause markdown inline-codes every timestamp so
 * we can localize it here without needing a custom markdown plugin.
 * Matches e.g. "2026-04-20T11:21:00.000Z" (Z-terminated, with ms).
 */
const ISO_8601_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/;
// Initialize mermaid
mermaid.initialize({
    startOnLoad: false,
    theme: "default",
    securityLevel: "strict",
    fontFamily: "inherit",
    themeVariables: {
        background: "#ffffff",
        primaryColor: "#e0f2fe",
        primaryTextColor: "#1e293b",
        primaryBorderColor: "#0ea5e9",
        lineColor: "#64748b",
        secondaryColor: "#f1f5f9",
        tertiaryColor: "#ffffff",
    },
});
// Mermaid diagram component
const MermaidDiagram = ({ chart, }) => {
    const containerRef = useRef(null);
    useEffect(() => {
        const renderDiagram = async () => {
            if (containerRef.current) {
                containerRef.current.innerHTML = "";
                try {
                    const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`;
                    const { svg } = await mermaid.render(id, chart);
                    if (containerRef.current) {
                        containerRef.current.innerHTML = DOMPurify.sanitize(svg, {
                            USE_PROFILES: { svg: true, svgFilters: true },
                            ADD_TAGS: ["foreignObject"],
                        });
                    }
                }
                catch (error) {
                    if (containerRef.current) {
                        const errorMessage = String(error);
                        const errorEl = document.createElement("pre");
                        errorEl.className = "text-red-500";
                        errorEl.textContent = `Error rendering diagram: ${errorMessage}`;
                        containerRef.current.innerHTML = "";
                        containerRef.current.appendChild(errorEl);
                    }
                }
            }
        };
        renderDiagram();
    }, [chart]);
    return (React.createElement("div", { ref: containerRef, className: "my-4 flex justify-center bg-white p-4 rounded-lg" }));
};
// Language display names
const langDisplayNames = {
    js: "JavaScript",
    javascript: "JavaScript",
    ts: "TypeScript",
    typescript: "TypeScript",
    jsx: "JSX",
    tsx: "TSX",
    py: "Python",
    python: "Python",
    rb: "Ruby",
    ruby: "Ruby",
    go: "Go",
    java: "Java",
    css: "CSS",
    html: "HTML",
    xml: "XML",
    json: "JSON",
    yaml: "YAML",
    yml: "YAML",
    sql: "SQL",
    bash: "Bash",
    shell: "Shell",
    sh: "Shell",
    dockerfile: "Dockerfile",
    docker: "Dockerfile",
    rust: "Rust",
    cpp: "C++",
    c: "C",
    csharp: "C#",
    php: "PHP",
    graphql: "GraphQL",
    http: "HTTP",
    markdown: "Markdown",
    md: "Markdown",
};
// Code block with copy button and language label
const CodeBlock = ({ language, content, rest, }) => {
    const [copied, setCopied] = useState(false);
    const handleCopy = useCallback(() => {
        navigator.clipboard
            .writeText(content)
            .then(() => {
            setCopied(true);
            setTimeout(() => {
                setCopied(false);
            }, 2000);
        })
            .catch(() => {
            // Fallback: do nothing
        });
    }, [content]);
    const displayLang = langDisplayNames[language] ||
        (language ? language.charAt(0).toUpperCase() + language.slice(1) : "");
    return (React.createElement("div", { className: "relative rounded-lg mt-3 mb-3 overflow-hidden border border-gray-200 shadow-sm" },
        React.createElement("div", { className: "flex items-center justify-between px-3 py-1.5 bg-gray-800 border-b border-gray-700" },
            React.createElement("span", { className: "text-[11px] font-medium uppercase tracking-wider text-gray-400 select-none" }, displayLang),
            React.createElement("button", { onClick: handleCopy, className: `inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] font-medium transition-all duration-150 border-none cursor-pointer ${copied
                    ? "text-green-400"
                    : "text-gray-400 hover:text-gray-200 hover:bg-white/10"}`, "aria-label": "Copy code", type: "button" },
                copied ? (React.createElement("svg", { className: "w-3.5 h-3.5", fill: "none", stroke: "currentColor", strokeWidth: 2, viewBox: "0 0 24 24" },
                    React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M5 13l4 4L19 7" }))) : (React.createElement("svg", { className: "w-3.5 h-3.5", fill: "none", stroke: "currentColor", strokeWidth: 2, viewBox: "0 0 24 24" },
                    React.createElement("rect", { x: "9", y: "9", width: "13", height: "13", rx: "2" }),
                    React.createElement("path", { d: "M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" }))),
                copied ? "Copied!" : "Copy")),
        React.createElement(SyntaxHighlighter, Object.assign({}, rest, { PreTag: "div", 
            // eslint-disable-next-line react/no-children-prop
            children: content, language: language, style: vscDarkPlus, className: "!rounded-none !mt-0 !mb-0 !bg-gray-900 !pt-3 !pb-3 !px-4 text-sm !border-0", codeTagProps: { className: "font-mono" } }))));
};
/**
 * Render an ISO 8601 timestamp in the viewer's local timezone, with the
 * canonical UTC instant preserved in the `title` for hover/accessibility.
 * Falls back to the raw string if the date fails to parse so we never
 * render "Invalid Date" in a markdown cell.
 */
const LocalTime = ({ isoValue, }) => {
    const parsed = new Date(isoValue);
    if (isNaN(parsed.getTime())) {
        return (React.createElement("code", { className: "text-xs px-1.5 py-0.5 bg-gray-100 border border-gray-200 rounded text-gray-800 font-mono" }, isoValue));
    }
    const localFormatted = OneUptimeDate.getDateAsLocalFormattedString(parsed, false, true, true);
    return (React.createElement("time", { dateTime: isoValue, title: `${isoValue} (UTC)`, className: "text-xs px-1.5 py-0.5 bg-gray-100 border border-gray-200 rounded text-gray-800 font-mono whitespace-nowrap" }, localFormatted));
};
const MarkdownViewer = (props) => {
    return (React.createElement("div", { className: "max-w-none" },
        React.createElement(ReactMarkdown, { components: {
                // because tailwind does not supply <h1 ... /> styles https://tailwindcss.com/docs/preflight#headings-are-unstyled
                h1: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("h1", Object.assign({ className: "text-lg mt-6 mb-3 text-gray-900 font-bold" }, props)));
                },
                h2: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("h2", Object.assign({ className: "text-base mt-6 mb-2 text-gray-900 font-semibold" }, props)));
                },
                h3: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("h3", Object.assign({ className: "text-base mt-4 mb-2 text-gray-900 font-semibold" }, props)));
                },
                h4: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("h4", Object.assign({ className: "text-sm mt-3 mb-2 text-gray-900 font-semibold" }, props)));
                },
                h5: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("h5", Object.assign({ className: "text-sm mt-3 mb-1 text-gray-900 font-medium" }, props)));
                },
                h6: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("h6", Object.assign({ className: "text-sm mt-2 mb-1 text-gray-700 font-medium" }, props)));
                },
                p: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("p", Object.assign({ className: "text-sm mt-2 mb-1 text-gray-700 leading-relaxed" }, props)));
                },
                a: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("a", Object.assign({ className: "underline text-blue-600 hover:text-blue-800 font-medium transition-colors" }, props)));
                },
                img: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("img", Object.assign({ className: "max-w-full h-auto rounded-md border border-gray-200 my-3", loading: "lazy" }, props)));
                },
                pre: (_a) => {
                    var _b, _c;
                    var { children } = _a, rest = __rest(_a, ["children"]);
                    // Check if this is a mermaid diagram - don't render pre wrapper for mermaid
                    const isMermaid = React.isValidElement(children) &&
                        ((_c = (_b = children.props) === null || _b === void 0 ? void 0 : _b.className) === null || _c === void 0 ? void 0 : _c.includes("language-mermaid"));
                    if (isMermaid) {
                        // For mermaid, just return the children (MermaidDiagram component)
                        return React.createElement(React.Fragment, null, children);
                    }
                    /*
                     * If the child is a custom component (CodeBlock, MermaidDiagram, etc.)
                     * rather than a plain HTML element like <code>, skip pre styling.
                     * Checking typeof type !== "string" is minification-safe unlike checking type.name.
                     */
                    const isCustomComponent = React.isValidElement(children) &&
                        typeof children.type !== "string";
                    if (isCustomComponent) {
                        return React.createElement(React.Fragment, null, children);
                    }
                    return (React.createElement("pre", Object.assign({ className: "bg-gray-900 text-gray-100 mt-3 mb-3 p-3 rounded-md text-sm overflow-x-auto border border-gray-700" }, rest), children));
                },
                strong: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("strong", Object.assign({ className: "text-sm font-semibold text-gray-900" }, props)));
                },
                li: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("li", Object.assign({ className: "text-sm mt-1 mb-1 text-gray-700 leading-relaxed" }, props)));
                },
                ul: (_a) => {
                    var props = __rest(_a, []);
                    return React.createElement("ul", Object.assign({ className: "list-disc pl-6 mt-0 mb-1" }, props));
                },
                ol: (_a) => {
                    var props = __rest(_a, []);
                    return React.createElement("ol", Object.assign({ className: "list-decimal pl-6 mt-0 mb-1" }, props));
                },
                blockquote: (_a) => {
                    var { children } = _a, props = __rest(_a, ["children"]);
                    return (React.createElement("blockquote", Object.assign({ className: "rounded-lg border border-amber-200 bg-amber-50/50 my-4 not-italic overflow-hidden" }, props),
                        React.createElement("div", { className: "flex items-start gap-3 px-4 py-3" },
                            React.createElement("svg", { className: "h-5 w-5 flex-shrink-0 text-amber-500 mt-0.5", fill: "none", stroke: "currentColor", strokeWidth: 2, viewBox: "0 0 24 24" },
                                React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" })),
                            React.createElement("div", { className: "text-sm text-gray-700 leading-relaxed [&>p]:mt-0 [&>p]:mb-0 [&>p>strong:first-child]:text-amber-700 [&>p>strong:first-child]:mr-1" }, children))));
                },
                table: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("div", { className: "overflow-hidden rounded-lg border border-gray-200 mt-4 mb-4 shadow-sm" },
                        React.createElement("table", Object.assign({ className: "min-w-full table-auto border-collapse text-sm" }, props))));
                },
                thead: (_a) => {
                    var props = __rest(_a, []);
                    return React.createElement("thead", Object.assign({ className: "bg-gray-50" }, props));
                },
                tbody: (_a) => {
                    var props = __rest(_a, []);
                    return React.createElement("tbody", Object.assign({ className: "divide-y divide-gray-100" }, props));
                },
                tr: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("tr", Object.assign({ className: "hover:bg-gray-50 transition-colors" }, props)));
                },
                th: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("th", Object.assign({ className: "px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-500 border-b border-gray-200" }, props)));
                },
                td: (_a) => {
                    var props = __rest(_a, []);
                    return (React.createElement("td", Object.assign({ className: "px-4 py-2.5 text-sm text-gray-700" }, props)));
                },
                hr: (_a) => {
                    var props = __rest(_a, []);
                    return React.createElement("hr", Object.assign({ className: "border-gray-300 my-6" }, props));
                },
                code: (props) => {
                    const { children, className } = props, rest = __rest(props, ["children", "className"]);
                    const match = new RegExp("language-(\\w+)").exec(className || "");
                    const content = String(children).replace(/\n$/, "");
                    // Handle mermaid diagrams
                    if (match && match[1] === "mermaid") {
                        return React.createElement(MermaidDiagram, { chart: content });
                    }
                    const isMultiline = content.includes("\n");
                    const hasLanguage = Boolean(match &&
                        (match === null || match === void 0 ? void 0 : match.filter((item) => {
                            return item.includes("language-");
                        }).length) > 0);
                    // Multiline code blocks (with or without language) get the full CodeBlock treatment
                    if (hasLanguage || isMultiline) {
                        return (React.createElement(CodeBlock, { language: match ? match[1] : "text", content: content, rest: rest }));
                    }
                    /*
                     * Inline ISO 8601 timestamp → render in the viewer's local
                     * timezone. The backend emits every root-cause timestamp in
                     * this format precisely so it can be re-localized here.
                     */
                    if (ISO_8601_REGEX.test(content)) {
                        return React.createElement(LocalTime, { isoValue: content });
                    }
                    // Inline code
                    return (React.createElement("code", Object.assign({ className: "text-xs px-1.5 py-0.5 bg-gray-100 border border-gray-200 rounded text-gray-800 font-mono" }, rest), children));
                },
            }, remarkPlugins: [remarkGfm] }, props.text)));
};
export default MarkdownViewer;
//# sourceMappingURL=MarkdownViewer.js.map