"use client";
import * as React from 'react';
import { cva } from 'class-variance-authority';
import { FileText, Check, Copy } from 'lucide-react';
import { codeToHtml } from 'shiki';
import { cn } from '@hanzo/ui/lib/utils';
import { Badge } from '@hanzo/ui/badge';
import { Button } from '@hanzo/ui/button';
import { Skeleton } from '@hanzo/ui/skeleton';
import { jsxs, jsx } from 'react/jsx-runtime';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var codeBlockVariants = cva(
  "relative overflow-hidden rounded-lg border bg-muted/50",
  {
    variants: {
      theme: {
        dark: "bg-slate-950 border-slate-800",
        light: "bg-slate-50 border-slate-200",
        github: "bg-white border-slate-200",
        "github-dark": "bg-slate-900 border-slate-700",
        "vs-dark": "bg-slate-950 border-slate-800",
        monokai: "bg-slate-900 border-slate-700",
        dracula: "bg-slate-900 border-purple-800/30",
        nord: "bg-slate-800 border-slate-600"
      },
      size: {
        sm: "text-xs",
        default: "text-sm",
        lg: "text-base"
      }
    },
    defaultVariants: {
      theme: "dark",
      size: "default"
    }
  }
);
var CodeLine = React.memo(
  ({
    line,
    lineNumber,
    showLineNumbers,
    isHighlighted = false,
    isDiffAdded = false,
    isDiffRemoved = false
  }) => {
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn(
          "group relative flex min-h-[1.5rem] items-center px-4 py-0.5",
          isHighlighted && "bg-blue-500/10 border-l-2 border-l-blue-500",
          isDiffAdded && "bg-green-500/10 border-l-2 border-l-green-500",
          isDiffRemoved && "bg-red-500/10 border-l-2 border-l-red-500"
        ),
        children: [
          showLineNumbers && /* @__PURE__ */ jsx("span", { className: "mr-4 inline-block w-8 select-none text-right text-xs text-muted-foreground", children: lineNumber }),
          (isDiffAdded || isDiffRemoved) && /* @__PURE__ */ jsx("span", { className: "mr-2 select-none text-xs", children: isDiffAdded ? "+" : isDiffRemoved ? "-" : " " }),
          /* @__PURE__ */ jsx(
            "div",
            {
              className: "flex-1 overflow-x-auto",
              dangerouslySetInnerHTML: { __html: line }
            }
          )
        ]
      }
    );
  }
);
CodeLine.displayName = "CodeLine";
var CodeBlock = React.forwardRef(
  ({
    className,
    theme,
    size,
    code,
    language = "text",
    filename,
    showLineNumbers = true,
    highlightLines = [],
    showCopyButton = true,
    maxHeight = "400px",
    diff,
    ...props
  }, ref) => {
    const [highlightedCode, setHighlightedCode] = React.useState("");
    const [copied, setCopied] = React.useState(false);
    const [isLoading, setIsLoading] = React.useState(true);
    const themeMap = {
      dark: "github-dark",
      light: "github-light",
      github: "github-light",
      "github-dark": "github-dark",
      "vs-dark": "dark-plus",
      monokai: "monokai",
      dracula: "dracula",
      nord: "nord"
    };
    React.useEffect(() => {
      const highlightCode = /* @__PURE__ */ __name(async () => {
        setIsLoading(true);
        try {
          const highlighted = await codeToHtml(code, {
            lang: language,
            theme: themeMap[theme || "dark"],
            transformers: [
              {
                code(node) {
                  const codeElement2 = node.children.find(
                    (child) => child.type === "element" && child.tagName === "code"
                  );
                  if (codeElement2 && "children" in codeElement2 && codeElement2.children) {
                    node.children = codeElement2.children;
                  }
                }
              }
            ]
          });
          const tempDiv = document.createElement("div");
          tempDiv.innerHTML = highlighted;
          const codeElement = tempDiv.querySelector("code");
          setHighlightedCode(codeElement?.innerHTML || highlighted);
        } catch (error) {
          console.error("Failed to highlight code:", error);
          setHighlightedCode(code);
        } finally {
          setIsLoading(false);
        }
      }, "highlightCode");
      highlightCode();
    }, [code, language, theme]);
    const copyToClipboard = React.useCallback(async () => {
      try {
        await navigator.clipboard.writeText(code);
        setCopied(true);
        setTimeout(() => setCopied(false), 2e3);
      } catch (error) {
        console.error("Failed to copy code:", error);
      }
    }, [code]);
    const lines = highlightedCode.split("\n");
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        "data-testid": "code-block",
        className: cn(codeBlockVariants({ theme, size, className })),
        ...props,
        children: [
          (filename || language || showCopyButton) && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              filename && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
                /* @__PURE__ */ jsx(FileText, { className: "h-3.5 w-3.5 text-muted-foreground" }),
                /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: filename })
              ] }),
              language && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: language })
            ] }),
            showCopyButton && /* @__PURE__ */ jsxs(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: copyToClipboard,
                className: "h-8 w-8 p-0",
                children: [
                  copied ? /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5 text-green-500" }) : /* @__PURE__ */ jsx(Copy, { className: "h-3.5 w-3.5" }),
                  /* @__PURE__ */ jsx("span", { className: "sr-only", children: copied ? "Copied" : "Copy code" })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: "overflow-auto", style: { maxHeight }, children: isLoading ? /* @__PURE__ */ jsx("div", { className: "p-4 space-y-2", children: Array.from({ length: 10 }).map((_, i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
            showLineNumbers && /* @__PURE__ */ jsx(Skeleton, { "data-testid": "skeleton", className: "h-4 w-8" }),
            /* @__PURE__ */ jsx(Skeleton, { "data-testid": "skeleton", className: "h-4 flex-1" })
          ] }, i)) }) : /* @__PURE__ */ jsx("div", { className: "font-mono", children: lines.map((line, index) => {
            const lineNumber = index + 1;
            const isHighlighted = highlightLines.includes(lineNumber);
            const isDiffAdded = diff?.added?.includes(lineNumber);
            const isDiffRemoved = diff?.removed?.includes(lineNumber);
            return /* @__PURE__ */ jsx(
              CodeLine,
              {
                line,
                lineNumber,
                showLineNumbers,
                isHighlighted,
                isDiffAdded,
                isDiffRemoved
              },
              index
            );
          }) }) })
        ]
      }
    );
  }
);
CodeBlock.displayName = "CodeBlock";

export { CodeBlock, codeBlockVariants };
