import React from "react";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { tokens } from "../Markdown.tokens";
import { CodeBlock, CodeBlockBody, CodeBlockHeader, CodeLanguage, InlineCode, StyledBlockImage, StyledInlineImage, TableScroll, syntaxTheme } from "../Markdown.styles";
import { sanitizeUrl } from "../utils/sanitizeUrl";
import { renderElement } from "./renderUtils";
const getCodeLanguage = (className)=>{
    if (!className) {
        return undefined;
    }
    const match = className.match(/(?:lang(?:uage)?-)([a-z0-9+#.-]+)/i);
    return match && match[1] ? match[1].toLowerCase() : undefined;
};
const CodeRenderer = ({ children, className, inline })=>{
    const value = String(children || '').replace(/\n$/, '');
    if (inline) {
        return /*#__PURE__*/ React.createElement(InlineCode, {
            className: className
        }, children);
    }
    const language = getCodeLanguage(className) || 'text';
    return /*#__PURE__*/ React.createElement(CodeBlock, null, /*#__PURE__*/ React.createElement(CodeBlockHeader, null, /*#__PURE__*/ React.createElement(CodeLanguage, null, language)), /*#__PURE__*/ React.createElement(CodeBlockBody, null, /*#__PURE__*/ React.createElement(SyntaxHighlighter, {
        PreTag: "div",
        codeTagProps: {
            style: {
                fontFamily: 'SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace'
            }
        },
        customStyle: {
            margin: 0,
            padding: `var(${tokens.codeBlockPadding}, 1rem 1.125rem)`
        },
        language: language,
        style: syntaxTheme,
        wrapLongLines: true
    }, value)));
};
export const renderCode = (key, props)=>renderElement(key, CodeRenderer, props, props.children);
export const ImageRenderer = ({ alt, imageDisplay = 'inline', src, title })=>{
    const sanitizedSrc = sanitizeUrl(src);
    if (!sanitizedSrc) {
        return null;
    }
    const Image = imageDisplay === 'block' ? StyledBlockImage : StyledInlineImage;
    return /*#__PURE__*/ React.createElement(Image, {
        alt: alt || '',
        loading: "lazy",
        src: sanitizedSrc,
        title: title
    });
};
export const LinkRenderer = ({ href, children, title })=>{
    const sanitizedHref = sanitizeUrl(href);
    const isExternal = typeof sanitizedHref === 'string' && /^https?:\/\//.test(sanitizedHref);
    return /*#__PURE__*/ React.createElement("a", {
        href: sanitizedHref,
        rel: isExternal ? 'noreferrer noopener' : undefined,
        target: isExternal ? '_blank' : undefined,
        title: title
    }, children);
};
export const TableRenderer = ({ children })=>/*#__PURE__*/ React.createElement(TableScroll, null, /*#__PURE__*/ React.createElement("table", null, children));
