import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import { tcx } from "@choiceform/design-system";
import mermaid_default from "../../../../../_vendor/mermaid/dist-mermaid.core.js";
import { forwardRef, useRef, useState, useEffect } from "react";
import { surveyToMermaid } from "../../../../../utils/survey-to-mermaid.js";
import { MessageMermaidDiagramTv } from "./tv.js";
import RefreshCw from "../../../../../_vendor/lucide-react/dist-esm-icons-refresh-cw.js";
import Copy from "../../../../../_vendor/lucide-react/dist-esm-icons-copy.js";
import Download from "../../../../../_vendor/lucide-react/dist-esm-icons-download.js";
const MessageMermaidDiagram = forwardRef(
  function MessageMermaidDiagram2({
    survey,
    title = "Generated Mermaid Diagram",
    showCode = false,
    className,
    mermaidConfig = {
      theme: "default",
      themeVariables: {
        darkMode: false
      }
    },
    ...props
  }, ref) {
    const mermaidRef = useRef(null);
    const [mermaidCode, setMermaidCode] = useState("");
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showCodeView, setShowCodeView] = useState(showCode);
    const styles = MessageMermaidDiagramTv();
    useEffect(() => {
      mermaid_default.initialize({
        startOnLoad: true,
        ...mermaidConfig
      });
    }, [mermaidConfig]);
    useEffect(() => {
      const renderDiagram = async () => {
        if (!mermaidRef.current) return;
        try {
          setIsLoading(true);
          setError(null);
          const code = surveyToMermaid(survey);
          setMermaidCode(code);
          mermaidRef.current.innerHTML = "";
          const id = `mermaid-${Date.now()}`;
          const { svg } = await mermaid_default.render(id, code);
          mermaidRef.current.innerHTML = svg;
        } catch (err) {
          console.error("Mermaid rendering error:", err);
          setError(err instanceof Error ? err.message : "Failed to render diagram");
        } finally {
          setIsLoading(false);
        }
      };
      renderDiagram();
    }, [survey]);
    const handleCopy = async () => {
      try {
        await navigator.clipboard.writeText(mermaidCode);
      } catch (err) {
        console.error("Failed to copy:", err);
      }
    };
    const handleDownload = () => {
      const blob = new Blob([mermaidCode], { type: "text/plain" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `survey-${survey.id}.mmd`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    };
    const handleRefresh = () => {
      const renderDiagram = async () => {
        if (!mermaidRef.current) return;
        try {
          setIsLoading(true);
          const code = surveyToMermaid(survey);
          mermaidRef.current.innerHTML = "";
          const id = `mermaid-${Date.now()}`;
          const { svg } = await mermaid_default.render(id, code);
          mermaidRef.current.innerHTML = svg;
        } catch (err) {
          console.error("Mermaid rendering error:", err);
        } finally {
          setIsLoading(false);
        }
      };
      renderDiagram();
    };
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: tcx(styles.root(), className),
        ...props,
        children: [
          /* @__PURE__ */ jsx("div", { className: styles.header(), children: /* @__PURE__ */ jsx("h2", { className: styles.title(), children: title }) }),
          /* @__PURE__ */ jsxs("div", { className: styles.container(), children: [
            /* @__PURE__ */ jsxs("div", { className: styles.toolbar(), children: [
              /* @__PURE__ */ jsxs("div", { className: styles.toolbarLeft(), children: [
                /* @__PURE__ */ jsx("span", { className: styles.label(), children: "Mermaid" }),
                /* @__PURE__ */ jsx("span", { className: styles.sublabel(), children: "flowchart" })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: styles.toolbarRight(), children: [
                /* @__PURE__ */ jsx(
                  "button",
                  {
                    type: "button",
                    onClick: () => setShowCodeView(!showCodeView),
                    className: styles.button(),
                    title: showCodeView ? "Show diagram" : "Show code",
                    children: /* @__PURE__ */ jsx(
                      "svg",
                      {
                        className: "h-4 w-4",
                        viewBox: "0 0 24 24",
                        fill: "none",
                        stroke: "currentColor",
                        children: /* @__PURE__ */ jsx(
                          "path",
                          {
                            d: "M16 18l6-6-6-6M8 6l-6 6 6 6",
                            strokeWidth: "2",
                            strokeLinecap: "round",
                            strokeLinejoin: "round"
                          }
                        )
                      }
                    )
                  }
                ),
                /* @__PURE__ */ jsx(
                  "button",
                  {
                    type: "button",
                    onClick: handleRefresh,
                    className: styles.button(),
                    title: "Refresh",
                    disabled: isLoading,
                    children: /* @__PURE__ */ jsx(RefreshCw, { className: tcx("h-4 w-4", isLoading && "animate-spin") })
                  }
                ),
                /* @__PURE__ */ jsx(
                  "button",
                  {
                    type: "button",
                    onClick: handleCopy,
                    className: styles.button(),
                    title: "Copy code",
                    children: /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" })
                  }
                ),
                /* @__PURE__ */ jsx(
                  "button",
                  {
                    type: "button",
                    onClick: handleDownload,
                    className: styles.button(),
                    title: "Download",
                    children: /* @__PURE__ */ jsx(Download, { className: "h-4 w-4" })
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsx("div", { className: styles.content(), children: error ? /* @__PURE__ */ jsxs("div", { className: styles.error(), children: [
              /* @__PURE__ */ jsx("p", { className: "font-strong", children: "Error rendering diagram" }),
              /* @__PURE__ */ jsx("p", { className: "text-body-small mt-1", children: error })
            ] }) : showCodeView ? /* @__PURE__ */ jsx("pre", { className: styles.code(), children: /* @__PURE__ */ jsx("code", { children: mermaidCode }) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(
                "div",
                {
                  ref: mermaidRef,
                  className: styles.diagram()
                }
              ),
              isLoading && /* @__PURE__ */ jsx("div", { className: styles.loading(), children: /* @__PURE__ */ jsx("div", { className: "border-primary h-8 w-8 animate-spin rounded-full border-2 border-t-transparent" }) })
            ] }) })
          ] })
        ]
      }
    );
  }
);
export {
  MessageMermaidDiagram
};
//# sourceMappingURL=message-mermaid-diagram.js.map
