"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 separator = require('@hanzo/ui/separator');
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 codeTerminalVariants = classVarianceAuthority.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__ */ jsxRuntime.jsx("span", { className: utils.cn(part.classes), children: part.text }, index));
}, "parseAnsiContent");
var CodeTerminal = React__namespace.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] = React__namespace.useState(initialLines);
    const [input$1, setInput] = React__namespace.useState("");
    const [historyIndex, setHistoryIndex] = React__namespace.useState(-1);
    const [isFullscreen, setIsFullscreen] = React__namespace.useState(false);
    const [commandHistory, setCommandHistory] = React__namespace.useState(history);
    const scrollAreaRef = React__namespace.useRef(null);
    const inputRef = React__namespace.useRef(null);
    React__namespace.useEffect(() => {
      if (autoScroll && scrollAreaRef.current) {
        scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
      }
    }, [lines, autoScroll]);
    const addLine = React__namespace.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 = React__namespace.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$1.trim()) {
        handleCommand(input$1);
        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 = React__namespace.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 = React__namespace.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__ */ jsxRuntime.jsxs(
      "div",
      {
        ref,
        className: utils.cn(
          codeTerminalVariants({ theme, size }),
          isFullscreen && "fixed inset-0 z-50",
          className
        ),
        style: { height: isFullscreen ? "100vh" : height },
        onClick: handleTerminalClick,
        ...props,
        children: [
          /* @__PURE__ */ jsxRuntime.jsxs("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-2", children: [
              /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1", children: [
                /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-3 h-3 rounded-full bg-red-500" }),
                /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-3 h-3 rounded-full bg-yellow-500" }),
                /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-3 h-3 rounded-full bg-green-500" })
              ] }),
              /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Terminal, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: title }),
              lines.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-xs text-muted-foreground", children: [
                lines.length,
                " lines"
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1", children: [
              allowClear && /* @__PURE__ */ jsxRuntime.jsx(
                button.Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: clearTerminal,
                  className: "h-8 w-8 p-0",
                  children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.RefreshCw, { className: "h-3.5 w-3.5" })
                }
              ),
              allowCopy && /* @__PURE__ */ jsxRuntime.jsx(
                button.Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: copyContent,
                  className: "h-8 w-8 p-0",
                  children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Copy, { className: "h-3.5 w-3.5" })
                }
              ),
              allowDownload && /* @__PURE__ */ jsxRuntime.jsx(
                button.Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: downloadContent,
                  className: "h-8 w-8 p-0",
                  children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Download, { className: "h-3.5 w-3.5" })
                }
              ),
              allowFullscreen && /* @__PURE__ */ jsxRuntime.jsx(
                button.Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: () => setIsFullscreen(!isFullscreen),
                  className: "h-8 w-8 p-0",
                  children: isFullscreen ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Minimize2, { className: "h-3.5 w-3.5" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Maximize2, { className: "h-3.5 w-3.5" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 flex flex-col min-h-0", children: [
            /* @__PURE__ */ jsxRuntime.jsx(scrollArea.ScrollArea, { ref: scrollAreaRef, className: "flex-1 p-4", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-1 font-mono", children: lines.map((line, index) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-2", children: [
              showLineNumbers && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground w-12 text-right flex-shrink-0", children: index + 1 }),
              /* @__PURE__ */ jsxRuntime.jsx(
                "div",
                {
                  className: utils.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__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
              /* @__PURE__ */ jsxRuntime.jsx(separator.Separator, {}),
              /* @__PURE__ */ jsxRuntime.jsx("form", { onSubmit: handleInputSubmit, className: "p-4", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 font-mono", children: [
                /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronRight, { className: "h-4 w-4 flex-shrink-0" }),
                /* @__PURE__ */ jsxRuntime.jsx("span", { className: "flex-shrink-0", children: prompt }),
                /* @__PURE__ */ jsxRuntime.jsx(
                  input.Input,
                  {
                    ref: inputRef,
                    value: input$1,
                    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";

exports.CodeTerminal = CodeTerminal;
exports.codeTerminalVariants = codeTerminalVariants;
