"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from "react";
import Markdown from "react-markdown";
import { cn } from "@stigmer/theme";
import { MARKDOWN_COMPONENTS, REMARK_PLUGINS, } from "../internal/markdown-components";
import { getArtifactRenderMode, } from "./artifact-utils";
/**
 * File-type-aware content renderer for execution artifacts.
 *
 * Determines the rendering strategy from the file name (via
 * {@link getArtifactRenderMode}) and dispatches to the appropriate
 * view:
 *
 * - **Markdown** (`.md`, `.mdx`) — rendered HTML via `react-markdown`
 *   with themed {@link MARKDOWN_COMPONENTS}, plus a source/rendered
 *   toggle so developers can inspect the raw markup.
 * - **YAML** (`.yaml`, `.yml`) — CSS-only syntax highlighting with
 *   key, comment, and value colorization.
 * - **JSON** (`.json`) — pretty-printed with basic key/value coloring.
 * - **Plain text** (all other extensions) — monospace display with
 *   line numbers.
 *
 * All visual properties flow through `--stgm-*` tokens. The component
 * is self-contained and works identically in the Stigmer Console and
 * in a third-party host application.
 *
 * Platform builders who want to render artifact content outside of
 * {@link ArtifactPreviewModal} can import this component directly:
 *
 * @example
 * ```tsx
 * import { ArtifactContentRenderer, useArtifactContent } from "@stigmer/react";
 *
 * function MyArtifactPanel({ executionId, storageKey, fileName }) {
 *   const { content } = useArtifactContent(executionId, storageKey);
 *   if (!content) return null;
 *   return <ArtifactContentRenderer content={content} fileName={fileName} />;
 * }
 * ```
 *
 * @see {@link getArtifactRenderMode} — pure utility for mode detection
 * @see {@link ArtifactPreviewModal} — full modal that composes this component
 * @see {@link useArtifactContent} — headless content-fetching hook
 */
export function ArtifactContentRenderer({ content, fileName, contentType, isTruncated = false, className, }) {
    const mode = getArtifactRenderMode(fileName, contentType);
    return (_jsxs("div", { className: cn(className), children: [mode === "markdown" ? (_jsx(MarkdownView, { content: content })) : mode === "yaml" ? (_jsx(YamlView, { content: content })) : mode === "json" ? (_jsx(JsonView, { content: content })) : (_jsx(PlainTextView, { content: content })), isTruncated && _jsx(TruncationWarning, {})] }));
}
function MarkdownView({ content }) {
    const [tab, setTab] = useState("rendered");
    return (_jsxs("div", { children: [_jsx("div", { className: "flex items-center border-b border-border px-4 py-1.5", children: _jsxs("div", { className: "inline-flex rounded-md bg-muted p-0.5", role: "tablist", "aria-label": "View mode", children: [_jsx(TabButton, { active: tab === "rendered", onClick: () => setTab("rendered"), label: "Rendered" }), _jsx(TabButton, { active: tab === "source", onClick: () => setTab("source"), label: "Source" })] }) }), tab === "rendered" ? (_jsx("div", { className: "p-5", children: _jsx(Markdown, { remarkPlugins: REMARK_PLUGINS, components: MARKDOWN_COMPONENTS, children: content }) })) : (_jsx(LineNumberedPre, { content: content }))] }));
}
function TabButton({ active, onClick, label, }) {
    return (_jsx("button", { type: "button", role: "tab", "aria-selected": active, onClick: onClick, className: cn("rounded-sm px-2.5 py-1 text-xs font-medium transition-colors", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", active
            ? "bg-background text-foreground shadow-sm"
            : "text-muted-foreground hover:text-foreground"), children: label }));
}
// ---------------------------------------------------------------------------
// YAML view (CSS-only syntax highlighting, zero dependencies)
// ---------------------------------------------------------------------------
/**
 * Applies lightweight CSS-only highlighting to YAML content.
 *
 * Processes content line-by-line, wrapping structural tokens in styled
 * `<span>` elements using `--stgm-*` theme tokens:
 *
 * - Keys → `text-primary`
 * - Comments → `text-muted-foreground italic`
 * - Document separators (`---`) → `text-muted-foreground`
 * - Boolean/null values → `font-medium`
 * - Multi-line scalar indicators → `text-muted-foreground`
 *
 * Values and block scalar content render in the default `text-foreground`.
 */
function highlightYaml(content) {
    return content.split("\n").map((line, i) => (_jsxs("span", { children: [i > 0 && "\n", highlightYamlLine(line)] }, i)));
}
function highlightYamlLine(line) {
    if (!line.trim())
        return line;
    if (/^---\s*$/.test(line) || /^\.\.\.\s*$/.test(line)) {
        return _jsx("span", { className: "text-muted-foreground", children: line });
    }
    const commentMatch = line.match(/^(\s*)(#.*)$/);
    if (commentMatch) {
        return (_jsxs(_Fragment, { children: [commentMatch[1], _jsx("span", { className: "text-muted-foreground italic", children: commentMatch[2] })] }));
    }
    const kvMatch = line.match(/^(\s*(?:-\s+)?)([\w][\w.-]*)(:(?:\s|$))(.*)/);
    if (kvMatch) {
        const [, indent, key, colon, value] = kvMatch;
        return (_jsxs(_Fragment, { children: [indent, _jsx("span", { className: "text-primary", children: key }), _jsx("span", { className: "text-muted-foreground", children: colon }), value ? highlightYamlValue(value) : null] }));
    }
    return _jsx(_Fragment, { children: line });
}
function highlightYamlValue(value) {
    const trimmed = value.trim();
    if (/^[|>][-+]?\s*$/.test(trimmed)) {
        return _jsx("span", { className: "text-muted-foreground", children: value });
    }
    if (/^(true|false|null|~)$/.test(trimmed)) {
        return _jsx("span", { className: "font-medium", children: value });
    }
    return _jsx(_Fragment, { children: value });
}
function YamlView({ content }) {
    return (_jsx("pre", { className: "overflow-x-auto p-4 font-mono text-xs leading-relaxed text-foreground", children: _jsx("code", { children: highlightYaml(content) }) }));
}
// ---------------------------------------------------------------------------
// JSON view (pretty-print + basic key coloring)
// ---------------------------------------------------------------------------
function highlightJson(content) {
    let formatted;
    try {
        formatted = JSON.stringify(JSON.parse(content), null, 2);
    }
    catch {
        formatted = content;
    }
    return formatted.split("\n").map((line, i) => {
        const keyMatch = line.match(/^(\s*)"([^"]+)"(\s*:)(.*)/);
        if (keyMatch) {
            const [, indent, key, colon, rest] = keyMatch;
            return (_jsxs("span", { children: [i > 0 && "\n", indent, _jsxs("span", { className: "text-primary", children: ["\"", key, "\""] }), _jsx("span", { className: "text-muted-foreground", children: colon }), highlightJsonValue(rest)] }, i));
        }
        return (_jsxs("span", { children: [i > 0 && "\n", line] }, i));
    });
}
function highlightJsonValue(value) {
    const trimmed = value.trim().replace(/,\s*$/, "");
    const trailingComma = value.trim().endsWith(",") ? "," : "";
    if (/^".*"$/.test(trimmed)) {
        return (_jsxs(_Fragment, { children: [" ", _jsx("span", { className: "text-success", children: trimmed }), trailingComma] }));
    }
    if (/^(true|false|null)$/.test(trimmed)) {
        return (_jsxs(_Fragment, { children: [" ", _jsx("span", { className: "font-medium", children: trimmed }), trailingComma] }));
    }
    if (/^-?\d/.test(trimmed)) {
        return (_jsxs(_Fragment, { children: [" ", _jsx("span", { className: "text-warning", children: trimmed }), trailingComma] }));
    }
    return _jsx(_Fragment, { children: value });
}
function JsonView({ content }) {
    return (_jsx("pre", { className: "overflow-x-auto p-4 font-mono text-xs leading-relaxed text-foreground", children: _jsx("code", { children: highlightJson(content) }) }));
}
// ---------------------------------------------------------------------------
// Plain text view (monospace + line numbers)
// ---------------------------------------------------------------------------
function PlainTextView({ content }) {
    return _jsx(LineNumberedPre, { content: content });
}
function LineNumberedPre({ content }) {
    const lines = content.split("\n");
    const gutterWidth = String(lines.length).length;
    return (_jsx("pre", { className: "overflow-x-auto font-mono text-xs leading-relaxed text-foreground", children: _jsx("code", { children: lines.map((line, i) => (_jsxs("span", { className: "flex", children: [_jsx("span", { className: "sticky left-0 select-none bg-background pr-4 text-right text-muted-foreground", style: { minWidth: `${gutterWidth + 2}ch` }, "aria-hidden": "true", children: i + 1 }), _jsx("span", { className: "flex-1 whitespace-pre pl-2", children: line || "\n" })] }, i))) }) }));
}
// ---------------------------------------------------------------------------
// Shared
// ---------------------------------------------------------------------------
function TruncationWarning() {
    return (_jsx("div", { className: "border-t border-border bg-warning/10 px-4 py-2 text-xs text-warning", children: "Content was truncated. Download the full file for complete content." }));
}
//# sourceMappingURL=ArtifactContentRenderer.js.map