"use client";
import * as React from 'react';
import { cva } from 'class-variance-authority';
import { Check, Copy, Eye, EyeOff, Terminal, RefreshCw, Play, Square, Settings, AlertTriangle, X } from 'lucide-react';
import { cn } from '@hanzo/ui/lib/utils';
import { Badge } from '@hanzo/ui/badge';
import { Button } from '@hanzo/ui/button';
import { CodeSnippet } from '@hanzo/ui/code/snippet';
import { Separator } from '@hanzo/ui/separator';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@hanzo/ui/tabs';
import { Toggle } from '@hanzo/ui/toggle';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
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 = React.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] = React.useState(
      defaultFile || files[0]?.filename || ""
    );
    const [previewContent, setPreviewContent] = React.useState("");
    const [isRunning, setIsRunning] = React.useState(false);
    const [results, setResults] = React.useState([]);
    const [isPreviewVisible, setIsPreviewVisible] = React.useState(showPreview);
    const [isConsoleVisible, setIsConsoleVisible] = React.useState(showConsole);
    const [isFullscreen, setIsFullscreen] = React.useState(false);
    const [copied, setCopied] = React.useState({});
    const iframeRef = React.useRef(null);
    files.find((f) => f.filename === activeFile) || files[0];
    React.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 = React.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]);
    React.useEffect(() => {
      if (autoRun) {
        const timer = setTimeout(runCode, 1e3);
        return () => clearTimeout(timer);
      }
    }, [files, autoRun, runCode]);
    const copyFileContent = React.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";

export { CodePreview, codePreviewVariants };
