"use client";
import { Loader2, RotateCcw, Download } from 'lucide-react';
import mermaid from 'mermaid';
import * as React from 'react';
import { useRef, useState, useCallback, useEffect } from 'react';
import { toast } from 'sonner';
import svgPanZoom from 'svg-pan-zoom';
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { Slot } from '@radix-ui/react-slot';
import { cva } from 'class-variance-authority';
import { jsxs, jsx } from 'react/jsx-runtime';
import * as TooltipPrimitive from '@radix-ui/react-tooltip';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
function cn(...inputs) {
  return twMerge(clsx(inputs));
}
__name(cn, "cn");
var buttonVariants = cva(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
        destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
        outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
        secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline",
        // Keep the additional Hanzo variants for backward compatibility
        primary: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
        linkFG: "text-primary underline-offset-4 hover:underline",
        linkMuted: "text-muted-foreground underline-offset-4 hover:underline hover:text-foreground"
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-10 rounded-md px-8",
        icon: "h-9 w-9"
      }
    },
    defaultVariants: {
      variant: "default",
      size: "default"
    }
  }
);
var Button = React.forwardRef(
  ({ className, variant, size, asChild = false, isLoading = false, children, ...props }, ref) => {
    const Comp = asChild ? Slot : "button";
    return /* @__PURE__ */ jsxs(
      Comp,
      {
        className: cn(buttonVariants({ variant, size, className })),
        ref,
        ...props,
        children: [
          isLoading ? /* @__PURE__ */ jsx(
            Loader2,
            {
              className: cn("h-4 w-4 animate-spin", size !== "icon" && "mr-2")
            }
          ) : null,
          isLoading && size === "icon" ? null : children
        ]
      }
    );
  }
);
Button.displayName = "Button";
var Tooltip = TooltipPrimitive.Root;
var TooltipTrigger = TooltipPrimitive.Trigger;
var TooltipContent = /* @__PURE__ */ __name(({
  className,
  sideOffset = 4,
  showArrow = true,
  ...props
}) => /* @__PURE__ */ jsxs(
  TooltipPrimitive.Content,
  {
    className: cn(
      "border-divider bg-bg-dark animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-w-[280px] rounded-lg border px-3 py-1.5 text-xs text-white",
      className
    ),
    sideOffset,
    ...props,
    children: [
      props.children,
      showArrow && /* @__PURE__ */ jsx(TooltipPrimitive.Arrow, { className: "fill-bg-dark -my-px drop-shadow-[0_1px_0_#313336]" })
    ]
  }
), "TooltipContent");
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
mermaid.initialize({
  startOnLoad: true,
  mindmap: {
    useWidth: 800
  },
  theme: "dark",
  fontSize: 18,
  darkMode: true,
  fontFamily: "Inter"
});
var generateId = /* @__PURE__ */ __name(() => `mermaid-${Math.random().toString(36).slice(2)}`, "generateId");
var downloadBlob = /* @__PURE__ */ __name(async (blob, filename) => {
  try {
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);
    toast.success("Mermaid diagram saved successfully");
  } catch (error) {
    toast.error("Failed to download diagram");
  }
}, "downloadBlob");
var MermaidDiagram = /* @__PURE__ */ __name(({
  code,
  className,
  isRunning
}) => {
  const ref = useRef(null);
  const lastCode = useRef(null);
  const [instance, setInstance] = useState(null);
  const isComplete = !isRunning;
  const resetZoom = useCallback(() => {
    instance?.fit();
    instance?.center();
  }, [instance]);
  const downloadSVG = useCallback(() => {
    if (ref.current) {
      const svg = ref.current.innerHTML;
      const blob = new Blob([svg], { type: "image/svg+xml" });
      void downloadBlob(blob, "mermaid-diagram.svg");
    }
  }, []);
  const enableZoom = useCallback(() => {
    instance?.enablePan();
    instance?.enableZoom();
  }, [instance]);
  const disableZoom = useCallback(() => {
    instance?.disablePan();
    instance?.disableZoom();
  }, [instance]);
  const handleFocus = useCallback(() => {
    enableZoom();
  }, [enableZoom]);
  const handleBlur = useCallback(() => {
    disableZoom();
  }, [disableZoom]);
  const handleClick = useCallback(() => {
    if (ref.current) {
      ref.current.focus();
    }
  }, []);
  useEffect(() => {
    if (!isComplete || !ref.current || !code) return;
    if (lastCode.current === code) return;
    void (async () => {
      try {
        const id = generateId();
        const { svg } = await mermaid.render(id, code);
        if (ref.current) {
          ref.current.innerHTML = svg;
          const svgElement = ref.current.querySelector("svg");
          if (svgElement) {
            svgElement.setAttribute("height", "100%");
            svgElement.setAttribute("width", "100%");
            svgElement.style.height = "100%";
            svgElement.style.width = "100%";
            svgElement.style.position = "absolute";
            svgElement.style.top = "0";
            svgElement.style.left = "0";
            const panZoomInstance = svgPanZoom(svgElement);
            panZoomInstance.fit();
            panZoomInstance.center();
            panZoomInstance.zoomAtPoint(1, { x: 0, y: 0 });
            panZoomInstance.disablePan();
            panZoomInstance.disableZoom();
            setInstance(panZoomInstance);
          }
        }
        lastCode.current = code;
      } catch (e) {
        console.warn("Failed to render Mermaid diagram:", e);
      }
    })();
  }, [code, isComplete]);
  return /* @__PURE__ */ jsxs("div", { className: "relative", children: [
    /* @__PURE__ */ jsxs("div", { className: "absolute top-2 right-2 z-10 flex gap-1", children: [
      /* @__PURE__ */ jsxs(Tooltip, { children: [
        /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
          Button,
          {
            variant: "ghost",
            size: "icon",
            onClick: resetZoom,
            className: "text-text-secondary",
            children: /* @__PURE__ */ jsx(RotateCcw, { size: 14 })
          }
        ) }),
        /* @__PURE__ */ jsx(TooltipContent, { children: /* @__PURE__ */ jsx("p", { children: "Reset Zoom" }) })
      ] }),
      /* @__PURE__ */ jsxs(Tooltip, { children: [
        /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
          Button,
          {
            variant: "ghost",
            size: "icon",
            onClick: downloadSVG,
            className: "text-text-secondary",
            children: /* @__PURE__ */ jsx(Download, { size: 14 })
          }
        ) }),
        /* @__PURE__ */ jsx(TooltipContent, { children: /* @__PURE__ */ jsx("p", { children: "Download SVG" }) })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      "div",
      {
        onClick: handleClick,
        className: "text-text-secondary bg-bg-quaternary absolute right-2 bottom-2 z-10 rounded px-2 py-1 text-xs",
        children: "Click to focus, then scroll to zoom & drag to pan"
      }
    ),
    /* @__PURE__ */ jsx(
      "div",
      {
        ref,
        tabIndex: 0,
        onFocus: handleFocus,
        onBlur: handleBlur,
        onClick: handleClick,
        className: cn(
          "text-text-secondary bg-bg-quaternary focus:ring-opacity-50 relative w-full cursor-grab overflow-hidden rounded-b-lg p-4 py-10 text-center text-sm focus:cursor-grabbing focus:ring-2 focus:ring-blue-500 focus:outline-none",
          className
        ),
        style: { width: "100%", minHeight: "400px" },
        children: "Drawing diagram..."
      }
    )
  ] });
}, "MermaidDiagram");

export { MermaidDiagram };
