"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 button = require('@hanzo/ui/button');
var input = require('@hanzo/ui/input');
var scrollArea = require('@hanzo/ui/scroll-area');
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 codeExplorerVariants = classVarianceAuthority.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 lucideReact.Folder;
  const ext = fileName.split(".").pop()?.toLowerCase();
  switch (ext) {
    case "js":
    case "jsx":
    case "ts":
    case "tsx":
    case "vue":
    case "svelte":
      return lucideReact.FileCode;
    case "json":
    case "xml":
    case "yaml":
    case "yml":
    case "toml":
    case "ini":
      return lucideReact.FileText;
    case "png":
    case "jpg":
    case "jpeg":
    case "gif":
    case "svg":
    case "webp":
    case "ico":
      return lucideReact.FileImage;
    default:
      return lucideReact.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 = React__namespace.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] = React__namespace.useState("");
    const [expandedFolders, setExpandedFolders] = React__namespace.useState(
      new Set(defaultExpanded)
    );
    const buildFileTree = React__namespace.useCallback(
      (nodes) => {
        return nodes.map((node) => ({
          ...node,
          isExpanded: expandedFolders.has(node.id),
          children: node.children ? buildFileTree(node.children) : void 0
        }));
      },
      [expandedFolders]
    );
    const filterFiles = React__namespace.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 = React__namespace.useMemo(() => {
      const withExpansion = buildFileTree(files);
      return searchTerm ? filterFiles(withExpansion, searchTerm) : withExpansion;
    }, [files, searchTerm, buildFileTree, filterFiles]);
    const toggleFolder = React__namespace.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 = React__namespace.useCallback(
      (node, depth = 0) => {
        const Icon = showFileIcons ? getFileIcon(node.name, node.type === "folder") : null;
        const FolderIcon = node.type === "folder" && node.isExpanded ? lucideReact.FolderOpen : lucideReact.Folder;
        const isSelected = selectedFile === node.id || selectedFile === node.path;
        return /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntime.jsxs(
            "div",
            {
              className: utils.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__ */ jsxRuntime.jsx("div", { className: "w-4 h-4 flex items-center justify-center", children: node.isExpanded ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronDown, { className: "h-3 w-3" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronRight, { className: "h-3 w-3" }) }),
                showFileIcons && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-4 h-4 flex items-center justify-center flex-shrink-0", children: node.type === "folder" ? /* @__PURE__ */ jsxRuntime.jsx(FolderIcon, { className: "h-4 w-4 text-blue-500" }) : Icon ? /* @__PURE__ */ jsxRuntime.jsx(Icon, { className: "h-4 w-4 text-muted-foreground" }) : null }),
                /* @__PURE__ */ jsxRuntime.jsx("span", { className: "flex-1 truncate", children: node.name }),
                showFileSize && node.type === "file" && node.size && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground flex-shrink-0", children: formatFileSize(node.size) }),
                showModifiedDate && node.modified && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground flex-shrink-0", children: formatModifiedDate(node.modified) })
              ]
            }
          ),
          node.type === "folder" && node.isExpanded && node.children && /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsxs(
      "div",
      {
        ref,
        className: utils.cn(codeExplorerVariants({ size }), className),
        style: { height },
        ...props,
        children: [
          showSearch && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center gap-2 border-b px-4 py-2", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex-1", children: [
            /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Search, { className: "absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" }),
            /* @__PURE__ */ jsxRuntime.jsx(
              input.Input,
              {
                value: searchTerm,
                onChange: (e) => setSearchTerm(e.target.value),
                placeholder: searchPlaceholder,
                className: "pl-8 pr-8 h-8"
              }
            ),
            searchTerm && /* @__PURE__ */ jsxRuntime.jsx(
              button.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__ */ jsxRuntime.jsx(lucideReact.X, { className: "h-3 w-3" })
              }
            )
          ] }) }),
          /* @__PURE__ */ jsxRuntime.jsx(scrollArea.ScrollArea, { className: "flex-1", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "p-2", children: processedFiles.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-center h-24 text-muted-foreground", children: searchTerm ? `No files match "${searchTerm}"` : emptyMessage }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-0.5", children: processedFiles.map((node) => renderFileNode(node, 0)) }) }) }),
          /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsx("span", { children: " (filtered)" })
          ] })
        ]
      }
    );
  }
);
CodeExplorer.displayName = "CodeExplorer";

exports.CodeExplorer = CodeExplorer;
exports.codeExplorerVariants = codeExplorerVariants;
