"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useMemo } from "react";
import { Search, ChevronRight, ChevronDown, Code, Database, Layers, Puzzle, PanelLeftClose, PanelLeft, Folder, FolderOpen } from "lucide-react";
import { Input } from "../../ui/input.js";
import { Badge } from "../../ui/badge.js";
import { Button } from "../../ui/button.js";
import { ScrollArea } from "../../ui/scroll-area.js";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "../../ui/collapsible.js";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
const methodColors = {
  GET: "bg-emerald-500/20 text-emerald-600 dark:text-emerald-400",
  POST: "bg-blue-500/20 text-blue-600 dark:text-blue-400",
  PATCH: "bg-amber-500/20 text-amber-600 dark:text-amber-400",
  PUT: "bg-orange-500/20 text-orange-600 dark:text-orange-400",
  DELETE: "bg-red-500/20 text-red-600 dark:text-red-400",
  OPTIONS: "bg-gray-500/20 text-gray-600 dark:text-gray-400"
};
const categoryConfig = {
  core: { icon: Code, label: "Core", color: "text-violet-600 dark:text-violet-400" },
  entity: { icon: Database, label: "Entities", color: "text-blue-600 dark:text-blue-400" },
  theme: { icon: Layers, label: "Theme", color: "text-pink-600 dark:text-pink-400" },
  plugin: { icon: Puzzle, label: "Plugins", color: "text-green-600 dark:text-green-400" }
};
function groupByPathPrefix(routes) {
  const groups = /* @__PURE__ */ new Map();
  for (const route of routes) {
    const pathWithoutBase = route.path.replace(/^\/api\/v1\//, "");
    const firstSegment = pathWithoutBase.split("/")[0] || "root";
    if (!groups.has(firstSegment)) {
      groups.set(firstSegment, []);
    }
    groups.get(firstSegment).push(route);
  }
  return Array.from(groups.entries()).sort(([a], [b]) => a.localeCompare(b)).map(([prefix, routes2]) => ({ prefix, routes: routes2 }));
}
function ApiEndpointsSidebar({
  routes,
  selectedEndpoint,
  onSelectEndpoint,
  isCollapsed,
  onToggleCollapse
}) {
  const [searchQuery, setSearchQuery] = useState("");
  const [expandedCategories, setExpandedCategories] = useState(
    /* @__PURE__ */ new Set(["core", "entity", "theme", "plugin"])
  );
  const [expandedPrefixes, setExpandedPrefixes] = useState(/* @__PURE__ */ new Set());
  const filteredRoutes = useMemo(() => {
    if (!searchQuery.trim()) return routes;
    const query = searchQuery.toLowerCase();
    const result = {
      core: [],
      entity: [],
      theme: [],
      plugin: []
    };
    for (const category of Object.keys(routes)) {
      result[category] = routes[category].filter(
        (route) => {
          var _a;
          return route.path.toLowerCase().includes(query) || ((_a = route.source) == null ? void 0 : _a.toLowerCase().includes(query)) || route.methods.some((m) => m.toLowerCase().includes(query));
        }
      );
    }
    return result;
  }, [routes, searchQuery]);
  const toggleCategory = (category) => {
    setExpandedCategories((prev) => {
      const next = new Set(prev);
      if (next.has(category)) {
        next.delete(category);
      } else {
        next.add(category);
      }
      return next;
    });
  };
  const togglePrefix = (category, prefix) => {
    const key = `${category}:${prefix}`;
    setExpandedPrefixes((prev) => {
      const next = new Set(prev);
      if (next.has(key)) {
        next.delete(key);
      } else {
        next.add(key);
      }
      return next;
    });
  };
  const totalRoutes = Object.values(filteredRoutes).reduce((sum, arr) => sum + arr.length, 0);
  if (isCollapsed) {
    return /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full w-14 border-r bg-card", "data-cy": sel("devtools.apiExplorer.sidebar.collapsed"), children: [
      /* @__PURE__ */ jsx("div", { className: "p-2 border-b", children: /* @__PURE__ */ jsx(
        Button,
        {
          variant: "ghost",
          size: "icon",
          onClick: onToggleCollapse,
          className: "w-full",
          "data-cy": sel("devtools.apiExplorer.sidebar.expand"),
          children: /* @__PURE__ */ jsx(PanelLeft, { className: "h-4 w-4" })
        }
      ) }),
      /* @__PURE__ */ jsx("div", { className: "flex-1 flex flex-col items-center gap-2 p-2", children: Object.keys(categoryConfig).map((category) => {
        const config = categoryConfig[category];
        const Icon = config.icon;
        const count = filteredRoutes[category].length;
        return /* @__PURE__ */ jsxs(
          Button,
          {
            variant: "ghost",
            size: "icon",
            className: cn("relative", config.color),
            title: `${config.label} (${count})`,
            onClick: () => {
              onToggleCollapse();
              setExpandedCategories(/* @__PURE__ */ new Set([category]));
            },
            children: [
              /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" }),
              count > 0 && /* @__PURE__ */ jsx("span", { className: "absolute -top-1 -right-1 text-[10px] bg-muted rounded-full px-1", children: count })
            ]
          },
          category
        );
      }) })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full w-72 shrink-0 border-r bg-card", "data-cy": sel("devtools.apiExplorer.sidebar.container"), children: [
    /* @__PURE__ */ jsxs("div", { className: "p-3 border-b space-y-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("h2", { className: "font-semibold text-sm", children: "Endpoints" }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: totalRoutes }),
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: "ghost",
              size: "icon",
              className: "h-7 w-7",
              onClick: onToggleCollapse,
              "data-cy": sel("devtools.apiExplorer.sidebar.collapse"),
              children: /* @__PURE__ */ jsx(PanelLeftClose, { className: "h-4 w-4" })
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "relative", children: [
        /* @__PURE__ */ jsx(Search, { className: "absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx(
          Input,
          {
            placeholder: "Search endpoints...",
            value: searchQuery,
            onChange: (e) => setSearchQuery(e.target.value),
            className: "pl-8 h-8 text-sm",
            "data-cy": sel("devtools.apiExplorer.sidebar.search")
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx(ScrollArea, { className: "flex-1", children: /* @__PURE__ */ jsx("div", { className: "p-2 space-y-1", children: Object.keys(categoryConfig).map((category) => {
      const config = categoryConfig[category];
      const Icon = config.icon;
      const categoryRoutes = filteredRoutes[category];
      const isExpanded = expandedCategories.has(category);
      if (categoryRoutes.length === 0 && searchQuery) return null;
      return /* @__PURE__ */ jsxs(
        Collapsible,
        {
          open: isExpanded,
          onOpenChange: () => toggleCategory(category),
          children: [
            /* @__PURE__ */ jsx(CollapsibleTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
              "button",
              {
                className: cn(
                  "flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm font-medium",
                  "hover:bg-muted/50 transition-colors",
                  config.color
                ),
                "data-cy": sel("devtools.apiExplorer.sidebar.category", { category }),
                children: [
                  isExpanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4 shrink-0" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4 shrink-0" }),
                  /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4 shrink-0" }),
                  /* @__PURE__ */ jsx("span", { className: "flex-1 text-left", children: config.label }),
                  /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: categoryRoutes.length })
                ]
              }
            ) }),
            /* @__PURE__ */ jsx(CollapsibleContent, { children: /* @__PURE__ */ jsx("div", { className: "ml-2 mt-1 space-y-0.5", children: categoryRoutes.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground px-2 py-2", children: "No endpoints in this category" }) : groupByPathPrefix(categoryRoutes).map((group) => {
              const prefixKey = `${category}:${group.prefix}`;
              const isPrefixExpanded = expandedPrefixes.has(prefixKey);
              return /* @__PURE__ */ jsxs(
                Collapsible,
                {
                  open: isPrefixExpanded,
                  onOpenChange: () => togglePrefix(category, group.prefix),
                  children: [
                    /* @__PURE__ */ jsx(CollapsibleTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                      "button",
                      {
                        className: cn(
                          "flex items-center gap-1.5 w-full px-2 py-1 rounded-md text-xs",
                          "hover:bg-muted/50 transition-colors text-muted-foreground"
                        ),
                        "data-cy": sel("devtools.apiExplorer.sidebar.prefix", { category, prefix: group.prefix }),
                        children: [
                          isPrefixExpanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3 shrink-0" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-3 w-3 shrink-0" }),
                          isPrefixExpanded ? /* @__PURE__ */ jsx(FolderOpen, { className: "h-3 w-3 shrink-0" }) : /* @__PURE__ */ jsx(Folder, { className: "h-3 w-3 shrink-0" }),
                          /* @__PURE__ */ jsx("span", { className: "flex-1 text-left font-medium", children: group.prefix }),
                          /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-[10px] px-1 py-0 h-4", children: group.routes.length })
                        ]
                      }
                    ) }),
                    /* @__PURE__ */ jsx(CollapsibleContent, { children: /* @__PURE__ */ jsx("div", { className: "ml-4 mt-0.5 space-y-0.5", children: group.routes.map((route, idx) => /* @__PURE__ */ jsx(
                      EndpointItem,
                      {
                        route,
                        prefix: group.prefix,
                        selectedEndpoint,
                        onSelect: onSelectEndpoint
                      },
                      `${route.path}-${idx}`
                    )) }) })
                  ]
                },
                prefixKey
              );
            }) }) })
          ]
        },
        category
      );
    }) }) })
  ] });
}
function EndpointItem({ route, prefix, selectedEndpoint, onSelect }) {
  return /* @__PURE__ */ jsx(Fragment, { children: route.methods.map((method) => {
    const isSelected = (selectedEndpoint == null ? void 0 : selectedEndpoint.path) === route.path && (selectedEndpoint == null ? void 0 : selectedEndpoint.method) === method;
    const shortPath = route.path.replace(/^\/api\/v1\//, "").replace(new RegExp(`^${prefix}/?`), "");
    return /* @__PURE__ */ jsxs(
      "button",
      {
        onClick: () => onSelect(route.path, method, route),
        className: cn(
          "flex items-center gap-2 w-full px-2 py-1 rounded-md text-xs",
          "hover:bg-muted/50 transition-colors text-left",
          isSelected && "bg-primary/10 ring-1 ring-primary/20"
        ),
        "data-cy": sel("devtools.apiExplorer.sidebar.endpoint", { method: method.toLowerCase(), path: route.path.replace(/\//g, "-") }),
        children: [
          /* @__PURE__ */ jsx(
            Badge,
            {
              variant: "secondary",
              className: cn("font-mono text-[10px] px-1.5 py-0 shrink-0", methodColors[method]),
              children: method
            }
          ),
          /* @__PURE__ */ jsxs("span", { className: "font-mono truncate text-muted-foreground", children: [
            "/",
            shortPath || ""
          ] })
        ]
      },
      `${route.path}-${method}`
    );
  }) });
}
export {
  ApiEndpointsSidebar
};
