"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Code, X, Trash2 } from "lucide-react";
import { JsonView } from "react-json-view-lite";
import { cn } from "@open-mercato/shared/lib/utils";
function DebugPanel({ events, onClear, isOpen, onToggle }) {
  const scrollRef = React.useRef(null);
  const filteredEvents = React.useMemo(
    () => events.filter((e) => e.type !== "text"),
    [events]
  );
  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [filteredEvents]);
  if (!isOpen) {
    return null;
  }
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full min-h-0", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex-shrink-0 flex items-center justify-between px-3 py-2 border-b border-gray-700", children: [
      /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-gray-300", children: [
        "Debug Events (",
        filteredEvents.length,
        ")"
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx(
          "button",
          {
            onClick: onClear,
            className: "text-gray-400 hover:text-gray-200",
            title: "Clear events",
            children: /* @__PURE__ */ jsx(Trash2, { className: "w-3 h-3" })
          }
        ),
        /* @__PURE__ */ jsx(
          "button",
          {
            onClick: onToggle,
            className: "text-gray-400 hover:text-gray-200",
            title: "Close debug panel",
            children: /* @__PURE__ */ jsx(X, { className: "w-3 h-3" })
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { ref: scrollRef, className: "flex-1 min-h-0 overflow-y-auto p-2 space-y-1", children: [
      filteredEvents.map((event) => /* @__PURE__ */ jsx(DebugEventRow, { event }, event.id)),
      filteredEvents.length === 0 && /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-500 text-center py-4", children: "No events yet" })
    ] })
  ] });
}
function parseNestedJson(data) {
  if (typeof data === "string") {
    try {
      const parsed = JSON.parse(data);
      return parseNestedJson(parsed);
    } catch {
      return data;
    }
  }
  if (Array.isArray(data)) {
    return data.map(parseNestedJson);
  }
  if (data && typeof data === "object") {
    const result = {};
    for (const [key, value] of Object.entries(data)) {
      result[key] = parseNestedJson(value);
    }
    return result;
  }
  return data;
}
const customDarkStyles = {
  container: "bg-transparent text-overline leading-relaxed font-mono",
  basicChildStyle: "pl-4 ml-0",
  label: "text-purple-400 mr-1",
  nullValue: "text-gray-500 italic",
  undefinedValue: "text-gray-500 italic",
  stringValue: "text-green-400",
  booleanValue: "text-yellow-400",
  numberValue: "text-blue-400",
  otherValue: "text-gray-300",
  punctuation: "text-gray-500",
  collapseIcon: "text-gray-400 cursor-pointer select-none mr-1",
  expandIcon: "text-gray-400 cursor-pointer select-none mr-1",
  collapsedContent: "text-gray-500"
};
function DebugEventRow({ event }) {
  const [expanded, setExpanded] = React.useState(false);
  const typeColors = {
    "thinking": "text-orange-400",
    "tool-call": "text-blue-400",
    "tool-result": "text-green-400",
    "text": "text-gray-300",
    "error": "text-red-400",
    "done": "text-purple-400",
    "message": "text-yellow-400",
    "connection": "text-cyan-400",
    "metadata": "text-teal-400",
    "debug": "text-gray-500",
    "question": "text-amber-400"
  };
  const formatTime = (date) => {
    return date.toLocaleTimeString("en-US", {
      hour12: false,
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit"
    }) + "." + String(date.getMilliseconds()).padStart(3, "0");
  };
  const parsedData = React.useMemo(() => parseNestedJson(event.data), [event.data]);
  return /* @__PURE__ */ jsxs("div", { className: "text-xs font-mono", children: [
    /* @__PURE__ */ jsxs(
      "button",
      {
        onClick: () => setExpanded(!expanded),
        className: "w-full text-left flex items-center gap-2 hover:bg-gray-800 rounded px-1 py-0.5",
        children: [
          /* @__PURE__ */ jsx("span", { className: "text-gray-500 flex-shrink-0", children: formatTime(event.timestamp) }),
          /* @__PURE__ */ jsx("span", { className: cn("font-medium flex-shrink-0", typeColors[event.type] || "text-gray-400"), children: event.type }),
          /* @__PURE__ */ jsx("span", { className: "text-gray-400 truncate flex-1", children: getEventPreview(event) }),
          /* @__PURE__ */ jsx("span", { className: "text-gray-600 flex-shrink-0", children: expanded ? "\u25BC" : "\u25B6" })
        ]
      }
    ),
    expanded && /* @__PURE__ */ jsx("div", { className: "bg-gray-800 rounded p-2 mt-1 overflow-x-auto max-h-[300px] overflow-y-auto", children: /* @__PURE__ */ jsx(
      JsonView,
      {
        data: parsedData,
        style: customDarkStyles,
        shouldExpandNode: (level) => level < 2
      }
    ) })
  ] });
}
function getEventPreview(event) {
  const data = event.data;
  if (event.type === "thinking") {
    return "Agent is processing...";
  }
  if (event.type === "tool-call") {
    const toolName = data?.toolName || "unknown";
    const args = data?.args;
    const argsPreview = args ? JSON.stringify(args).substring(0, 40) : "";
    return `${toolName}(${argsPreview}${argsPreview.length >= 40 ? "..." : ""})`;
  }
  if (event.type === "tool-result") {
    const result = data?.result;
    const resultPreview = typeof result === "string" ? result.substring(0, 50) : JSON.stringify(result)?.substring(0, 50);
    return `\u2192 ${resultPreview}${resultPreview && resultPreview.length >= 50 ? "..." : ""}`;
  }
  if (event.type === "text") {
    const content = data?.content || "";
    return content.substring(0, 50) + (content.length > 50 ? "..." : "");
  }
  if (event.type === "error") {
    return data?.error || "Unknown error";
  }
  if (event.type === "message") {
    const role = data?.role || "";
    const content = data?.content || "";
    return `[${role}] ${content.substring(0, 40)}...`;
  }
  if (event.type === "connection") {
    return data?.status || "";
  }
  if (event.type === "metadata") {
    const model = data?.model || "";
    const tokens = data?.tokens;
    const durationMs = data?.durationMs;
    const parts = [];
    if (model) parts.push(model);
    if (tokens) parts.push(`${tokens.input || 0}\u2192${tokens.output || 0} tokens`);
    if (durationMs) parts.push(`${(durationMs / 1e3).toFixed(1)}s`);
    return parts.join(" | ") || "No metadata";
  }
  if (event.type === "debug") {
    const partType = data?.partType || "unknown";
    return `Unknown part: ${partType}`;
  }
  if (event.type === "question") {
    const questionText = data?.questionText || data?.question?.questions?.[0]?.question || data?.header || "Confirmation required";
    return questionText.substring(0, 50) + (questionText.length > 50 ? "..." : "");
  }
  return "";
}
function DebugToggleButton({
  isOpen,
  onToggle
}) {
  return /* @__PURE__ */ jsxs(
    "button",
    {
      type: "button",
      onClick: onToggle,
      className: cn(
        "flex items-center gap-1 text-xs transition-colors",
        isOpen ? "text-blue-500 hover:text-blue-400" : "text-muted-foreground hover:text-foreground"
      ),
      title: "Toggle debug panel",
      children: [
        /* @__PURE__ */ jsx(Code, { className: "w-3 h-3" }),
        /* @__PURE__ */ jsx("span", { children: isOpen ? "Hide Debug" : "Debug" })
      ]
    }
  );
}
export {
  DebugPanel,
  DebugToggleButton
};
//# sourceMappingURL=DebugPanel.js.map
