"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { Code, Menu, X } from "lucide-react";
import { Button } from "../../ui/button.js";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
import { ApiEndpointsSidebar } from "./ApiEndpointsSidebar.js";
import { ApiRequestPanel } from "./ApiRequestPanel.js";
import { ApiResponsePanel } from "./ApiResponsePanel.js";
import { useApiRequest } from "../api-tester/hooks/useApiRequest.js";
import { useApiExplorerNavigation } from "../../../hooks/useApiExplorerNavigation.js";
import { extractPathParams, buildUrl } from "../api-tester/utils/url-builder.js";
import { ApiPresetsService } from "../../../lib/services/api-presets.service.js";
import { ApiDocsService } from "../../../lib/services/api-docs.service.js";
function findRouteByPath(routes, path) {
  for (const category of Object.keys(routes)) {
    const found = routes[category].find((r) => r.path === path);
    if (found) return found;
  }
  return null;
}
function createEmptyRows(count = 2) {
  return Array.from({ length: count }, () => ({
    id: crypto.randomUUID(),
    key: "",
    value: "",
    enabled: true
  }));
}
function ApiExplorer({ routes, initialEndpoint }) {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [selectedEndpoint, setSelectedEndpoint] = useState(null);
  const [method, setMethod] = useState("GET");
  const [pathParams, setPathParams] = useState([]);
  const [queryParams, setQueryParams] = useState(() => createEmptyRows());
  const [headers, setHeaders] = useState(() => createEmptyRows());
  const [authType, setAuthType] = useState("session");
  const [apiKey, setApiKey] = useState("");
  const [bypassMode, setBypassMode] = useState(false);
  const [selectedTeamId, setSelectedTeamId] = useState(() => {
    if (typeof window !== "undefined") {
      return localStorage.getItem("activeTeamId");
    }
    return null;
  });
  const [body, setBody] = useState("");
  const [tabsModifiedByPreset, setTabsModifiedByPreset] = useState(
    () => /* @__PURE__ */ new Set()
  );
  const endpointPresets = useMemo(() => {
    if (!selectedEndpoint) return null;
    return ApiPresetsService.getByEndpoint(selectedEndpoint.path) ?? null;
  }, [selectedEndpoint == null ? void 0 : selectedEndpoint.path]);
  const endpointDoc = useMemo(() => {
    if (!selectedEndpoint) return null;
    return ApiDocsService.getByEndpoint(selectedEndpoint.path) ?? null;
  }, [selectedEndpoint == null ? void 0 : selectedEndpoint.path]);
  const hasInitialized = useRef(false);
  const { status, response, error, execute, cancel, reset } = useApiRequest();
  const { selectedMethod: urlMethod, selectedPath: urlPath, navigateToEndpoint } = useApiExplorerNavigation({ basePath: "/devtools/api" });
  const handleSelectEndpoint = useCallback(
    (path, selectedMethod, route) => {
      reset();
      navigateToEndpoint(selectedMethod, path);
      setSelectedEndpoint({ path, method: selectedMethod, route });
      setMethod(selectedMethod);
      setPathParams(extractPathParams(path));
      setQueryParams(createEmptyRows());
      setHeaders(createEmptyRows());
      setBody("");
      setTabsModifiedByPreset(/* @__PURE__ */ new Set());
      setMobileOpen(false);
    },
    [reset, navigateToEndpoint]
  );
  const handleSend = useCallback(async () => {
    if (!selectedEndpoint) return;
    const url = buildUrl(selectedEndpoint.path, pathParams, queryParams);
    const fullUrl = (typeof window !== "undefined" ? window.location.origin : "") + url;
    const customHeaders = {};
    if (bypassMode) {
      customHeaders["x-admin-bypass"] = "confirm-cross-team-access";
      if (selectedTeamId) {
        customHeaders["x-team-id"] = selectedTeamId;
      }
    } else {
      if (selectedTeamId) {
        customHeaders["x-team-id"] = selectedTeamId;
      }
    }
    for (const h of headers) {
      if (h.enabled && h.key) {
        customHeaders[h.key] = h.value;
      }
    }
    await execute({
      url: fullUrl,
      method,
      headers: customHeaders,
      body: ["POST", "PATCH", "PUT"].includes(method) ? body : void 0,
      authType,
      apiKey: authType === "apiKey" ? apiKey : void 0
    });
  }, [selectedEndpoint, pathParams, queryParams, headers, method, body, authType, apiKey, bypassMode, selectedTeamId, execute]);
  const handleApplyPreset = useCallback((preset) => {
    const modifiedTabs = /* @__PURE__ */ new Set();
    if (preset.method) {
      setMethod(preset.method);
    }
    if (preset.pathParams && Object.keys(preset.pathParams).length > 0) {
      setPathParams(
        (prev) => prev.map((p) => {
          var _a;
          return {
            ...p,
            value: ((_a = preset.pathParams) == null ? void 0 : _a[p.name]) ?? p.value
          };
        })
      );
      modifiedTabs.add("params");
    }
    if (preset.params && Object.keys(preset.params).length > 0) {
      const newParams = Object.entries(preset.params).map(([key, value], idx) => ({
        id: `preset-${idx}-${crypto.randomUUID()}`,
        key,
        value: String(value),
        enabled: true
      }));
      setQueryParams(newParams);
      modifiedTabs.add("params");
    }
    if (preset.headers && Object.keys(preset.headers).length > 0) {
      const newHeaders = Object.entries(preset.headers).map(([key, value], idx) => ({
        id: `preset-header-${idx}-${crypto.randomUUID()}`,
        key,
        value,
        enabled: true
      }));
      setHeaders(newHeaders);
      modifiedTabs.add("headers");
    }
    if (preset.payload && Object.keys(preset.payload).length > 0) {
      setBody(JSON.stringify(preset.payload, null, 2));
      modifiedTabs.add("body");
    }
    if (preset.sessionConfig) {
      if (preset.sessionConfig.crossTeam !== void 0) {
        setBypassMode(preset.sessionConfig.crossTeam);
      }
      if (preset.sessionConfig.teamId) {
        let teamId = preset.sessionConfig.teamId;
        if (teamId === "{{FIRST_TEAM_ID}}" && typeof window !== "undefined") {
          teamId = localStorage.getItem("firstTeamId") || localStorage.getItem("activeTeamId") || "";
        }
        setSelectedTeamId(teamId);
      }
      if (preset.sessionConfig.authType) {
        setAuthType(preset.sessionConfig.authType);
      }
    }
    setTabsModifiedByPreset(modifiedTabs);
  }, []);
  useEffect(() => {
    if (urlPath && urlMethod) {
      const route = findRouteByPath(routes, urlPath);
      if (route && ((selectedEndpoint == null ? void 0 : selectedEndpoint.path) !== urlPath || (selectedEndpoint == null ? void 0 : selectedEndpoint.method) !== urlMethod)) {
        setSelectedEndpoint({ path: urlPath, method: urlMethod, route });
        setMethod(urlMethod);
        setPathParams(extractPathParams(urlPath));
        setQueryParams(createEmptyRows());
        setHeaders(createEmptyRows());
        setBody("");
        setTabsModifiedByPreset(/* @__PURE__ */ new Set());
      }
    }
  }, [urlPath, urlMethod, routes, selectedEndpoint]);
  useEffect(() => {
    if (hasInitialized.current) return;
    if (urlPath && urlMethod) {
      const route = findRouteByPath(routes, urlPath);
      if (route) {
        hasInitialized.current = true;
        setSelectedEndpoint({ path: urlPath, method: urlMethod, route });
        setMethod(urlMethod);
        setPathParams(extractPathParams(urlPath));
        return;
      }
    }
    if (initialEndpoint) {
      const route = findRouteByPath(routes, initialEndpoint.path);
      if (route) {
        hasInitialized.current = true;
        const endpointMethod = initialEndpoint.method;
        setSelectedEndpoint({ path: initialEndpoint.path, method: endpointMethod, route });
        setMethod(endpointMethod);
        setPathParams(extractPathParams(initialEndpoint.path));
        if (!urlPath) {
          navigateToEndpoint(endpointMethod, initialEndpoint.path);
        }
        return;
      }
    }
    const categories = ["core", "entity", "theme", "plugin"];
    for (const category of categories) {
      const categoryRoutes = routes[category];
      if (categoryRoutes.length > 0) {
        hasInitialized.current = true;
        const firstRoute = categoryRoutes[0];
        const firstMethod = firstRoute.methods[0] || "GET";
        setSelectedEndpoint({ path: firstRoute.path, method: firstMethod, route: firstRoute });
        setMethod(firstMethod);
        setPathParams(extractPathParams(firstRoute.path));
        navigateToEndpoint(firstMethod, firstRoute.path);
        break;
      }
    }
  }, [routes, initialEndpoint, urlPath, urlMethod, navigateToEndpoint]);
  const totalRoutes = Object.values(routes).reduce((sum, arr) => sum + arr.length, 0);
  return /* @__PURE__ */ jsxs("div", { className: "flex h-[calc(100vh-4rem)] w-full overflow-hidden", "data-cy": sel("devtools.apiExplorer.container"), children: [
    /* @__PURE__ */ jsxs("div", { className: "lg:hidden fixed top-0 left-0 right-0 z-50 h-14 bg-background border-b flex items-center px-4 gap-3", children: [
      /* @__PURE__ */ jsx(
        Button,
        {
          variant: "ghost",
          size: "icon",
          onClick: () => setMobileOpen(!mobileOpen),
          "data-cy": sel("devtools.apiExplorer.mobileToggle"),
          children: mobileOpen ? /* @__PURE__ */ jsx(X, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Menu, { className: "h-5 w-5" })
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsx(Code, { className: "h-5 w-5 text-violet-600" }),
        /* @__PURE__ */ jsx("span", { className: "font-semibold", children: "API Explorer" })
      ] }),
      selectedEndpoint && /* @__PURE__ */ jsxs("code", { className: "text-xs text-muted-foreground truncate ml-auto", children: [
        selectedEndpoint.method,
        " ",
        selectedEndpoint.path
      ] })
    ] }),
    mobileOpen && /* @__PURE__ */ jsx(
      "div",
      {
        className: "lg:hidden fixed inset-0 z-40 bg-black/50",
        onClick: () => setMobileOpen(false)
      }
    ),
    /* @__PURE__ */ jsx(
      "div",
      {
        className: cn(
          "fixed lg:relative z-50 lg:z-auto h-full transition-transform duration-300",
          "lg:translate-x-0",
          mobileOpen ? "translate-x-0" : "-translate-x-full"
        ),
        children: /* @__PURE__ */ jsx(
          ApiEndpointsSidebar,
          {
            routes,
            selectedEndpoint: selectedEndpoint ? { path: selectedEndpoint.path, method: selectedEndpoint.method } : null,
            onSelectEndpoint: handleSelectEndpoint,
            isCollapsed,
            onToggleCollapse: () => setIsCollapsed(!isCollapsed)
          }
        )
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "flex-1 flex flex-col lg:flex-row min-w-0 pt-14 lg:pt-0", children: selectedEndpoint ? /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx("div", { className: "flex-1 lg:flex-[1.2] min-h-0 border-b lg:border-b-0 lg:border-r overflow-hidden", children: /* @__PURE__ */ jsx(
        ApiRequestPanel,
        {
          route: selectedEndpoint.route,
          basePath: selectedEndpoint.path,
          method,
          pathParams,
          queryParams,
          headers,
          authType,
          apiKey,
          bypassMode,
          selectedTeamId,
          body,
          status,
          onMethodChange: setMethod,
          onPathParamsChange: setPathParams,
          onQueryParamsChange: setQueryParams,
          onHeadersChange: setHeaders,
          onAuthTypeChange: setAuthType,
          onApiKeyChange: setApiKey,
          onBypassModeChange: setBypassMode,
          onTeamChange: setSelectedTeamId,
          onBodyChange: setBody,
          onSend: handleSend,
          onCancel: cancel,
          endpointPresets,
          endpointDoc,
          onApplyPreset: handleApplyPreset,
          tabsModifiedByPreset,
          onClearPresetIndicator: (tab) => {
            setTabsModifiedByPreset((prev) => {
              const next = new Set(prev);
              next.delete(tab);
              return next;
            });
          }
        }
      ) }),
      /* @__PURE__ */ jsx("div", { className: "h-[40vh] lg:h-auto lg:flex-1 min-h-[200px] overflow-hidden", children: /* @__PURE__ */ jsx(
        ApiResponsePanel,
        {
          status,
          response,
          error
        }
      ) })
    ] }) : (
      /* Empty state */
      /* @__PURE__ */ jsx("div", { className: "flex-1 flex items-center justify-center text-muted-foreground", children: /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
        /* @__PURE__ */ jsx(Code, { className: "h-12 w-12 mx-auto mb-4 opacity-50" }),
        /* @__PURE__ */ jsx("p", { className: "text-lg font-medium", children: "No endpoint selected" }),
        /* @__PURE__ */ jsx("p", { className: "text-sm", children: totalRoutes > 0 ? "Select an endpoint from the sidebar to get started" : "No API endpoints available" })
      ] }) })
    ) })
  ] });
}
export {
  ApiExplorer
};
