"use client";
import * as React6 from 'react';
import { cva } from 'class-variance-authority';
import { FileText, Check, Copy, MoreHorizontal, RotateCcw, Settings, GitCompare, Plus, Minus, Square, SplitSquareHorizontal, ChevronDown, FolderOpen, Folder, ChevronRight, Search, X, Eye, EyeOff, Terminal, RefreshCw, Play, AlertTriangle, Download, Minimize2, Maximize2, File, FileImage, FileCode } from 'lucide-react';
import { codeToHtml, bundledLanguages } 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, Fragment } from 'react/jsx-runtime';
import { CodeDiff } from '@hanzo/ui/code/diff';
import { CodeSnippet } from '@hanzo/ui/code/snippet';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@hanzo/ui/dropdown-menu';
import { ScrollArea } from '@hanzo/ui/scroll-area';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@hanzo/ui/tabs';
import { ToggleGroup, ToggleGroupItem } from '@hanzo/ui/toggle-group';
import Editor from '@monaco-editor/react';
import { useTheme } from 'next-themes';
import { Input } from '@hanzo/ui/input';
import { Separator } from '@hanzo/ui/separator';
import { Toggle } from '@hanzo/ui/toggle';

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 = React6.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 = React6.forwardRef(
  ({
    className,
    theme,
    size,
    code,
    language = "text",
    filename,
    showLineNumbers = true,
    highlightLines = [],
    showCopyButton = true,
    maxHeight = "400px",
    diff,
    ...props
  }, ref) => {
    const [highlightedCode, setHighlightedCode] = React6.useState("");
    const [copied, setCopied] = React6.useState(false);
    const [isLoading, setIsLoading] = React6.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"
    };
    React6.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 = React6.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";
var codeCompareVariants = cva(
  "relative flex flex-col overflow-hidden rounded-lg border bg-background",
  {
    variants: {
      layout: {
        horizontal: "flex-col",
        vertical: "flex-row"
      },
      size: {
        sm: "text-xs",
        default: "text-sm",
        lg: "text-base"
      }
    },
    defaultVariants: {
      layout: "horizontal",
      size: "default"
    }
  }
);
var CodeCompare = React6.forwardRef(
  ({
    className,
    layout,
    size,
    files,
    defaultView = "side-by-side",
    showLineNumbers = true,
    showCopyButton = true,
    allowMerge = false,
    conflictMarkers = [],
    onMergeConflict,
    onFileSelect,
    height = "600px",
    syncScroll = true,
    ...props
  }, ref) => {
    const [view, setView] = React6.useState(defaultView);
    const [selectedFiles, setSelectedFiles] = React6.useState(() => {
      if (files.length >= 2) {
        return [files[0].id, files[1].id];
      }
      return files.length > 0 ? [files[0].id] : [];
    });
    const [mergeState, setMergeState] = React6.useState({
      resolved: {},
      conflicts: conflictMarkers
    });
    const [copied, setCopied] = React6.useState(false);
    const scrollRefs = React6.useRef({});
    const handleScroll = React6.useCallback(
      (sourceId, scrollTop) => {
        if (!syncScroll) return;
        Object.entries(scrollRefs.current).forEach(([id, ref2]) => {
          if (id !== sourceId && ref2) {
            ref2.scrollTop = scrollTop;
          }
        });
      },
      [syncScroll]
    );
    const copyComparison = React6.useCallback(async () => {
      const comparison = selectedFiles.map((fileId) => {
        const file = files.find((f) => f.id === fileId);
        return file ? `=== ${file.filename} ===
${file.content}` : "";
      }).join("\n\n");
      try {
        await navigator.clipboard.writeText(comparison);
        setCopied(true);
        setTimeout(() => setCopied(false), 2e3);
      } catch (error) {
        console.error("Failed to copy comparison:", error);
      }
    }, [files, selectedFiles]);
    const resolveConflict = React6.useCallback(
      (conflictIndex, resolution) => {
        setMergeState((prev) => ({
          ...prev,
          resolved: {
            ...prev.resolved,
            [conflictIndex]: resolution
          }
        }));
        onMergeConflict?.(resolution);
      },
      [onMergeConflict]
    );
    const getFileStats = React6.useCallback(
      (file1, file2) => {
        const lines1 = file1.content.split("\n");
        const lines2 = file2.content.split("\n");
        let added = 0;
        let removed = 0;
        let modified = 0;
        const maxLines = Math.max(lines1.length, lines2.length);
        for (let i = 0; i < maxLines; i++) {
          const line1 = lines1[i];
          const line2 = lines2[i];
          if (line1 === void 0) {
            added++;
          } else if (line2 === void 0) {
            removed++;
          } else if (line1 !== line2) {
            modified++;
          }
        }
        return { added, removed, modified };
      },
      []
    );
    const renderFileSelector = /* @__PURE__ */ __name(() => /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 flex-wrap", children: files.map((file, index) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          variant: selectedFiles.includes(file.id) ? "default" : "outline",
          size: "sm",
          onClick: () => {
            if (view === "three-way") {
              setSelectedFiles((prev) => {
                if (prev.includes(file.id)) {
                  return prev.filter((id) => id !== file.id);
                }
                return prev.length < 3 ? [...prev, file.id] : [prev[1], prev[2], file.id];
              });
            } else {
              setSelectedFiles((prev) => {
                if (prev.includes(file.id)) {
                  return prev.filter((id) => id !== file.id);
                }
                return prev.length < 2 ? [...prev, file.id] : [prev[1], file.id];
              });
            }
            onFileSelect?.(file.id);
          },
          className: "gap-2",
          children: [
            file.label || file.filename,
            file.version && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: file.version })
          ]
        }
      ),
      index < files.length - 1 && view !== "three-way" && /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "vs" })
    ] }, file.id)) }), "renderFileSelector");
    const renderSideBySide = /* @__PURE__ */ __name(() => {
      const [file1, file2] = selectedFiles.map((id) => files.find((f) => f.id === id)).filter(Boolean);
      if (!file1 || !file2) {
        return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-32 text-muted-foreground", children: "Select two files to compare" });
      }
      const stats = getFileStats(file1, file2);
      return /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full", children: [
        /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between border-b px-4 py-2 bg-muted/30", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
          /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Comparison" }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 text-xs", children: [
            /* @__PURE__ */ jsxs("span", { className: "text-green-600", children: [
              "+",
              stats.added
            ] }),
            /* @__PURE__ */ jsxs("span", { className: "text-red-600", children: [
              "-",
              stats.removed
            ] }),
            /* @__PURE__ */ jsxs("span", { className: "text-yellow-600", children: [
              "~",
              stats.modified
            ] })
          ] })
        ] }) }),
        /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-0", children: /* @__PURE__ */ jsx(
          CodeDiff,
          {
            oldCode: file1.content,
            newCode: file2.content,
            language: file1.language,
            oldFilename: file1.filename,
            newFilename: file2.filename,
            showLineNumbers,
            showCopyButton: false,
            maxHeight: "100%",
            defaultView: "split",
            className: "border-0 rounded-none h-full"
          }
        ) })
      ] });
    }, "renderSideBySide");
    const renderUnified = /* @__PURE__ */ __name(() => {
      const [file1, file2] = selectedFiles.map((id) => files.find((f) => f.id === id)).filter(Boolean);
      if (!file1 || !file2) {
        return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-32 text-muted-foreground", children: "Select two files to compare" });
      }
      return /* @__PURE__ */ jsx(
        CodeDiff,
        {
          oldCode: file1.content,
          newCode: file2.content,
          language: file1.language,
          filename: `${file1.filename} \u2192 ${file2.filename}`,
          showLineNumbers,
          showCopyButton: false,
          maxHeight: "100%",
          defaultView: "unified",
          className: "border-0 rounded-none"
        }
      );
    }, "renderUnified");
    const renderThreeWay = /* @__PURE__ */ __name(() => {
      const [base, current, incoming] = selectedFiles.map((id) => files.find((f) => f.id === id)).filter(Boolean);
      if (!base || !current || !incoming) {
        return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-32 text-muted-foreground", children: "Select three files for three-way merge (base, current, incoming)" });
      }
      return /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-0 h-full", children: [
        /* @__PURE__ */ jsxs("div", { className: "border-r", children: [
          /* @__PURE__ */ jsx("div", { className: "border-b px-4 py-2 bg-muted/30", children: /* @__PURE__ */ jsxs("span", { className: "text-sm font-medium", children: [
            "Base (",
            base.filename,
            ")"
          ] }) }),
          /* @__PURE__ */ jsx(
            ScrollArea,
            {
              className: "h-full",
              ref: (ref2) => {
                scrollRefs.current["base"] = ref2;
              },
              onScrollCapture: (e) => {
                const target = e.target;
                handleScroll("base", target.scrollTop);
              },
              children: /* @__PURE__ */ jsx(
                CodeSnippet,
                {
                  code: base.content,
                  language: base.language,
                  showLineNumbers,
                  showCopyButton: false,
                  showHeader: false,
                  className: "border-0 rounded-none"
                }
              )
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "border-r", children: [
          /* @__PURE__ */ jsx("div", { className: "border-b px-4 py-2 bg-blue-500/10", children: /* @__PURE__ */ jsxs("span", { className: "text-sm font-medium text-blue-600 dark:text-blue-400", children: [
            "Current (",
            current.filename,
            ")"
          ] }) }),
          /* @__PURE__ */ jsx(
            ScrollArea,
            {
              className: "h-full",
              ref: (ref2) => {
                scrollRefs.current["current"] = ref2;
              },
              onScrollCapture: (e) => {
                const target = e.target;
                handleScroll("current", target.scrollTop);
              },
              children: /* @__PURE__ */ jsx(
                CodeSnippet,
                {
                  code: current.content,
                  language: current.language,
                  showLineNumbers,
                  showCopyButton: false,
                  showHeader: false,
                  className: "border-0 rounded-none"
                }
              )
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("div", { className: "border-b px-4 py-2 bg-green-500/10", children: /* @__PURE__ */ jsxs("span", { className: "text-sm font-medium text-green-600 dark:text-green-400", children: [
            "Incoming (",
            incoming.filename,
            ")"
          ] }) }),
          /* @__PURE__ */ jsx(
            ScrollArea,
            {
              className: "h-full",
              ref: (ref2) => {
                scrollRefs.current["incoming"] = ref2;
              },
              onScrollCapture: (e) => {
                const target = e.target;
                handleScroll("incoming", target.scrollTop);
              },
              children: /* @__PURE__ */ jsx(
                CodeSnippet,
                {
                  code: incoming.content,
                  language: incoming.language,
                  showLineNumbers,
                  showCopyButton: false,
                  showHeader: false,
                  className: "border-0 rounded-none"
                }
              )
            }
          )
        ] })
      ] });
    }, "renderThreeWay");
    const renderMergeConflicts = /* @__PURE__ */ __name(() => {
      if (!allowMerge || mergeState.conflicts.length === 0) return null;
      return /* @__PURE__ */ jsx("div", { className: "border-t bg-muted/30", children: /* @__PURE__ */ jsxs("div", { className: "px-4 py-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Merge Conflicts" }),
          /* @__PURE__ */ jsx(Badge, { variant: "destructive", className: "text-xs", children: mergeState.conflicts.length })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "mt-2 space-y-2", children: mergeState.conflicts.map((conflict, index) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
          /* @__PURE__ */ jsxs("span", { children: [
            "Lines ",
            conflict.startLine,
            "-",
            conflict.endLine
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: () => resolveConflict(index, "current"),
                className: "h-6 text-xs",
                children: "Keep Current"
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: () => resolveConflict(index, "incoming"),
                className: "h-6 text-xs",
                children: "Accept Incoming"
              }
            )
          ] })
        ] }, index)) })
      ] }) });
    }, "renderMergeConflicts");
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(codeCompareVariants({ layout, size }), className),
        style: { height },
        ...props,
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2", children: [
            /* @__PURE__ */ jsx("div", { className: "flex items-center gap-4", children: renderFileSelector() }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Tabs, { value: view, onValueChange: (value) => setView(value), children: /* @__PURE__ */ jsxs(TabsList, { className: "grid w-full grid-cols-3", children: [
                /* @__PURE__ */ jsx(TabsTrigger, { value: "side-by-side", className: "text-xs", children: "Side by Side" }),
                /* @__PURE__ */ jsx(TabsTrigger, { value: "unified", className: "text-xs", children: "Unified" }),
                /* @__PURE__ */ jsx(TabsTrigger, { value: "three-way", className: "text-xs", children: "Three-way" })
              ] }) }),
              showCopyButton && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: copyComparison,
                  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__ */ jsxs(DropdownMenu, { children: [
                /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", className: "h-8 w-8 p-0", children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-3.5 w-3.5" }) }) }),
                /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
                  /* @__PURE__ */ jsxs(
                    DropdownMenuItem,
                    {
                      onClick: () => setSelectedFiles([]),
                      className: "gap-2",
                      children: [
                        /* @__PURE__ */ jsx(RotateCcw, { className: "h-4 w-4" }),
                        "Reset Selection"
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsxs(DropdownMenuItem, { className: "gap-2", children: [
                    /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" }),
                    "Settings"
                  ] })
                ] })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1 min-h-0", children: [
            view === "side-by-side" && renderSideBySide(),
            view === "unified" && renderUnified(),
            view === "three-way" && renderThreeWay()
          ] }),
          renderMergeConflicts()
        ]
      }
    );
  }
);
CodeCompare.displayName = "CodeCompare";
var codeDiffVariants = 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"
      },
      size: {
        sm: "text-xs",
        default: "text-sm",
        lg: "text-base"
      }
    },
    defaultVariants: {
      theme: "dark",
      size: "default"
    }
  }
);
var DiffLine = React6.memo(
  ({
    change,
    showLineNumbers,
    isUnified = false,
    highlightedContent
  }) => {
    const getLineClasses = /* @__PURE__ */ __name(() => {
      const base = "group relative flex min-h-[1.5rem] items-center py-0.5";
      if (isUnified) {
        switch (change.type) {
          case "add":
            return cn(base, "bg-green-500/10 border-l-2 border-l-green-500");
          case "remove":
            return cn(base, "bg-red-500/10 border-l-2 border-l-red-500");
          default:
            return cn(base, "hover:bg-muted/50");
        }
      }
      return cn(base, "hover:bg-muted/50");
    }, "getLineClasses");
    const getLinePrefix = /* @__PURE__ */ __name(() => {
      if (!isUnified) return null;
      switch (change.type) {
        case "add":
          return /* @__PURE__ */ jsx(Plus, { className: "h-3 w-3 text-green-500 mr-2 flex-shrink-0" });
        case "remove":
          return /* @__PURE__ */ jsx(Minus, { className: "h-3 w-3 text-red-500 mr-2 flex-shrink-0" });
        default:
          return /* @__PURE__ */ jsx("span", { className: "w-3 mr-2 flex-shrink-0" });
      }
    }, "getLinePrefix");
    return /* @__PURE__ */ jsx("div", { className: getLineClasses(), children: /* @__PURE__ */ jsxs("div", { className: "flex items-center px-4 w-full", children: [
      showLineNumbers && /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 mr-4", children: !isUnified ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("span", { className: "inline-block w-8 select-none text-right text-xs text-muted-foreground", children: change.oldLineNumber || "" }),
        /* @__PURE__ */ jsx("span", { className: "inline-block w-8 select-none text-right text-xs text-muted-foreground", children: change.newLineNumber || "" })
      ] }) : /* @__PURE__ */ jsx("span", { className: "inline-block w-8 select-none text-right text-xs text-muted-foreground", children: change.lineNumber }) }),
      getLinePrefix(),
      /* @__PURE__ */ jsx(
        "div",
        {
          className: "flex-1 overflow-x-auto font-mono",
          dangerouslySetInnerHTML: {
            __html: highlightedContent || change.content
          }
        }
      )
    ] }) });
  }
);
DiffLine.displayName = "DiffLine";
function generateDiff(oldCode, newCode) {
  const oldLines = oldCode.split("\n");
  const newLines = newCode.split("\n");
  const changes = [];
  let oldIndex = 0;
  let newIndex = 0;
  let lineNumber = 1;
  while (oldIndex < oldLines.length || newIndex < newLines.length) {
    const oldLine = oldLines[oldIndex];
    const newLine = newLines[newIndex];
    if (oldIndex >= oldLines.length) {
      changes.push({
        type: "add",
        lineNumber: lineNumber++,
        content: newLine,
        newLineNumber: newIndex + 1
      });
      newIndex++;
    } else if (newIndex >= newLines.length) {
      changes.push({
        type: "remove",
        lineNumber: lineNumber++,
        content: oldLine,
        oldLineNumber: oldIndex + 1
      });
      oldIndex++;
    } else if (oldLine === newLine) {
      changes.push({
        type: "unchanged",
        lineNumber: lineNumber++,
        content: oldLine,
        oldLineNumber: oldIndex + 1,
        newLineNumber: newIndex + 1
      });
      oldIndex++;
      newIndex++;
    } else {
      changes.push({
        type: "remove",
        lineNumber: lineNumber++,
        content: oldLine,
        oldLineNumber: oldIndex + 1
      });
      changes.push({
        type: "add",
        lineNumber: lineNumber++,
        content: newLine,
        newLineNumber: newIndex + 1
      });
      oldIndex++;
      newIndex++;
    }
  }
  return changes;
}
__name(generateDiff, "generateDiff");
var CodeDiff2 = React6.forwardRef(
  ({
    className,
    theme,
    size,
    oldCode,
    newCode,
    language = "text",
    filename,
    oldFilename,
    newFilename,
    showLineNumbers = true,
    showCopyButton = true,
    maxHeight = "500px",
    defaultView = "unified",
    collapseUnchanged = false,
    contextLines = 3,
    ...props
  }, ref) => {
    const [view, setView] = React6.useState(defaultView);
    const [copied, setCopied] = React6.useState(false);
    const [isLoading, setIsLoading] = React6.useState(true);
    const [highlightedOldCode, setHighlightedOldCode] = React6.useState("");
    const [highlightedNewCode, setHighlightedNewCode] = React6.useState("");
    const [changes, setChanges] = React6.useState([]);
    const themeMap = {
      dark: "github-dark",
      light: "github-light",
      github: "github-light",
      "github-dark": "github-dark"
    };
    React6.useEffect(() => {
      const highlightCode = /* @__PURE__ */ __name(async () => {
        setIsLoading(true);
        try {
          const [oldHighlighted, newHighlighted] = await Promise.all([
            codeToHtml(oldCode, {
              lang: language,
              theme: themeMap[theme || "dark"]
            }),
            codeToHtml(newCode, {
              lang: language,
              theme: themeMap[theme || "dark"]
            })
          ]);
          const extractContent = /* @__PURE__ */ __name((html) => {
            const tempDiv = document.createElement("div");
            tempDiv.innerHTML = html;
            const codeElement = tempDiv.querySelector("code");
            return codeElement?.innerHTML || html;
          }, "extractContent");
          setHighlightedOldCode(extractContent(oldHighlighted));
          setHighlightedNewCode(extractContent(newHighlighted));
          const diffChanges = generateDiff(oldCode, newCode);
          setChanges(diffChanges);
        } catch (error) {
          console.error("Failed to highlight code:", error);
          setHighlightedOldCode(oldCode);
          setHighlightedNewCode(newCode);
          setChanges(generateDiff(oldCode, newCode));
        } finally {
          setIsLoading(false);
        }
      }, "highlightCode");
      highlightCode();
    }, [oldCode, newCode, language, theme]);
    const copyToClipboard = React6.useCallback(async () => {
      try {
        const diffText = view === "unified" ? changes.map((change) => {
          const prefix = change.type === "add" ? "+" : change.type === "remove" ? "-" : " ";
          return `${prefix}${change.content}`;
        }).join("\n") : `--- ${oldFilename || "old"}
+++ ${newFilename || "new"}
${oldCode}

${newCode}`;
        await navigator.clipboard.writeText(diffText);
        setCopied(true);
        setTimeout(() => setCopied(false), 2e3);
      } catch (error) {
        console.error("Failed to copy diff:", error);
      }
    }, [changes, view, oldCode, newCode, oldFilename, newFilename]);
    const filteredChanges = React6.useMemo(() => {
      if (!collapseUnchanged) return changes;
      const result = [];
      let i = 0;
      while (i < changes.length) {
        const change = changes[i];
        if (change.type !== "unchanged") {
          result.push(change);
          i++;
          continue;
        }
        const unchangedStart = i;
        while (i < changes.length && changes[i].type === "unchanged") {
          i++;
        }
        const unchangedCount = i - unchangedStart;
        if (unchangedCount <= contextLines * 2) {
          for (let j = unchangedStart; j < i; j++) {
            result.push(changes[j]);
          }
        } else {
          for (let j = unchangedStart; j < unchangedStart + contextLines; j++) {
            result.push(changes[j]);
          }
          result.push({
            type: "unchanged",
            lineNumber: -1,
            content: `... ${unchangedCount - contextLines * 2} unchanged lines ...`
          });
          for (let j = i - contextLines; j < i; j++) {
            result.push(changes[j]);
          }
        }
      }
      return result;
    }, [changes, collapseUnchanged, contextLines]);
    const stats = React6.useMemo(() => {
      const additions = changes.filter((c) => c.type === "add").length;
      const deletions = changes.filter((c) => c.type === "remove").length;
      return { additions, deletions };
    }, [changes]);
    const renderUnifiedView = /* @__PURE__ */ __name(() => {
      const oldLines = highlightedOldCode.split("\n");
      const newLines = highlightedNewCode.split("\n");
      return /* @__PURE__ */ jsx("div", { className: "font-mono", children: filteredChanges.map((change, index) => {
        if (change.lineNumber === -1) {
          return /* @__PURE__ */ jsx(
            "div",
            {
              className: "flex items-center justify-center py-2 text-muted-foreground bg-muted/30",
              children: /* @__PURE__ */ jsx("span", { className: "text-xs", children: change.content })
            },
            index
          );
        }
        let highlightedContent = change.content;
        if (change.type === "add" && change.newLineNumber) {
          highlightedContent = newLines[change.newLineNumber - 1] || change.content;
        } else if (change.type === "remove" && change.oldLineNumber) {
          highlightedContent = oldLines[change.oldLineNumber - 1] || change.content;
        } else if (change.type === "unchanged" && change.oldLineNumber) {
          highlightedContent = oldLines[change.oldLineNumber - 1] || change.content;
        }
        return /* @__PURE__ */ jsx(
          DiffLine,
          {
            change,
            showLineNumbers,
            isUnified: true,
            highlightedContent
          },
          index
        );
      }) });
    }, "renderUnifiedView");
    const renderSplitView = /* @__PURE__ */ __name(() => {
      const oldLines = highlightedOldCode.split("\n");
      const newLines = highlightedNewCode.split("\n");
      return /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-0", children: [
        /* @__PURE__ */ jsxs("div", { className: "border-r", children: [
          /* @__PURE__ */ jsx("div", { className: "border-b px-4 py-2 bg-red-500/10", children: /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-red-600 dark:text-red-400", children: oldFilename || filename || "Old" }) }),
          /* @__PURE__ */ jsx("div", { className: "font-mono", children: oldLines.map((line, index) => /* @__PURE__ */ jsx(
            DiffLine,
            {
              change: {
                type: "remove",
                lineNumber: index + 1,
                content: line,
                oldLineNumber: index + 1
              },
              showLineNumbers,
              highlightedContent: line
            },
            `old-${index}`
          )) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("div", { className: "border-b px-4 py-2 bg-green-500/10", children: /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-green-600 dark:text-green-400", children: newFilename || filename || "New" }) }),
          /* @__PURE__ */ jsx("div", { className: "font-mono", children: newLines.map((line, index) => /* @__PURE__ */ jsx(
            DiffLine,
            {
              change: {
                type: "add",
                lineNumber: index + 1,
                content: line,
                newLineNumber: index + 1
              },
              showLineNumbers,
              highlightedContent: line
            },
            `new-${index}`
          )) })
        ] })
      ] });
    }, "renderSplitView");
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(codeDiffVariants({ theme, size, className })),
        ...props,
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsx(GitCompare, { className: "h-4 w-4 text-muted-foreground" }),
                filename && /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: filename }),
                language && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: language })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
                /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1", children: [
                  /* @__PURE__ */ jsx(Plus, { className: "h-3 w-3 text-green-500" }),
                  stats.additions
                ] }),
                /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1", children: [
                  /* @__PURE__ */ jsx(Minus, { className: "h-3 w-3 text-red-500" }),
                  stats.deletions
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxs(
                ToggleGroup,
                {
                  type: "single",
                  value: view,
                  onValueChange: (value) => value && setView(value),
                  size: "sm",
                  children: [
                    /* @__PURE__ */ jsx(ToggleGroupItem, { value: "unified", "aria-label": "Unified view", children: /* @__PURE__ */ jsx(Square, { className: "h-3 w-3" }) }),
                    /* @__PURE__ */ jsx(ToggleGroupItem, { value: "split", "aria-label": "Split view", children: /* @__PURE__ */ jsx(SplitSquareHorizontal, { className: "h-3 w-3" }) })
                  ]
                }
              ),
              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 diff" })
                  ]
                }
              )
            ] })
          ] }),
          /* @__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, { className: "h-4 w-8" }),
            /* @__PURE__ */ jsx(Skeleton, { className: "h-4 flex-1" })
          ] }, i)) }) : view === "unified" ? renderUnifiedView() : renderSplitView() })
        ]
      }
    );
  }
);
CodeDiff2.displayName = "CodeDiff";
var defaultLanguages = [
  "javascript",
  "typescript",
  "python",
  "java",
  "csharp",
  "cpp",
  "c",
  "go",
  "rust",
  "ruby",
  "php",
  "swift",
  "kotlin",
  "dart",
  "html",
  "css",
  "scss",
  "json",
  "xml",
  "yaml",
  "sql",
  "markdown",
  "shell",
  "plaintext"
];
var languageDisplayNames = {
  javascript: "JavaScript",
  typescript: "TypeScript",
  python: "Python",
  java: "Java",
  csharp: "C#",
  cpp: "C++",
  c: "C",
  go: "Go",
  rust: "Rust",
  ruby: "Ruby",
  php: "PHP",
  swift: "Swift",
  kotlin: "Kotlin",
  dart: "Dart",
  html: "HTML",
  css: "CSS",
  scss: "SCSS",
  json: "JSON",
  xml: "XML",
  yaml: "YAML",
  sql: "SQL",
  markdown: "Markdown",
  shell: "Shell",
  plaintext: "Plain Text"
};
var CodeEditor = React6.forwardRef(
  ({
    value,
    defaultValue = "",
    language = "javascript",
    height = "400px",
    theme: themeProp = "auto",
    onChange,
    onMount,
    readOnly = false,
    lineNumbers = true,
    minimap = false,
    wordWrap = "on",
    fontSize = 14,
    className,
    showCopyButton = true,
    showLanguageSelector = true,
    availableLanguages = defaultLanguages
  }, ref) => {
    const { theme: systemTheme } = useTheme();
    const [selectedLanguage, setSelectedLanguage] = React6.useState(language);
    const [copied, setCopied] = React6.useState(false);
    const [editorValue, setEditorValue] = React6.useState(value || defaultValue);
    React6.useEffect(() => {
      if (value !== void 0) {
        setEditorValue(value);
      }
    }, [value]);
    const handleCopy = React6.useCallback(async () => {
      try {
        await navigator.clipboard.writeText(editorValue);
        setCopied(true);
        setTimeout(() => setCopied(false), 2e3);
      } catch (err) {
        console.error("Failed to copy:", err);
      }
    }, [editorValue]);
    const handleChange = React6.useCallback(
      (newValue, ev) => {
        setEditorValue(newValue || "");
        if (onChange) {
          onChange(newValue, ev);
        }
      },
      [onChange]
    );
    const resolveTheme = React6.useMemo(() => {
      if (themeProp === "auto") {
        return systemTheme === "dark" ? "vs-dark" : "light";
      }
      return themeProp === "dark" ? "vs-dark" : "light";
    }, [themeProp, systemTheme]);
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(
          "relative overflow-hidden rounded-md border bg-background",
          className
        ),
        children: [
          (showLanguageSelector || showCopyButton) && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b bg-muted/50 px-3 py-2", children: [
            showLanguageSelector && /* @__PURE__ */ jsxs(DropdownMenu, { children: [
              /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  className: "h-8 gap-1 px-2 text-xs font-mono",
                  children: [
                    languageDisplayNames[selectedLanguage] || selectedLanguage,
                    /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3" })
                  ]
                }
              ) }),
              /* @__PURE__ */ jsx(
                DropdownMenuContent,
                {
                  align: "start",
                  className: "max-h-80 overflow-auto",
                  children: availableLanguages.map((lang) => /* @__PURE__ */ jsx(
                    DropdownMenuItem,
                    {
                      onClick: () => setSelectedLanguage(lang),
                      className: "font-mono text-xs",
                      children: languageDisplayNames[lang] || lang
                    },
                    lang
                  ))
                }
              )
            ] }),
            showCopyButton && /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                className: "h-8 gap-1.5 px-2 text-xs",
                onClick: handleCopy,
                disabled: !editorValue,
                children: copied ? /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx(Check, { className: "h-3 w-3" }),
                  "Copied!"
                ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx(Copy, { className: "h-3 w-3" }),
                  "Copy"
                ] })
              }
            )
          ] }),
          /* @__PURE__ */ jsx(
            Editor,
            {
              height,
              defaultLanguage: language,
              language: selectedLanguage,
              value: editorValue,
              defaultValue,
              theme: resolveTheme,
              onChange: handleChange,
              onMount,
              options: {
                readOnly,
                lineNumbers: lineNumbers ? "on" : "off",
                minimap: {
                  enabled: minimap
                },
                wordWrap,
                fontSize,
                scrollBeyondLastLine: false,
                automaticLayout: true,
                tabSize: 2,
                insertSpaces: true,
                formatOnPaste: true,
                formatOnType: true,
                scrollbar: {
                  vertical: "auto",
                  horizontal: "auto",
                  verticalScrollbarSize: 10,
                  horizontalScrollbarSize: 10
                },
                padding: {
                  top: 16,
                  bottom: 16
                }
              }
            }
          )
        ]
      }
    );
  }
);
CodeEditor.displayName = "CodeEditor";
var codeExplorerVariants = cva(
  "relative flex flex-col overflow-hidden rounded-lg border bg-background",
  {
    variants: {
      size: {
        sm: "text-xs",
        default: "text-sm",
        lg: "text-base"
      }
    },
    defaultVariants: {
      size: "default"
    }
  }
);
var getFileIcon = /* @__PURE__ */ __name((fileName, isFolder = false) => {
  if (isFolder) return Folder;
  const ext = fileName.split(".").pop()?.toLowerCase();
  switch (ext) {
    case "js":
    case "jsx":
    case "ts":
    case "tsx":
    case "vue":
    case "svelte":
      return FileCode;
    case "json":
    case "xml":
    case "yaml":
    case "yml":
    case "toml":
    case "ini":
      return FileText;
    case "png":
    case "jpg":
    case "jpeg":
    case "gif":
    case "svg":
    case "webp":
    case "ico":
      return FileImage;
    default:
      return File;
  }
}, "getFileIcon");
var formatFileSize = /* @__PURE__ */ __name((bytes) => {
  if (!bytes) return "";
  const units = ["B", "KB", "MB", "GB"];
  let size = bytes;
  let unitIndex = 0;
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  return `${size.toFixed(1)} ${units[unitIndex]}`;
}, "formatFileSize");
var formatModifiedDate = /* @__PURE__ */ __name((date) => {
  if (!date) return "";
  const now = /* @__PURE__ */ new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1e3 * 60 * 60 * 24));
  if (days === 0) return "Today";
  if (days === 1) return "Yesterday";
  if (days < 7) return `${days} days ago`;
  if (days < 30) return `${Math.floor(days / 7)} weeks ago`;
  if (days < 365) return `${Math.floor(days / 30)} months ago`;
  return `${Math.floor(days / 365)} years ago`;
}, "formatModifiedDate");
var CodeExplorer = React6.forwardRef(
  ({
    className,
    size,
    files,
    onFileSelect,
    onFolderToggle,
    selectedFile,
    showSearch = true,
    showFileIcons = true,
    showFileSize = false,
    showModifiedDate = false,
    height = "400px",
    defaultExpanded = [],
    searchPlaceholder = "Search files...",
    emptyMessage = "No files found",
    ...props
  }, ref) => {
    const [searchTerm, setSearchTerm] = React6.useState("");
    const [expandedFolders, setExpandedFolders] = React6.useState(
      new Set(defaultExpanded)
    );
    const buildFileTree = React6.useCallback(
      (nodes) => {
        return nodes.map((node) => ({
          ...node,
          isExpanded: expandedFolders.has(node.id),
          children: node.children ? buildFileTree(node.children) : void 0
        }));
      },
      [expandedFolders]
    );
    const filterFiles = React6.useCallback(
      (nodes, term) => {
        if (!term) return nodes;
        const filtered = [];
        for (const node of nodes) {
          if (node.name.toLowerCase().includes(term.toLowerCase())) {
            filtered.push(node);
          } else if (node.type === "folder" && node.children) {
            const filteredChildren = filterFiles(node.children, term);
            if (filteredChildren.length > 0) {
              filtered.push({
                ...node,
                children: filteredChildren,
                isExpanded: true
                // Auto-expand folders with matches
              });
            }
          }
        }
        return filtered;
      },
      []
    );
    const processedFiles = React6.useMemo(() => {
      const withExpansion = buildFileTree(files);
      return searchTerm ? filterFiles(withExpansion, searchTerm) : withExpansion;
    }, [files, searchTerm, buildFileTree, filterFiles]);
    const toggleFolder = React6.useCallback(
      (folder) => {
        setExpandedFolders((prev) => {
          const newSet = new Set(prev);
          if (newSet.has(folder.id)) {
            newSet.delete(folder.id);
          } else {
            newSet.add(folder.id);
          }
          return newSet;
        });
        onFolderToggle?.(folder);
      },
      [onFolderToggle]
    );
    const renderFileNode = React6.useCallback(
      (node, depth = 0) => {
        const Icon = showFileIcons ? getFileIcon(node.name, node.type === "folder") : null;
        const FolderIcon = node.type === "folder" && node.isExpanded ? FolderOpen : Folder;
        const isSelected = selectedFile === node.id || selectedFile === node.path;
        return /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs(
            "div",
            {
              className: cn(
                "flex items-center gap-2 px-2 py-1 hover:bg-muted/50 cursor-pointer transition-colors",
                isSelected && "bg-muted",
                "rounded-sm"
              ),
              style: { paddingLeft: `${depth * 16 + 8}px` },
              onClick: () => {
                if (node.type === "folder") {
                  toggleFolder(node);
                } else {
                  onFileSelect?.(node);
                }
              },
              children: [
                node.type === "folder" && /* @__PURE__ */ jsx("div", { className: "w-4 h-4 flex items-center justify-center", children: node.isExpanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-3 w-3" }) }),
                showFileIcons && /* @__PURE__ */ jsx("div", { className: "w-4 h-4 flex items-center justify-center flex-shrink-0", children: node.type === "folder" ? /* @__PURE__ */ jsx(FolderIcon, { className: "h-4 w-4 text-blue-500" }) : Icon ? /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4 text-muted-foreground" }) : null }),
                /* @__PURE__ */ jsx("span", { className: "flex-1 truncate", children: node.name }),
                showFileSize && node.type === "file" && node.size && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground flex-shrink-0", children: formatFileSize(node.size) }),
                showModifiedDate && node.modified && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground flex-shrink-0", children: formatModifiedDate(node.modified) })
              ]
            }
          ),
          node.type === "folder" && node.isExpanded && node.children && /* @__PURE__ */ jsx("div", { children: node.children.map((child) => renderFileNode(child, depth + 1)) })
        ] }, node.id);
      },
      [
        showFileIcons,
        showFileSize,
        showModifiedDate,
        selectedFile,
        toggleFolder,
        onFileSelect
      ]
    );
    const clearSearch = /* @__PURE__ */ __name(() => {
      setSearchTerm("");
    }, "clearSearch");
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(codeExplorerVariants({ size }), className),
        style: { height },
        ...props,
        children: [
          showSearch && /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 border-b px-4 py-2", children: /* @__PURE__ */ jsxs("div", { className: "relative flex-1", children: [
            /* @__PURE__ */ jsx(Search, { className: "absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" }),
            /* @__PURE__ */ jsx(
              Input,
              {
                value: searchTerm,
                onChange: (e) => setSearchTerm(e.target.value),
                placeholder: searchPlaceholder,
                className: "pl-8 pr-8 h-8"
              }
            ),
            searchTerm && /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: clearSearch,
                className: "absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0",
                children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
              }
            )
          ] }) }),
          /* @__PURE__ */ jsx(ScrollArea, { className: "flex-1", children: /* @__PURE__ */ jsx("div", { className: "p-2", children: processedFiles.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-24 text-muted-foreground", children: searchTerm ? `No files match "${searchTerm}"` : emptyMessage }) : /* @__PURE__ */ jsx("div", { className: "space-y-0.5", children: processedFiles.map((node) => renderFileNode(node, 0)) }) }) }),
          /* @__PURE__ */ jsxs("div", { className: "border-t px-4 py-2 text-xs text-muted-foreground", children: [
            (() => {
              const countFiles = /* @__PURE__ */ __name((nodes) => {
                let files2 = 0;
                let folders = 0;
                for (const node of nodes) {
                  if (node.type === "file") {
                    files2++;
                  } else {
                    folders++;
                    if (node.children) {
                      const childCounts = countFiles(node.children);
                      files2 += childCounts.files;
                      folders += childCounts.folders;
                    }
                  }
                }
                return { files: files2, folders };
              }, "countFiles");
              const { files: fileCount, folders: folderCount } = countFiles(processedFiles);
              const parts = [];
              if (fileCount > 0)
                parts.push(`${fileCount} file${fileCount === 1 ? "" : "s"}`);
              if (folderCount > 0)
                parts.push(`${folderCount} folder${folderCount === 1 ? "" : "s"}`);
              return parts.join(", ") || "Empty";
            })(),
            searchTerm && /* @__PURE__ */ jsx("span", { children: " (filtered)" })
          ] })
        ]
      }
    );
  }
);
CodeExplorer.displayName = "CodeExplorer";
var codePreviewVariants = cva(
  "relative overflow-hidden rounded-lg border bg-background",
  {
    variants: {
      size: {
        sm: "text-xs",
        default: "text-sm",
        lg: "text-base"
      }
    },
    defaultVariants: {
      size: "default"
    }
  }
);
var runHTMLCode = /* @__PURE__ */ __name((files) => {
  const htmlFile = files.find((f) => f.type === "html");
  const cssFiles = files.filter((f) => f.type === "css");
  const jsFiles = files.filter((f) => f.type === "js");
  let html = htmlFile?.content || "<div>No HTML file provided</div>";
  if (cssFiles.length > 0) {
    const cssContent = cssFiles.map((f) => f.content).join("\n");
    html = `<style>${cssContent}</style>
${html}`;
  }
  if (jsFiles.length > 0) {
    const jsContent = jsFiles.map((f) => f.content).join("\n");
    html = `${html}
<script>${jsContent}</script>`;
  }
  return html;
}, "runHTMLCode");
var consoleScript = `
<script>
  const originalConsole = window.console;
  const logs = [];

  ['log', 'warn', 'error', 'info'].forEach(method => {
    window.console[method] = function(...args) {
      logs.push({
        type: method,
        content: args.map(arg =>
          typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
        ).join(' '),
        timestamp: Date.now()
      });

      // Also call original console method
      originalConsole[method].apply(originalConsole, arguments);

      // Send to parent
      window.parent.postMessage({
        type: 'console',
        data: logs[logs.length - 1]
      }, '*');
    };
  });

  window.addEventListener('error', (e) => {
    window.parent.postMessage({
      type: 'error',
      data: {
        type: 'error',
        content: e.message + ' at ' + e.filename + ':' + e.lineno,
        timestamp: Date.now()
      }
    }, '*');
  });
</script>
`;
var CodePreview = React6.forwardRef(
  ({
    className,
    size,
    files,
    defaultFile,
    showPreview = true,
    showConsole = true,
    autoRun = false,
    maxHeight = "600px",
    previewHeight = "300px",
    consoleHeight = "150px",
    allowFullscreen = true,
    customRunner,
    ...props
  }, ref) => {
    const [activeFile, setActiveFile] = React6.useState(
      defaultFile || files[0]?.filename || ""
    );
    const [previewContent, setPreviewContent] = React6.useState("");
    const [isRunning, setIsRunning] = React6.useState(false);
    const [results, setResults] = React6.useState([]);
    const [isPreviewVisible, setIsPreviewVisible] = React6.useState(showPreview);
    const [isConsoleVisible, setIsConsoleVisible] = React6.useState(showConsole);
    const [isFullscreen, setIsFullscreen] = React6.useState(false);
    const [copied, setCopied] = React6.useState({});
    const iframeRef = React6.useRef(null);
    files.find((f) => f.filename === activeFile) || files[0];
    React6.useEffect(() => {
      const handleMessage = /* @__PURE__ */ __name((event) => {
        if (event.data?.type === "console" || event.data?.type === "error") {
          setResults((prev) => [...prev, event.data.data]);
        }
      }, "handleMessage");
      window.addEventListener("message", handleMessage);
      return () => window.removeEventListener("message", handleMessage);
    }, []);
    const runCode = React6.useCallback(async () => {
      setIsRunning(true);
      setResults([]);
      try {
        let output;
        if (customRunner) {
          output = await customRunner(files);
        } else {
          output = runHTMLCode(files);
        }
        output = consoleScript + output;
        setPreviewContent(output);
        if (iframeRef.current) {
          const doc = iframeRef.current.contentDocument;
          if (doc) {
            doc.open();
            doc.write(output);
            doc.close();
          }
        }
      } catch (error) {
        setResults([
          {
            type: "error",
            content: error instanceof Error ? error.message : String(error),
            timestamp: Date.now()
          }
        ]);
      } finally {
        setIsRunning(false);
      }
    }, [files, customRunner]);
    React6.useEffect(() => {
      if (autoRun) {
        const timer = setTimeout(runCode, 1e3);
        return () => clearTimeout(timer);
      }
    }, [files, autoRun, runCode]);
    const copyFileContent = React6.useCallback(
      async (filename) => {
        const file = files.find((f) => f.filename === filename);
        if (!file) return;
        try {
          await navigator.clipboard.writeText(file.content);
          setCopied((prev) => ({ ...prev, [filename]: true }));
          setTimeout(() => {
            setCopied((prev) => ({ ...prev, [filename]: false }));
          }, 2e3);
        } catch (error) {
          console.error("Failed to copy code:", error);
        }
      },
      [files]
    );
    const clearConsole = /* @__PURE__ */ __name(() => {
      setResults([]);
    }, "clearConsole");
    const renderConsole = /* @__PURE__ */ __name(() => /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2 bg-muted/30", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Terminal, { className: "h-4 w-4" }),
          /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Console" }),
          results.length > 0 && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: results.length })
        ] }),
        /* @__PURE__ */ jsx(
          Button,
          {
            variant: "ghost",
            size: "sm",
            onClick: clearConsole,
            className: "h-8 w-8 p-0",
            children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" })
          }
        )
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-auto p-2 space-y-1 font-mono text-xs", children: results.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-muted-foreground italic", children: "No output" }) : results.map((result, index) => /* @__PURE__ */ jsxs(
        "div",
        {
          className: cn(
            "flex items-start gap-2 p-2 rounded",
            result.type === "error" && "bg-red-500/10 text-red-600 dark:text-red-400",
            result.type === "log" && "bg-blue-500/10 text-blue-600 dark:text-blue-400",
            result.type === "output" && "bg-green-500/10 text-green-600 dark:text-green-400"
          ),
          children: [
            /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: new Date(result.timestamp).toLocaleTimeString() }),
            /* @__PURE__ */ jsx("pre", { className: "flex-1 whitespace-pre-wrap break-words", children: result.content })
          ]
        },
        index
      )) })
    ] }), "renderConsole");
    const layout = isFullscreen ? "fixed inset-0 z-50 bg-background" : "";
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(codePreviewVariants({ size }), layout, className),
        style: { maxHeight: isFullscreen ? "100vh" : maxHeight },
        ...props,
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2", children: [
            /* @__PURE__ */ jsx(
              Tabs,
              {
                value: activeFile,
                onValueChange: setActiveFile,
                className: "flex-1",
                children: /* @__PURE__ */ jsx(TabsList, { className: "h-auto p-0 bg-transparent", children: files.map((file) => /* @__PURE__ */ jsxs(
                  TabsTrigger,
                  {
                    value: file.filename,
                    className: "relative flex items-center gap-2 data-[state=active]:bg-muted",
                    children: [
                      /* @__PURE__ */ jsx("span", { children: file.filename }),
                      /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: file.language }),
                      /* @__PURE__ */ jsx(
                        Button,
                        {
                          variant: "ghost",
                          size: "sm",
                          onClick: (e) => {
                            e.stopPropagation();
                            copyFileContent(file.filename);
                          },
                          className: "h-6 w-6 p-0 opacity-0 group-hover:opacity-100",
                          children: copied[file.filename] ? /* @__PURE__ */ jsx(Check, { className: "h-3 w-3 text-green-500" }) : /* @__PURE__ */ jsx(Copy, { className: "h-3 w-3" })
                        }
                      )
                    ]
                  },
                  file.filename
                )) })
              }
            ),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(
                Toggle,
                {
                  pressed: isPreviewVisible,
                  onPressedChange: setIsPreviewVisible,
                  "aria-label": "Toggle preview",
                  size: "sm",
                  children: isPreviewVisible ? /* @__PURE__ */ jsx(Eye, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(EyeOff, { className: "h-4 w-4" })
                }
              ),
              /* @__PURE__ */ jsx(
                Toggle,
                {
                  pressed: isConsoleVisible,
                  onPressedChange: setIsConsoleVisible,
                  "aria-label": "Toggle console",
                  size: "sm",
                  children: /* @__PURE__ */ jsx(Terminal, { className: "h-4 w-4" })
                }
              ),
              /* @__PURE__ */ jsxs(
                Button,
                {
                  variant: "outline",
                  size: "sm",
                  onClick: runCode,
                  disabled: isRunning,
                  className: "gap-2",
                  children: [
                    isRunning ? /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(Play, { className: "h-4 w-4" }),
                    "Run"
                  ]
                }
              ),
              allowFullscreen && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: () => setIsFullscreen(!isFullscreen),
                  className: "h-8 w-8 p-0",
                  children: isFullscreen ? /* @__PURE__ */ jsx(Square, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full", children: [
            /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-0", children: /* @__PURE__ */ jsx(Tabs, { value: activeFile, onValueChange: setActiveFile, children: files.map((file) => /* @__PURE__ */ jsx(
              TabsContent,
              {
                value: file.filename,
                className: "m-0 h-full",
                children: /* @__PURE__ */ jsx(
                  CodeSnippet,
                  {
                    code: file.content,
                    language: file.language,
                    showLineNumbers: true,
                    showCopyButton: false,
                    showHeader: false,
                    maxHeight: "100%",
                    className: "border-0 rounded-none"
                  }
                )
              },
              file.filename
            )) }) }),
            (isPreviewVisible || isConsoleVisible) && /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(Separator, {}),
              /* @__PURE__ */ jsxs("div", { className: "flex flex-col lg:flex-row min-h-0", children: [
                isPreviewVisible && /* @__PURE__ */ jsxs(
                  "div",
                  {
                    className: "flex-1 min-h-0 border-r last:border-r-0",
                    style: { height: previewHeight },
                    children: [
                      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 border-b px-4 py-2 bg-muted/30", children: [
                        /* @__PURE__ */ jsx(Eye, { className: "h-4 w-4" }),
                        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Preview" }),
                        results.filter((r) => r.type === "error").length > 0 && /* @__PURE__ */ jsx(AlertTriangle, { className: "h-4 w-4 text-red-500" })
                      ] }),
                      /* @__PURE__ */ jsx(
                        "iframe",
                        {
                          ref: iframeRef,
                          className: "w-full h-full bg-white",
                          sandbox: "allow-scripts allow-same-origin",
                          srcDoc: previewContent
                        }
                      )
                    ]
                  }
                ),
                isConsoleVisible && /* @__PURE__ */ jsx(
                  "div",
                  {
                    className: "flex-1 min-h-0",
                    style: { height: consoleHeight },
                    children: renderConsole()
                  }
                )
              ] })
            ] })
          ] }),
          isFullscreen && /* @__PURE__ */ jsx(
            "div",
            {
              className: "absolute inset-0 bg-black/50",
              onClick: () => setIsFullscreen(false)
            }
          )
        ]
      }
    );
  }
);
CodePreview.displayName = "CodePreview";
var codeSnippetVariants = cva("relative group", {
  variants: {
    variant: {
      default: "rounded-lg border bg-muted/50",
      inline: "inline-block rounded-md bg-muted px-2 py-1",
      minimal: "bg-transparent"
    },
    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",
      terminal: "bg-black border-green-500/30 text-green-400",
      retro: "bg-amber-50 border-amber-200 text-amber-900"
    },
    size: {
      xs: "text-xs",
      sm: "text-sm",
      default: "text-sm",
      lg: "text-base"
    }
  },
  defaultVariants: {
    variant: "default",
    theme: "dark",
    size: "default"
  }
});
var CodeSnippet3 = React6.forwardRef(
  ({
    className,
    variant,
    theme,
    size,
    code,
    language = "text",
    filename,
    showLineNumbers = false,
    highlightLines = [],
    showCopyButton = true,
    showLanguageBadge = true,
    showHeader = true,
    maxHeight,
    expandable = false,
    collapsedHeight = "200px",
    wrapLines = false,
    startLineNumber = 1,
    ...props
  }, ref) => {
    const [highlightedCode, setHighlightedCode] = React6.useState("");
    const [copied, setCopied] = React6.useState(false);
    const [isLoading, setIsLoading] = React6.useState(true);
    const [isExpanded, setIsExpanded] = React6.useState(!expandable);
    const themeMap = {
      dark: "github-dark",
      light: "github-light",
      github: "github-light",
      "github-dark": "github-dark",
      terminal: "github-dark",
      retro: "github-light"
    };
    React6.useEffect(() => {
      const highlightCode = /* @__PURE__ */ __name(async () => {
        setIsLoading(true);
        try {
          const supportedLang = Object.keys(bundledLanguages).includes(language);
          const highlighted = await codeToHtml(code, {
            lang: supportedLang ? language : "text",
            theme: themeMap[theme || "dark"]
          });
          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);
          const escaped = code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
          setHighlightedCode(escaped);
        } finally {
          setIsLoading(false);
        }
      }, "highlightCode");
      highlightCode();
    }, [code, language, theme]);
    const copyToClipboard = React6.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").filter((line, index, array) => {
      return line.trim() !== "" || index < array.length - 1;
    });
    const renderInline = /* @__PURE__ */ __name(() => /* @__PURE__ */ jsx(
      "code",
      {
        className: cn(
          codeSnippetVariants({ variant, theme, size }),
          "font-mono",
          className
        ),
        dangerouslySetInnerHTML: { __html: highlightedCode }
      }
    ), "renderInline");
    const renderBlock = /* @__PURE__ */ __name(() => /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(
          codeSnippetVariants({ variant, theme, size }),
          "overflow-hidden",
          className
        ),
        ...props,
        children: [
          showHeader && (filename || language || showCopyButton || expandable) && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2 bg-muted/30", 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 })
              ] }),
              showLanguageBadge && language && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: language })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
              expandable && /* @__PURE__ */ jsxs(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: () => setIsExpanded(!isExpanded),
                  className: "h-8 w-8 p-0",
                  children: [
                    isExpanded ? /* @__PURE__ */ jsx(Minimize2, { className: "h-3.5 w-3.5" }) : /* @__PURE__ */ jsx(Maximize2, { className: "h-3.5 w-3.5" }),
                    /* @__PURE__ */ jsx("span", { className: "sr-only", children: isExpanded ? "Collapse" : "Expand" })
                  ]
                }
              ),
              showCopyButton && /* @__PURE__ */ jsxs(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: copyToClipboard,
                  className: "h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity",
                  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: cn("overflow-auto", !wrapLines && "overflow-x-auto"),
              style: {
                maxHeight: isExpanded ? maxHeight : collapsedHeight
              },
              children: isLoading ? /* @__PURE__ */ jsx("div", { className: "p-4 space-y-2", children: Array.from({ length: Math.min(lines.length || 5, 10) }).map(
                (_, i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
                  showLineNumbers && /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-8" }),
                  /* @__PURE__ */ jsx(Skeleton, { className: "h-4 flex-1" })
                ] }, i)
              ) }) : /* @__PURE__ */ jsx("div", { className: "font-mono", children: lines.map((line, index) => {
                const lineNumber = index + startLineNumber;
                const isHighlighted = highlightLines.includes(lineNumber);
                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",
                      !wrapLines && "whitespace-nowrap"
                    ),
                    children: [
                      showLineNumbers && /* @__PURE__ */ jsx("span", { className: "mr-4 inline-block w-8 select-none text-right text-xs text-muted-foreground", children: lineNumber }),
                      /* @__PURE__ */ jsx(
                        "div",
                        {
                          className: cn(
                            "flex-1",
                            wrapLines ? "whitespace-pre-wrap break-words" : "overflow-x-auto"
                          ),
                          dangerouslySetInnerHTML: { __html: line }
                        }
                      )
                    ]
                  },
                  index
                );
              }) })
            }
          ),
          expandable && !isExpanded && /* @__PURE__ */ jsx("div", { className: "absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-background to-transparent pointer-events-none" }),
          variant === "minimal" && showCopyButton && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "ghost",
              size: "sm",
              onClick: copyToClipboard,
              className: "absolute top-2 right-2 h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity",
              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" })
            }
          )
        ]
      }
    ), "renderBlock");
    if (variant === "inline") {
      return renderInline();
    }
    return renderBlock();
  }
);
CodeSnippet3.displayName = "CodeSnippet";
var InlineCode = React6.forwardRef(({ children, language, className, ...props }, ref) => {
  return /* @__PURE__ */ jsx(
    CodeSnippet3,
    {
      ref,
      code: children,
      language,
      variant: "inline",
      showCopyButton: false,
      showLanguageBadge: false,
      showHeader: false,
      className,
      ...props
    }
  );
});
InlineCode.displayName = "InlineCode";
var CodeTabs = React6.forwardRef(
  ({ className, tabs = [], defaultTab = 0, ...props }, ref) => {
    const [activeTab, setActiveTab] = React6.useState(defaultTab);
    if (tabs.length === 0) {
      return /* @__PURE__ */ jsx(
        "div",
        {
          ref,
          className: cn(
            "rounded-lg border bg-card p-6 text-card-foreground shadow-sm",
            className
          ),
          ...props,
          children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "No code tabs available. Add tabs to display code snippets." })
        }
      );
    }
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(
          "rounded-lg border bg-card text-card-foreground shadow-sm",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ jsx("div", { className: "border-b", children: /* @__PURE__ */ jsx("div", { className: "flex gap-1 p-2", children: tabs.map((tab, index) => /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => setActiveTab(index),
              className: cn(
                "rounded-md px-4 py-2 text-sm font-medium transition-colors",
                activeTab === index ? "bg-primary text-primary-foreground" : "hover:bg-muted"
              ),
              children: tab.label
            },
            index
          )) }) }),
          /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx("pre", { className: "overflow-x-auto rounded-md bg-muted p-4", children: /* @__PURE__ */ jsx("code", { className: "text-sm", children: tabs[activeTab]?.code }) }) })
        ]
      }
    );
  }
);
CodeTabs.displayName = "CodeTabs";
var codeTerminalVariants = cva(
  "relative flex flex-col overflow-hidden rounded-lg border",
  {
    variants: {
      theme: {
        dark: "bg-black border-gray-700 text-green-400",
        light: "bg-white border-gray-300 text-gray-900",
        matrix: "bg-black border-green-500 text-green-400",
        hacker: "bg-gray-900 border-yellow-500 text-yellow-400",
        retro: "bg-amber-900 border-amber-600 text-amber-100",
        modern: "bg-slate-900 border-slate-700 text-slate-100"
      },
      size: {
        sm: "text-xs",
        default: "text-sm",
        lg: "text-base"
      }
    },
    defaultVariants: {
      theme: "dark",
      size: "default"
    }
  }
);
var ansiColors = {
  black: "text-black",
  red: "text-red-500",
  green: "text-green-500",
  yellow: "text-yellow-500",
  blue: "text-blue-500",
  magenta: "text-magenta-500",
  cyan: "text-cyan-500",
  white: "text-white",
  gray: "text-gray-500",
  brightRed: "text-red-400",
  brightGreen: "text-green-400",
  brightYellow: "text-yellow-400",
  brightBlue: "text-blue-400",
  brightMagenta: "text-magenta-400",
  brightCyan: "text-cyan-400",
  brightWhite: "text-gray-100"
};
var parseAnsiContent = /* @__PURE__ */ __name((content) => {
  const ansiRegex = /\x1b\[([0-9;]*)m/g;
  const parts = [];
  let lastIndex = 0;
  let currentClasses = [];
  let match;
  while ((match = ansiRegex.exec(content)) !== null) {
    if (match.index > lastIndex) {
      parts.push({
        text: content.slice(lastIndex, match.index),
        classes: [...currentClasses]
      });
    }
    const codes = match[1].split(";").map((code) => parseInt(code) || 0);
    codes.forEach((code) => {
      switch (code) {
        case 0:
          currentClasses = [];
          break;
        // reset
        case 30:
          currentClasses.push(ansiColors.black);
          break;
        case 31:
          currentClasses.push(ansiColors.red);
          break;
        case 32:
          currentClasses.push(ansiColors.green);
          break;
        case 33:
          currentClasses.push(ansiColors.yellow);
          break;
        case 34:
          currentClasses.push(ansiColors.blue);
          break;
        case 35:
          currentClasses.push(ansiColors.magenta);
          break;
        case 36:
          currentClasses.push(ansiColors.cyan);
          break;
        case 37:
          currentClasses.push(ansiColors.white);
          break;
        case 90:
          currentClasses.push(ansiColors.gray);
          break;
        case 91:
          currentClasses.push(ansiColors.brightRed);
          break;
        case 92:
          currentClasses.push(ansiColors.brightGreen);
          break;
        case 93:
          currentClasses.push(ansiColors.brightYellow);
          break;
        case 94:
          currentClasses.push(ansiColors.brightBlue);
          break;
        case 95:
          currentClasses.push(ansiColors.brightMagenta);
          break;
        case 96:
          currentClasses.push(ansiColors.brightCyan);
          break;
        case 97:
          currentClasses.push(ansiColors.brightWhite);
          break;
      }
    });
    lastIndex = match.index + match[0].length;
  }
  if (lastIndex < content.length) {
    parts.push({
      text: content.slice(lastIndex),
      classes: [...currentClasses]
    });
  }
  return parts.map((part, index) => /* @__PURE__ */ jsx("span", { className: cn(part.classes), children: part.text }, index));
}, "parseAnsiContent");
var CodeTerminal = React6.forwardRef(
  ({
    className,
    theme,
    size,
    title = "Terminal",
    prompt = "$",
    maxLines = 1e3,
    showLineNumbers = false,
    allowInput = true,
    allowClear = true,
    allowCopy = true,
    allowDownload = false,
    allowFullscreen = true,
    height = "400px",
    autoScroll = true,
    history = [],
    onCommand,
    onClear,
    initialLines = [],
    ...props
  }, ref) => {
    const [lines, setLines] = React6.useState(initialLines);
    const [input, setInput] = React6.useState("");
    const [historyIndex, setHistoryIndex] = React6.useState(-1);
    const [isFullscreen, setIsFullscreen] = React6.useState(false);
    const [commandHistory, setCommandHistory] = React6.useState(history);
    const scrollAreaRef = React6.useRef(null);
    const inputRef = React6.useRef(null);
    React6.useEffect(() => {
      if (autoScroll && scrollAreaRef.current) {
        scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
      }
    }, [lines, autoScroll]);
    const addLine = React6.useCallback(
      (line) => {
        const newLine = {
          ...line,
          id: `line-${Date.now()}-${Math.random()}`,
          timestamp: Date.now()
        };
        setLines((prev) => {
          const updated = [...prev, newLine];
          return updated.length > maxLines ? updated.slice(-maxLines) : updated;
        });
      },
      [maxLines]
    );
    const handleCommand = React6.useCallback(
      async (command) => {
        if (!command.trim()) return;
        setCommandHistory((prev) => [...prev, command]);
        setHistoryIndex(-1);
        addLine({
          type: "input",
          content: `${prompt} ${command}`,
          command
        });
        if (command === "clear") {
          if (onClear) {
            onClear();
          } else {
            setLines([]);
          }
          return;
        }
        if (command === "history") {
          commandHistory.forEach((cmd, index) => {
            addLine({
              type: "output",
              content: `${index + 1}  ${cmd}`
            });
          });
          return;
        }
        if (command.startsWith("echo ")) {
          addLine({
            type: "output",
            content: command.slice(5)
          });
          return;
        }
        if (onCommand) {
          try {
            await onCommand(command);
          } catch (error) {
            addLine({
              type: "error",
              content: error instanceof Error ? error.message : String(error),
              exitCode: 1
            });
          }
        } else {
          addLine({
            type: "error",
            content: `Command not found: ${command}`,
            exitCode: 127
          });
        }
      },
      [prompt, addLine, onCommand, onClear, commandHistory]
    );
    const handleInputSubmit = /* @__PURE__ */ __name((e) => {
      e.preventDefault();
      if (input.trim()) {
        handleCommand(input);
        setInput("");
      }
    }, "handleInputSubmit");
    const handleKeyDown = /* @__PURE__ */ __name((e) => {
      if (e.key === "ArrowUp") {
        e.preventDefault();
        if (historyIndex < commandHistory.length - 1) {
          const newIndex = historyIndex + 1;
          setHistoryIndex(newIndex);
          setInput(commandHistory[commandHistory.length - 1 - newIndex] || "");
        }
      } else if (e.key === "ArrowDown") {
        e.preventDefault();
        if (historyIndex > 0) {
          const newIndex = historyIndex - 1;
          setHistoryIndex(newIndex);
          setInput(commandHistory[commandHistory.length - 1 - newIndex] || "");
        } else if (historyIndex === 0) {
          setHistoryIndex(-1);
          setInput("");
        }
      }
    }, "handleKeyDown");
    const copyContent = React6.useCallback(async () => {
      const content = lines.map((line) => line.content).join("\n");
      try {
        await navigator.clipboard.writeText(content);
      } catch (error) {
        console.error("Failed to copy terminal content:", error);
      }
    }, [lines]);
    const downloadContent = React6.useCallback(() => {
      const content = lines.map(
        (line) => `[${new Date(line.timestamp).toISOString()}] ${line.content}`
      ).join("\n");
      const blob = new Blob([content], { type: "text/plain" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `terminal-${Date.now()}.txt`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }, [lines]);
    const clearTerminal = /* @__PURE__ */ __name(() => {
      if (onClear) {
        onClear();
      } else {
        setLines([]);
      }
    }, "clearTerminal");
    const handleTerminalClick = /* @__PURE__ */ __name(() => {
      if (allowInput && inputRef.current) {
        inputRef.current.focus();
      }
    }, "handleTerminalClick");
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(
          codeTerminalVariants({ theme, size }),
          isFullscreen && "fixed inset-0 z-50",
          className
        ),
        style: { height: isFullscreen ? "100vh" : height },
        onClick: handleTerminalClick,
        ...props,
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2 bg-muted/30", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
                /* @__PURE__ */ jsx("div", { className: "w-3 h-3 rounded-full bg-red-500" }),
                /* @__PURE__ */ jsx("div", { className: "w-3 h-3 rounded-full bg-yellow-500" }),
                /* @__PURE__ */ jsx("div", { className: "w-3 h-3 rounded-full bg-green-500" })
              ] }),
              /* @__PURE__ */ jsx(Terminal, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: title }),
              lines.length > 0 && /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
                lines.length,
                " lines"
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
              allowClear && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: clearTerminal,
                  className: "h-8 w-8 p-0",
                  children: /* @__PURE__ */ jsx(RefreshCw, { className: "h-3.5 w-3.5" })
                }
              ),
              allowCopy && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: copyContent,
                  className: "h-8 w-8 p-0",
                  children: /* @__PURE__ */ jsx(Copy, { className: "h-3.5 w-3.5" })
                }
              ),
              allowDownload && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: downloadContent,
                  className: "h-8 w-8 p-0",
                  children: /* @__PURE__ */ jsx(Download, { className: "h-3.5 w-3.5" })
                }
              ),
              allowFullscreen && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: () => setIsFullscreen(!isFullscreen),
                  className: "h-8 w-8 p-0",
                  children: isFullscreen ? /* @__PURE__ */ jsx(Minimize2, { className: "h-3.5 w-3.5" }) : /* @__PURE__ */ jsx(Maximize2, { className: "h-3.5 w-3.5" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1 flex flex-col min-h-0", children: [
            /* @__PURE__ */ jsx(ScrollArea, { ref: scrollAreaRef, className: "flex-1 p-4", children: /* @__PURE__ */ jsx("div", { className: "space-y-1 font-mono", children: lines.map((line, index) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2", children: [
              showLineNumbers && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground w-12 text-right flex-shrink-0", children: index + 1 }),
              /* @__PURE__ */ jsx(
                "div",
                {
                  className: cn(
                    "flex-1 whitespace-pre-wrap break-words",
                    line.type === "input" && "text-inherit",
                    line.type === "output" && "text-muted-foreground",
                    line.type === "error" && "text-red-400",
                    line.type === "system" && "text-blue-400"
                  ),
                  children: typeof line.content === "string" && line.content.includes("\x1B[") ? parseAnsiContent(line.content) : line.content
                }
              )
            ] }, line.id)) }) }),
            allowInput && /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(Separator, {}),
              /* @__PURE__ */ jsx("form", { onSubmit: handleInputSubmit, className: "p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 font-mono", children: [
                /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4 flex-shrink-0" }),
                /* @__PURE__ */ jsx("span", { className: "flex-shrink-0", children: prompt }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    ref: inputRef,
                    value: input,
                    onChange: (e) => setInput(e.target.value),
                    onKeyDown: handleKeyDown,
                    className: "flex-1 border-0 bg-transparent p-0 focus-visible:ring-0 font-mono",
                    placeholder: "Enter command...",
                    autoComplete: "off",
                    autoFocus: true
                  }
                )
              ] }) })
            ] })
          ] })
        ]
      }
    );
  }
);
CodeTerminal.displayName = "CodeTerminal";

export { CodeBlock, CodeCompare, CodeDiff2 as CodeDiff, CodeEditor, CodeExplorer, CodePreview, CodeSnippet3 as CodeSnippet, CodeTabs, CodeTerminal, InlineCode, codeBlockVariants, codeCompareVariants, codeDiffVariants, codeExplorerVariants, codePreviewVariants, codeSnippetVariants, codeTerminalVariants };
