"use client";
'use strict';

var React = require('react');
var classVarianceAuthority = require('class-variance-authority');
var lucideReact = require('lucide-react');
var utils = require('@hanzo/ui/lib/utils');
var badge = require('@hanzo/ui/badge');
var button = require('@hanzo/ui/button');
var diff = require('@hanzo/ui/code/diff');
var snippet = require('@hanzo/ui/code/snippet');
var dropdownMenu = require('@hanzo/ui/dropdown-menu');
var scrollArea = require('@hanzo/ui/scroll-area');
var tabs = require('@hanzo/ui/tabs');
var jsxRuntime = require('react/jsx-runtime');

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var React__namespace = /*#__PURE__*/_interopNamespace(React);

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var codeCompareVariants = classVarianceAuthority.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 = React__namespace.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] = React__namespace.useState(defaultView);
    const [selectedFiles, setSelectedFiles] = React__namespace.useState(() => {
      if (files.length >= 2) {
        return [files[0].id, files[1].id];
      }
      return files.length > 0 ? [files[0].id] : [];
    });
    const [mergeState, setMergeState] = React__namespace.useState({
      resolved: {},
      conflicts: conflictMarkers
    });
    const [copied, setCopied] = React__namespace.useState(false);
    const scrollRefs = React__namespace.useRef({});
    const handleScroll = React__namespace.useCallback(
      (sourceId, scrollTop) => {
        if (!syncScroll) return;
        Object.entries(scrollRefs.current).forEach(([id, ref2]) => {
          if (id !== sourceId && ref2) {
            ref2.scrollTop = scrollTop;
          }
        });
      },
      [syncScroll]
    );
    const copyComparison = React__namespace.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 = React__namespace.useCallback(
      (conflictIndex, resolution) => {
        setMergeState((prev) => ({
          ...prev,
          resolved: {
            ...prev.resolved,
            [conflictIndex]: resolution
          }
        }));
        onMergeConflict?.(resolution);
      },
      [onMergeConflict]
    );
    const getFileStats = React__namespace.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__ */ jsxRuntime.jsx("div", { className: "flex items-center gap-2 flex-wrap", children: files.map((file, index) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsxRuntime.jsxs(
        button.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__ */ jsxRuntime.jsx(badge.Badge, { variant: "secondary", className: "text-xs", children: file.version })
          ]
        }
      ),
      index < files.length - 1 && view !== "three-way" && /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.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__ */ jsxRuntime.jsxs("div", { className: "flex flex-col h-full", children: [
        /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-between border-b px-4 py-2 bg-muted/30", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-4", children: [
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: "Comparison" }),
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 text-xs", children: [
            /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-green-600", children: [
              "+",
              stats.added
            ] }),
            /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-red-600", children: [
              "-",
              stats.removed
            ] }),
            /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-yellow-600", children: [
              "~",
              stats.modified
            ] })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex-1 min-h-0", children: /* @__PURE__ */ jsxRuntime.jsx(
          diff.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__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-center h-32 text-muted-foreground", children: "Select two files to compare" });
      }
      return /* @__PURE__ */ jsxRuntime.jsx(
        diff.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__ */ jsxRuntime.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__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-3 gap-0 h-full", children: [
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "border-r", children: [
          /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-b px-4 py-2 bg-muted/30", children: /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm font-medium", children: [
            "Base (",
            base.filename,
            ")"
          ] }) }),
          /* @__PURE__ */ jsxRuntime.jsx(
            scrollArea.ScrollArea,
            {
              className: "h-full",
              ref: (ref2) => {
                scrollRefs.current["base"] = ref2;
              },
              onScrollCapture: (e) => {
                const target = e.target;
                handleScroll("base", target.scrollTop);
              },
              children: /* @__PURE__ */ jsxRuntime.jsx(
                snippet.CodeSnippet,
                {
                  code: base.content,
                  language: base.language,
                  showLineNumbers,
                  showCopyButton: false,
                  showHeader: false,
                  className: "border-0 rounded-none"
                }
              )
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "border-r", children: [
          /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-b px-4 py-2 bg-blue-500/10", children: /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm font-medium text-blue-600 dark:text-blue-400", children: [
            "Current (",
            current.filename,
            ")"
          ] }) }),
          /* @__PURE__ */ jsxRuntime.jsx(
            scrollArea.ScrollArea,
            {
              className: "h-full",
              ref: (ref2) => {
                scrollRefs.current["current"] = ref2;
              },
              onScrollCapture: (e) => {
                const target = e.target;
                handleScroll("current", target.scrollTop);
              },
              children: /* @__PURE__ */ jsxRuntime.jsx(
                snippet.CodeSnippet,
                {
                  code: current.content,
                  language: current.language,
                  showLineNumbers,
                  showCopyButton: false,
                  showHeader: false,
                  className: "border-0 rounded-none"
                }
              )
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-b px-4 py-2 bg-green-500/10", children: /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm font-medium text-green-600 dark:text-green-400", children: [
            "Incoming (",
            incoming.filename,
            ")"
          ] }) }),
          /* @__PURE__ */ jsxRuntime.jsx(
            scrollArea.ScrollArea,
            {
              className: "h-full",
              ref: (ref2) => {
                scrollRefs.current["incoming"] = ref2;
              },
              onScrollCapture: (e) => {
                const target = e.target;
                handleScroll("incoming", target.scrollTop);
              },
              children: /* @__PURE__ */ jsxRuntime.jsx(
                snippet.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__ */ jsxRuntime.jsx("div", { className: "border-t bg-muted/30", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "px-4 py-2", children: [
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: "Merge Conflicts" }),
          /* @__PURE__ */ jsxRuntime.jsx(badge.Badge, { variant: "destructive", className: "text-xs", children: mergeState.conflicts.length })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-2 space-y-2", children: mergeState.conflicts.map((conflict, index) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
          /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
            "Lines ",
            conflict.startLine,
            "-",
            conflict.endLine
          ] }),
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1", children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              button.Button,
              {
                variant: "outline",
                size: "sm",
                onClick: () => resolveConflict(index, "current"),
                className: "h-6 text-xs",
                children: "Keep Current"
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(
              button.Button,
              {
                variant: "outline",
                size: "sm",
                onClick: () => resolveConflict(index, "incoming"),
                className: "h-6 text-xs",
                children: "Accept Incoming"
              }
            )
          ] })
        ] }, index)) })
      ] }) });
    }, "renderMergeConflicts");
    return /* @__PURE__ */ jsxRuntime.jsxs(
      "div",
      {
        ref,
        className: utils.cn(codeCompareVariants({ layout, size }), className),
        style: { height },
        ...props,
        children: [
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between border-b px-4 py-2", children: [
            /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center gap-4", children: renderFileSelector() }),
            /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntime.jsx(tabs.Tabs, { value: view, onValueChange: (value) => setView(value), children: /* @__PURE__ */ jsxRuntime.jsxs(tabs.TabsList, { className: "grid w-full grid-cols-3", children: [
                /* @__PURE__ */ jsxRuntime.jsx(tabs.TabsTrigger, { value: "side-by-side", className: "text-xs", children: "Side by Side" }),
                /* @__PURE__ */ jsxRuntime.jsx(tabs.TabsTrigger, { value: "unified", className: "text-xs", children: "Unified" }),
                /* @__PURE__ */ jsxRuntime.jsx(tabs.TabsTrigger, { value: "three-way", className: "text-xs", children: "Three-way" })
              ] }) }),
              showCopyButton && /* @__PURE__ */ jsxRuntime.jsx(
                button.Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: copyComparison,
                  className: "h-8 w-8 p-0",
                  children: copied ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-3.5 w-3.5 text-green-500" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Copy, { className: "h-3.5 w-3.5" })
                }
              ),
              /* @__PURE__ */ jsxRuntime.jsxs(dropdownMenu.DropdownMenu, { children: [
                /* @__PURE__ */ jsxRuntime.jsx(dropdownMenu.DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsx(button.Button, { variant: "ghost", size: "sm", className: "h-8 w-8 p-0", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.MoreHorizontal, { className: "h-3.5 w-3.5" }) }) }),
                /* @__PURE__ */ jsxRuntime.jsxs(dropdownMenu.DropdownMenuContent, { align: "end", children: [
                  /* @__PURE__ */ jsxRuntime.jsxs(
                    dropdownMenu.DropdownMenuItem,
                    {
                      onClick: () => setSelectedFiles([]),
                      className: "gap-2",
                      children: [
                        /* @__PURE__ */ jsxRuntime.jsx(lucideReact.RotateCcw, { className: "h-4 w-4" }),
                        "Reset Selection"
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsxRuntime.jsxs(dropdownMenu.DropdownMenuItem, { className: "gap-2", children: [
                    /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Settings, { className: "h-4 w-4" }),
                    "Settings"
                  ] })
                ] })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntime.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";

exports.CodeCompare = CodeCompare;
exports.codeCompareVariants = codeCompareVariants;
