"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { SearchX } from "lucide-react";
import { Input } from "@open-mercato/ui/primitives/input";
import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
const METHOD_STYLES = {
  GET: "bg-status-success-bg text-status-success-text border border-status-success-border",
  POST: "bg-status-info-bg text-status-info-text border border-status-info-border",
  PUT: "bg-status-warning-bg text-status-warning-text border border-status-warning-border",
  PATCH: "bg-brand-violet/10 text-brand-violet border border-brand-violet/30",
  DELETE: "bg-status-error-bg text-status-error-text border border-status-error-border"
};
const PREFERRED_MEDIA_TYPES = [
  "application/json",
  "application/x-www-form-urlencoded",
  "multipart/form-data",
  "text/plain"
];
function pickContentVariant(content) {
  if (!content) return null;
  const entries = Object.entries(content);
  if (!entries.length) return null;
  for (const mediaType2 of PREFERRED_MEDIA_TYPES) {
    const match = entries.find(([candidate]) => candidate === mediaType2);
    if (match) {
      return { mediaType: match[0], entry: match[1] };
    }
  }
  const [mediaType, entry] = entries[0];
  return { mediaType, entry };
}
function buildExampleFromSchema(schema) {
  if (!schema || typeof schema !== "object") return void 0;
  if (schema.example !== void 0) return schema.example;
  if (schema.default !== void 0) return schema.default;
  if (Array.isArray(schema.enum) && schema.enum.length) return schema.enum[0];
  if (Array.isArray(schema.oneOf) && schema.oneOf.length) return buildExampleFromSchema(schema.oneOf[0]);
  if (Array.isArray(schema.anyOf) && schema.anyOf.length) return buildExampleFromSchema(schema.anyOf[0]);
  if (Array.isArray(schema.allOf) && schema.allOf.length) {
    return Object.assign({}, ...schema.allOf.map((part) => buildExampleFromSchema(part) ?? {}));
  }
  const type = Array.isArray(schema.type) ? schema.type[0] : schema.type;
  if (schema.properties || type === "object" || !type && schema.required) {
    const properties = schema.properties ?? {};
    const result = {};
    for (const key of Object.keys(properties)) {
      const value = buildExampleFromSchema(properties[key]);
      if (value !== void 0) {
        result[key] = value;
      }
    }
    if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
      const value = buildExampleFromSchema(schema.additionalProperties);
      if (value !== void 0) {
        result["additionalProperty"] = value;
      }
    }
    return Object.keys(result).length ? result : {};
  }
  if (type === "array") {
    const itemSchema = schema.items ?? (Array.isArray(schema.prefixItems) ? schema.prefixItems[0] : void 0);
    const value = buildExampleFromSchema(itemSchema);
    return value === void 0 ? [] : [value];
  }
  if (type === "number" || type === "integer") return 1;
  if (type === "boolean") return true;
  if (schema.format === "date-time") return (/* @__PURE__ */ new Date("2025-01-01T00:00:00.000Z")).toISOString();
  if (schema.format === "uuid") return "00000000-0000-4000-8000-000000000000";
  if (schema.format === "email") return "user@example.com";
  if (schema.format === "uri" || schema.format === "url") return "https://example.com/resource";
  return "string";
}
function stringifyExample(mediaType, example) {
  if (example === void 0 || example === null) return "";
  if (mediaType === "application/json") {
    try {
      return JSON.stringify(example, null, 2);
    } catch {
      return "";
    }
  }
  if (mediaType === "application/x-www-form-urlencoded") {
    if (typeof example !== "object") return "";
    const params = new URLSearchParams();
    for (const [key, value] of Object.entries(example)) {
      if (value === void 0) continue;
      params.append(key, value === null ? "" : String(value));
    }
    return params.toString();
  }
  if (mediaType === "multipart/form-data") {
    if (typeof example === "object") {
      return Object.entries(example).map(([key, value]) => `${key}=${value ?? ""}`).join("\n");
    }
    return typeof example === "string" ? example : "";
  }
  if (typeof example === "string") return example;
  try {
    return JSON.stringify(example, null, 2);
  } catch {
    return "";
  }
}
function formatJson(value) {
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return "";
  }
}
function applyPathParams(path, params) {
  return path.replace(/\{([^}]+)\}/g, (_, key) => {
    const value = params[key] ?? "";
    return value ? encodeURIComponent(value) : `{${key}}`;
  });
}
const PLACEHOLDER_BASE_URL = "https://api.your-service.com";
const CATEGORY_PAGE_SIZE = 20;
function escapeSingleQuotes(value) {
  return value.replace(/'/g, `'\\''`);
}
function escapeSingleQuotesForJs(value) {
  return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
}
function escapeBackticks(value) {
  return value.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
}
function toPythonLiteral(value, indent = 0) {
  const padding = "  ".repeat(indent);
  if (value === null || value === void 0) return "None";
  if (typeof value === "boolean") return value ? "True" : "False";
  if (typeof value === "number" && Number.isFinite(value)) return String(value);
  if (typeof value === "string") {
    return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
  }
  if (Array.isArray(value)) {
    if (!value.length) return "[]";
    const entries = value.map((item) => `${"  ".repeat(indent + 1)}${toPythonLiteral(item, indent + 1)}`).join(",\n");
    return `[
${entries},
${padding}]`;
  }
  if (typeof value === "object") {
    const entries = Object.entries(value);
    if (!entries.length) return "{}";
    const lines = entries.map(
      ([key, entry]) => `${"  ".repeat(indent + 1)}'${key.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}': ${toPythonLiteral(entry, indent + 1)}`
    );
    return `{
${lines.join(",\n")},
${padding}}`;
  }
  return "None";
}
function ApiDocsExplorer(props) {
  const { title, version, description, operations, tagOrder, servers, docsUrl, jsonSpecUrl, markdownSpecUrl } = props;
  const methodOptions = useMemo(
    () => Array.from(new Set(operations.map((operation) => operation.method))).sort((a, b) => a.localeCompare(b)),
    [operations]
  );
  const operationsById = useMemo(() => {
    const map = /* @__PURE__ */ new Map();
    for (const operation of operations) {
      map.set(operation.id, operation);
    }
    return map;
  }, [operations]);
  const [searchTerm, setSearchTerm] = useState("");
  const [methodFilter, setMethodFilter] = useState(methodOptions);
  const [selectedId, setSelectedId] = useState(operations[0]?.id ?? "");
  const [isNavOpen, setIsNavOpen] = useState(false);
  const [isTesterOpen, setIsTesterOpen] = useState(false);
  const [expanded, setExpanded] = useState({});
  const [visibleCounts, setVisibleCounts] = useState({});
  const [baseUrl, setBaseUrl] = useState(servers[0]?.url ?? "");
  const [apiKey, setApiKey] = useState("");
  useEffect(() => {
    setMethodFilter(methodOptions);
  }, [methodOptions]);
  useEffect(() => {
    if (servers.length === 0) return;
    setBaseUrl((prev) => {
      if (!prev) return servers[0].url;
      return prev;
    });
  }, [servers]);
  const filteredOperations = useMemo(() => {
    const lowered = searchTerm.trim().toLowerCase();
    return operations.filter((operation) => {
      if (!methodFilter.includes(operation.method)) return false;
      if (!lowered) return true;
      return operation.path.toLowerCase().includes(lowered) || operation.summary && operation.summary.toLowerCase().includes(lowered) || operation.description && operation.description.toLowerCase().includes(lowered);
    });
  }, [operations, methodFilter, searchTerm]);
  const categories = useMemo(() => {
    const grouped = /* @__PURE__ */ new Map();
    for (const operation of filteredOperations) {
      const list = grouped.get(operation.tag) ?? [];
      list.push(operation);
      grouped.set(operation.tag, list);
    }
    const ordered = [];
    for (const tag of tagOrder) {
      const list = grouped.get(tag);
      if (list && list.length) {
        ordered.push({ tag, operations: list });
        grouped.delete(tag);
      }
    }
    const remaining = Array.from(grouped.entries()).sort(([a], [b]) => a.localeCompare(b));
    for (const [tag, ops] of remaining) {
      ordered.push({ tag, operations: ops });
    }
    return ordered;
  }, [filteredOperations, tagOrder]);
  useEffect(() => {
    setExpanded((prev) => {
      const next = {};
      for (const category of categories) {
        next[category.tag] = prev[category.tag] ?? true;
      }
      return next;
    });
    setVisibleCounts((prev) => {
      const next = {};
      for (const category of categories) {
        const total = category.operations.length;
        const previous = prev[category.tag] ?? CATEGORY_PAGE_SIZE;
        next[category.tag] = Math.min(total, previous);
      }
      return next;
    });
  }, [categories]);
  useEffect(() => {
    if (!selectedId && filteredOperations.length) {
      setSelectedId(filteredOperations[0].id);
      return;
    }
    if (selectedId && filteredOperations.some((operation) => operation.id === selectedId)) return;
    if (filteredOperations.length) {
      setSelectedId(filteredOperations[0].id);
    }
  }, [filteredOperations, selectedId]);
  const selectedOperation = (selectedId ? operationsById.get(selectedId) : void 0) ?? filteredOperations[0] ?? operations[0] ?? null;
  const shouldOpenTesterOverlay = () => {
    if (typeof window === "undefined") return false;
    return window.innerWidth < 1280;
  };
  const handleSelectOperation = (operationId) => {
    setSelectedId(operationId);
    const targetCategory = categories.find(
      (category) => category.operations.some((operation) => operation.id === operationId)
    );
    if (targetCategory) {
      const index = targetCategory.operations.findIndex((operation) => operation.id === operationId);
      if (index >= 0) {
        setVisibleCounts((prev) => {
          const currentVisible = prev[targetCategory.tag] ?? CATEGORY_PAGE_SIZE;
          if (index < currentVisible) return prev;
          return { ...prev, [targetCategory.tag]: index + 1 };
        });
      }
    }
    requestAnimationFrame(() => {
      const element = document.getElementById(`operation-${operationId}`);
      if (element) element.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
    });
    if (shouldOpenTesterOverlay()) setIsTesterOpen(true);
    setIsNavOpen(false);
  };
  return /* @__PURE__ */ jsxs("div", { className: "min-h-screen bg-background text-foreground", children: [
    /* @__PURE__ */ jsx("header", { className: "border-b bg-card", children: /* @__PURE__ */ jsxs("div", { className: "mx-auto flex w-full max-w-screen-2xl flex-col gap-4 px-6 py-6 lg:flex-row lg:items-center lg:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsxs(
          "button",
          {
            type: "button",
            className: "inline-flex h-10 w-10 items-center justify-center rounded-md border border-border text-sm font-medium text-muted-foreground hover:border-foreground hover:text-foreground lg:hidden",
            onClick: () => setIsNavOpen(true),
            children: [
              /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Open navigation" }),
              "\u2630"
            ]
          }
        ),
        /* @__PURE__ */ jsxs(Link, { href: "/", className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsx(Image, { src: "/open-mercato.svg", alt: "Open Mercato", width: 36, height: 36 }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("div", { className: "text-base font-semibold leading-tight", children: title }),
            /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
              "Version ",
              version
            ] })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-end gap-2", children: [
        /* @__PURE__ */ jsxs("nav", { className: "hidden items-center gap-2 text-xs text-muted-foreground sm:flex", children: [
          /* @__PURE__ */ jsx(Link, { href: "/", className: "hover:text-foreground hover:underline", children: "Home" }),
          /* @__PURE__ */ jsx("span", { children: "/" }),
          /* @__PURE__ */ jsx("span", { children: "Docs" }),
          /* @__PURE__ */ jsx("span", { children: "/" }),
          /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: "API Explorer" })
        ] }),
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            className: "inline-flex h-10 items-center justify-center rounded-md border border-border px-3 text-sm font-medium text-muted-foreground hover:border-foreground hover:text-foreground xl:hidden",
            onClick: () => setIsTesterOpen(true),
            children: "Try Endpoint"
          }
        ),
        /* @__PURE__ */ jsx(
          Link,
          {
            href: jsonSpecUrl,
            target: "_blank",
            rel: "noreferrer",
            className: "inline-flex h-10 items-center justify-center rounded-md border border-border px-3 text-sm font-medium text-muted-foreground hover:border-foreground hover:text-foreground",
            children: "OpenAPI JSON"
          }
        ),
        /* @__PURE__ */ jsx(
          Link,
          {
            href: markdownSpecUrl,
            target: "_blank",
            rel: "noreferrer",
            className: "inline-flex h-10 items-center justify-center rounded-md border border-border px-3 text-sm font-medium text-muted-foreground hover:border-foreground hover:text-foreground",
            children: "Markdown Docs"
          }
        ),
        /* @__PURE__ */ jsx(
          Link,
          {
            href: docsUrl,
            target: "_blank",
            rel: "noreferrer",
            className: "hidden rounded-md border border-primary/30 px-4 py-2 text-sm font-medium text-primary hover:bg-primary/10 sm:inline-flex",
            children: "View full docs"
          }
        )
      ] })
    ] }) }),
    /* @__PURE__ */ jsxs("main", { className: "mx-auto flex w-full max-w-screen-2xl flex-1 flex-col px-6 py-8 lg:flex-row lg:gap-6", children: [
      /* @__PURE__ */ jsx("aside", { className: "hidden w-64 shrink-0 lg:block", children: /* @__PURE__ */ jsxs("div", { className: "sticky top-20 max-h-[calc(100vh-6rem)] overflow-y-auto rounded-lg border bg-card p-4", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-sm font-semibold uppercase tracking-wide text-muted-foreground", children: "API Categories" }),
        /* @__PURE__ */ jsx("nav", { className: "mt-4 space-y-4 text-sm", children: categories.map((category) => {
          const isExpanded = expanded[category.tag] ?? true;
          return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs(
              "button",
              {
                type: "button",
                className: "flex w-full items-center justify-between rounded-md bg-muted px-3 py-2 text-left font-medium text-foreground hover:bg-muted/50",
                onClick: () => setExpanded((prev) => ({
                  ...prev,
                  [category.tag]: !isExpanded
                })),
                children: [
                  /* @__PURE__ */ jsx("span", { children: category.tag }),
                  /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: isExpanded ? "\u2212" : "+" })
                ]
              }
            ),
            isExpanded ? /* @__PURE__ */ jsx("ul", { className: "space-y-1 pl-2", children: category.operations.map((operation) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
              "button",
              {
                type: "button",
                className: `flex w-full items-center gap-2 rounded-md px-3 py-2 text-left transition ${selectedOperation?.id === operation.id ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"}`,
                onClick: () => handleSelectOperation(operation.id),
                children: [
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: `inline-flex min-w-[3rem] justify-center rounded border px-2 py-0.5 text-overline font-semibold uppercase ${METHOD_STYLES[operation.method] ?? "border border-border bg-muted text-foreground"}`,
                      children: operation.method
                    }
                  ),
                  /* @__PURE__ */ jsx("span", { className: "truncate text-xs", children: operation.path })
                ]
              }
            ) }, operation.id)) }) : null
          ] }, category.tag);
        }) })
      ] }) }),
      /* @__PURE__ */ jsxs("section", { className: "flex-1 space-y-6", children: [
        /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-card p-5 shadow-sm", children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: "OpenAPI Explorer" }),
              description ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: description }) : null
            ] }),
            /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: servers[0]?.url ? /* @__PURE__ */ jsxs("span", { children: [
              "Default server: ",
              servers[0].url
            ] }) : /* @__PURE__ */ jsx("span", { children: "Server URL not configured." }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between", children: [
            /* @__PURE__ */ jsx("div", { className: "flex flex-1 items-center gap-3", children: /* @__PURE__ */ jsx(
              Input,
              {
                type: "search",
                value: searchTerm,
                onChange: (event) => setSearchTerm(event.target.value),
                placeholder: "Search endpoints by path or summary",
                className: "flex-1"
              }
            ) }),
            /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2 text-xs", children: methodOptions.map((method) => {
              const isActive = methodFilter.includes(method);
              return /* @__PURE__ */ jsx(
                "button",
                {
                  type: "button",
                  className: `rounded-md border px-3 py-1 font-semibold uppercase transition ${isActive ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:border-foreground hover:text-foreground"}`,
                  onClick: () => {
                    setMethodFilter((prev) => {
                      if (prev.includes(method)) {
                        const next = prev.filter((entry) => entry !== method);
                        return next.length ? next : prev;
                      }
                      return [...prev, method];
                    });
                  },
                  children: method
                },
                method
              );
            }) })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-8", children: [
          categories.map((category) => {
            const totalCount = category.operations.length;
            const visibleCount = Math.min(
              totalCount,
              visibleCounts[category.tag] ?? CATEGORY_PAGE_SIZE
            );
            const visibleOperations = category.operations.slice(0, visibleCount);
            const hiddenCount = totalCount - visibleCount;
            return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
                /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: category.tag }),
                /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
                  "Showing ",
                  visibleCount,
                  " of ",
                  totalCount,
                  " endpoints"
                ] })
              ] }),
              /* @__PURE__ */ jsx("div", { className: "space-y-6", children: visibleOperations.map((operation) => {
                const methodClass = METHOD_STYLES[operation.method] ?? "border border-border bg-muted text-foreground";
                const operationId = `operation-${operation.id}`;
                const contentVariant = pickContentVariant(operation.operation?.requestBody?.content);
                const contentExample = contentVariant?.entry?.example ?? contentVariant?.entry?.examples?.default?.value ?? buildExampleFromSchema(contentVariant?.entry?.schema);
                const requestSnippet = contentVariant && contentExample ? stringifyExample(contentVariant.mediaType, contentExample) : void 0;
                return /* @__PURE__ */ jsxs(
                  "article",
                  {
                    id: operationId,
                    className: `rounded-lg border bg-card shadow-sm transition ${selectedOperation?.id === operation.id ? "ring-2 ring-primary/40" : ""}`,
                    children: [
                      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 border-b bg-muted/50 px-5 py-4 md:flex-row md:items-center md:justify-between", children: [
                        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                          /* @__PURE__ */ jsx("span", { className: `rounded px-3 py-1 text-xs font-semibold uppercase ${methodClass}`, children: operation.method }),
                          /* @__PURE__ */ jsx("code", { className: "text-sm text-foreground", children: operation.path })
                        ] }),
                        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-overline text-muted-foreground", children: [
                          operation.operation?.["x-require-auth"] ? /* @__PURE__ */ jsx("span", { className: "rounded bg-status-warning-bg px-2 py-0.5 text-status-warning-text", children: "Auth required" }) : null,
                          Array.isArray(operation.operation?.["x-require-features"]) ? operation.operation["x-require-features"].map((feature) => /* @__PURE__ */ jsx("span", { className: "rounded bg-status-info-bg px-2 py-0.5 text-status-info-text", children: feature }, feature)) : null
                        ] })
                      ] }),
                      /* @__PURE__ */ jsxs("div", { className: "space-y-5 p-5", children: [
                        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                          operation.summary ? /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold", children: operation.summary }) : null,
                          operation.description ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground whitespace-pre-line", children: operation.description }) : null
                        ] }),
                        Array.isArray(operation.operation?.parameters) && operation.operation.parameters.length ? /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
                          /* @__PURE__ */ jsx("h4", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: "Parameters" }),
                          /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-lg border", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full divide-y divide-border text-left text-xs", children: [
                            /* @__PURE__ */ jsx("thead", { className: "bg-muted/50 text-overline uppercase tracking-wide text-muted-foreground", children: /* @__PURE__ */ jsxs("tr", { children: [
                              /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: "Name" }),
                              /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: "In" }),
                              /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: "Required" }),
                              /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: "Schema" }),
                              /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: "Description" })
                            ] }) }),
                            /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-border text-xs", children: operation.operation.parameters.map((parameter) => /* @__PURE__ */ jsxs("tr", { children: [
                              /* @__PURE__ */ jsx("td", { className: "px-3 py-2 font-medium text-foreground", children: parameter.name }),
                              /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-muted-foreground", children: parameter.in }),
                              /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-muted-foreground", children: parameter.required ? "Yes" : "No" }),
                              /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-muted-foreground", children: parameter.schema?.type ?? "any" }),
                              /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-muted-foreground", children: parameter.description ?? "\u2014" })
                            ] }, `${parameter.in}-${parameter.name}`)) })
                          ] }) })
                        ] }) : null,
                        contentVariant ? /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
                          /* @__PURE__ */ jsxs("h4", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: [
                            "Request body (",
                            contentVariant.mediaType,
                            ")"
                          ] }),
                          requestSnippet ? /* @__PURE__ */ jsx("pre", { className: "max-h-80 overflow-auto rounded-lg bg-muted px-4 py-3 text-xs leading-relaxed", children: requestSnippet }) : /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "No example available for this content type." })
                        ] }) : null,
                        operation.operation?.responses ? /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
                          /* @__PURE__ */ jsx("h4", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: "Responses" }),
                          /* @__PURE__ */ jsx("div", { className: "space-y-3", children: Object.entries(operation.operation.responses).map(([status, response]) => {
                            if (response?.["x-autoGenerated"]) return null;
                            const responseVariant = pickContentVariant(response?.content);
                            const responseExample = responseVariant?.entry?.example ?? responseVariant?.entry?.examples?.default?.value ?? buildExampleFromSchema(responseVariant?.entry?.schema);
                            const responseSnippet = responseVariant && responseExample ? stringifyExample(responseVariant.mediaType, responseExample) : void 0;
                            return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border", children: [
                              /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b bg-muted/50 px-4 py-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: [
                                /* @__PURE__ */ jsx("span", { children: status }),
                                /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: response?.description ?? "Response" })
                              ] }),
                              responseVariant ? /* @__PURE__ */ jsxs("div", { className: "border-b bg-muted/50 px-4 py-2 text-overline text-muted-foreground", children: [
                                "Content-Type: ",
                                responseVariant.mediaType
                              ] }) : null,
                              responseSnippet ? /* @__PURE__ */ jsx("pre", { className: "max-h-80 overflow-auto bg-muted px-4 py-3 text-xs leading-relaxed", children: responseSnippet }) : /* @__PURE__ */ jsx("p", { className: "px-4 py-3 text-xs text-muted-foreground", children: responseVariant ? "No example available for this content type." : "No response body." })
                            ] }, status);
                          }) })
                        ] }) : null,
                        Array.isArray(operation.operation?.["x-codeSamples"]) && operation.operation["x-codeSamples"].length ? /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
                          /* @__PURE__ */ jsx("h4", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: "Example" }),
                          /* @__PURE__ */ jsx("pre", { className: "overflow-auto rounded-lg bg-muted px-4 py-3 text-xs leading-relaxed", children: operation.operation["x-codeSamples"][0].source })
                        ] }) : null,
                        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-3", children: [
                          /* @__PURE__ */ jsx(
                            "button",
                            {
                              type: "button",
                              className: "inline-flex items-center rounded-md border border-primary px-4 py-2 text-sm font-semibold text-primary hover:bg-primary/10",
                              onClick: () => {
                                setSelectedId(operation.id);
                                if (shouldOpenTesterOverlay()) setIsTesterOpen(true);
                              },
                              children: "Test this endpoint"
                            }
                          ),
                          /* @__PURE__ */ jsx(
                            "button",
                            {
                              type: "button",
                              className: "inline-flex items-center rounded-md border border-border px-4 py-2 text-sm text-muted-foreground hover:border-foreground hover:text-foreground",
                              onClick: () => handleSelectOperation(operation.id),
                              children: "Jump to tester"
                            }
                          )
                        ] })
                      ] })
                    ]
                  },
                  operation.id
                );
              }) }),
              hiddenCount > 0 ? /* @__PURE__ */ jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxs(
                "button",
                {
                  type: "button",
                  className: "inline-flex items-center rounded-md border border-border px-4 py-2 text-sm font-medium text-muted-foreground hover:border-foreground hover:text-foreground",
                  onClick: () => setVisibleCounts((prev) => ({
                    ...prev,
                    [category.tag]: Math.min(
                      totalCount,
                      (prev[category.tag] ?? CATEGORY_PAGE_SIZE) + CATEGORY_PAGE_SIZE
                    )
                  })),
                  children: [
                    "Show ",
                    Math.min(CATEGORY_PAGE_SIZE, hiddenCount),
                    " more endpoints"
                  ]
                }
              ) }) : null
            ] }, category.tag);
          }),
          !categories.length ? /* @__PURE__ */ jsx(
            EmptyState,
            {
              icon: /* @__PURE__ */ jsx(SearchX, { className: "h-8 w-8", "aria-hidden": "true" }),
              title: "No endpoints match your filters.",
              description: "Try adjusting the method filters or clearing the search query."
            }
          ) : null
        ] })
      ] }),
      /* @__PURE__ */ jsx("aside", { className: "hidden w-96 shrink-0 xl:block", children: /* @__PURE__ */ jsx("div", { className: "sticky top-20 max-h-[calc(100vh-6rem)] overflow-y-auto", children: /* @__PURE__ */ jsx(
        TesterPanel,
        {
          operation: selectedOperation,
          baseUrl,
          setBaseUrl,
          baseUrlOptions: servers,
          apiKey,
          setApiKey
        },
        selectedOperation?.id ?? "tester"
      ) }) })
    ] }),
    /* @__PURE__ */ jsx("footer", { className: "border-t bg-card", children: /* @__PURE__ */ jsxs("div", { className: "mx-auto flex w-full max-w-screen-2xl flex-col gap-4 px-6 py-6 md:flex-row md:items-center md:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "text-sm text-muted-foreground", children: [
        "\xA9 ",
        (/* @__PURE__ */ new Date()).getFullYear(),
        " Open Mercato. All rights reserved."
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-4 text-sm text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Link, { href: docsUrl, target: "_blank", rel: "noreferrer", className: "hover:text-foreground hover:underline", children: "Documentation" }),
        /* @__PURE__ */ jsx(
          Link,
          {
            href: "https://openmercato.com/privacy",
            target: "_blank",
            rel: "noreferrer",
            className: "hover:text-foreground hover:underline",
            children: "Privacy"
          }
        ),
        /* @__PURE__ */ jsx(
          Link,
          {
            href: "https://openmercato.com/terms",
            target: "_blank",
            rel: "noreferrer",
            className: "hover:text-foreground hover:underline",
            children: "Terms"
          }
        )
      ] })
    ] }) }),
    isNavOpen ? /* @__PURE__ */ jsx(MobileOverlay, { title: "API categories", onClose: () => setIsNavOpen(false), children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-sm font-semibold uppercase tracking-wide text-muted-foreground", children: "API Categories" }),
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            className: "text-sm text-muted-foreground hover:text-foreground",
            onClick: () => setIsNavOpen(false),
            children: "Close"
          }
        )
      ] }),
      /* @__PURE__ */ jsx("div", { className: "max-h-[70vh] space-y-4 overflow-y-auto", children: categories.map((category) => /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("div", { className: "font-semibold text-foreground", children: category.tag }),
        /* @__PURE__ */ jsx("ul", { className: "space-y-2", children: category.operations.map((operation) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
          "button",
          {
            type: "button",
            className: `flex w-full items-center gap-2 rounded-md border px-3 py-2 text-left text-sm ${selectedOperation?.id === operation.id ? "border-accent-indigo text-foreground" : "border-border text-muted-foreground"}`,
            onClick: () => handleSelectOperation(operation.id),
            children: [
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: `inline-flex min-w-[3rem] justify-center rounded border px-2 py-0.5 text-overline font-semibold uppercase ${METHOD_STYLES[operation.method] ?? "border border-border bg-muted text-foreground"}`,
                  children: operation.method
                }
              ),
              /* @__PURE__ */ jsx("span", { className: "truncate", children: operation.path })
            ]
          }
        ) }, `mobile-${operation.id}`)) })
      ] }, `mobile-${category.tag}`)) })
    ] }) }) : null,
    isTesterOpen ? /* @__PURE__ */ jsx(MobileOverlay, { title: "API tester", onClose: () => setIsTesterOpen(false), children: /* @__PURE__ */ jsx(
      TesterPanel,
      {
        operation: selectedOperation,
        baseUrl,
        setBaseUrl,
        baseUrlOptions: servers,
        apiKey,
        setApiKey
      },
      `mobile-${selectedOperation?.id ?? "tester"}`
    ) }) : null
  ] });
}
function CodeSnippetTabs(props) {
  const { snippets } = props;
  const [activeId, setActiveId] = useState(snippets[0]?.id ?? "");
  const [copied, setCopied] = useState(false);
  useEffect(() => {
    const first = snippets[0]?.id ?? "";
    setActiveId((current) => snippets.some((snippet) => snippet.id === current) ? current : first);
  }, [snippets]);
  useEffect(() => {
    setCopied(false);
  }, [activeId]);
  useEffect(() => {
    if (!copied) return;
    const timeout = window.setTimeout(() => setCopied(false), 2e3);
    return () => window.clearTimeout(timeout);
  }, [copied]);
  if (!snippets.length) {
    return null;
  }
  const activeSnippet = snippets.find((snippet) => snippet.id === activeId) ?? snippets[0];
  const handleCopy = async () => {
    if (!activeSnippet) return;
    if (typeof navigator === "undefined" || !navigator.clipboard) return;
    try {
      await navigator.clipboard.writeText(activeSnippet.code);
      setCopied(true);
    } catch {
      setCopied(false);
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
      /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: snippets.map((snippet) => /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          className: `rounded-md border px-3 py-1 text-xs font-semibold ${snippet.id === activeSnippet.id ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:border-foreground hover:text-foreground"}`,
          onClick: () => setActiveId(snippet.id),
          children: snippet.label
        },
        snippet.id
      )) }),
      /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          className: "inline-flex items-center rounded-md border border-border px-3 py-1 text-xs font-semibold text-muted-foreground hover:border-foreground hover:text-foreground",
          onClick: handleCopy,
          children: copied ? "Copied" : "Copy"
        }
      )
    ] }),
    /* @__PURE__ */ jsx("pre", { className: "max-h-80 overflow-auto rounded-md bg-muted px-3 py-2 text-xs leading-relaxed", children: activeSnippet.code })
  ] });
}
function MobileOverlay(props) {
  const { title, children, onClose } = props;
  return /* @__PURE__ */ jsxs("div", { className: "fixed inset-0 z-modal flex flex-col bg-background/95 backdrop-blur", children: [
    /* @__PURE__ */ jsx("div", { className: "border-b bg-card px-6 py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-base font-semibold text-foreground", children: title }),
      /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          className: "rounded-md border border-border px-3 py-1 text-sm text-muted-foreground hover:border-foreground hover:text-foreground",
          onClick: onClose,
          children: "Close"
        }
      )
    ] }) }),
    /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto px-6 py-4", children })
  ] });
}
function TesterPanel(props) {
  const { operation, baseUrl, setBaseUrl, baseUrlOptions, apiKey, setApiKey } = props;
  const [pathValues, setPathValues] = useState({});
  const [queryValues, setQueryValues] = useState({});
  const [bodyContent, setBodyContent] = useState("");
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const parameters = useMemo(
    () => operation && Array.isArray(operation.operation?.parameters) ? operation.operation.parameters : [],
    [operation]
  );
  const pathParams = useMemo(
    () => parameters.filter((parameter) => parameter.in === "path"),
    [parameters]
  );
  const queryParams = useMemo(
    () => parameters.filter((parameter) => parameter.in === "query"),
    [parameters]
  );
  const requestVariant = useMemo(
    () => operation ? pickContentVariant(operation.operation?.requestBody?.content) : null,
    [operation]
  );
  const mergedBaseUrls = useMemo(() => {
    if (!baseUrl) return baseUrlOptions;
    if (baseUrlOptions.some((server) => server.url === baseUrl)) return baseUrlOptions;
    return [...baseUrlOptions, { url: baseUrl }];
  }, [baseUrlOptions, baseUrl]);
  const requestPreview = useMemo(() => {
    if (!operation) return null;
    const method = operation.method.toUpperCase();
    const rawBase = baseUrl.trim();
    const normalizedBase = rawBase || PLACEHOLDER_BASE_URL;
    const usesPlaceholderBase = !rawBase;
    const baseWithSlash = normalizedBase.endsWith("/") ? normalizedBase : `${normalizedBase}/`;
    const resolvedPath = applyPathParams(operation.path, pathValues);
    const relativePath = resolvedPath.replace(/^\//, "");
    let url;
    try {
      url = new URL(relativePath, baseWithSlash);
    } catch {
      return {
        method,
        url: "",
        headers: [],
        mediaType: requestVariant?.mediaType,
        usesPlaceholderBase,
        baseError: "Base URL must be absolute (include protocol, e.g. https://api.example.com)."
      };
    }
    for (const [key, value] of Object.entries(queryValues)) {
      if (!value) continue;
      url.searchParams.append(key, value);
    }
    const headers = [["Accept", "application/json"]];
    const trimmedKey = apiKey.trim();
    if (trimmedKey) {
      headers.push(["Authorization", `ApiKey ${trimmedKey}`]);
      headers.push(["X-Api-Key", trimmedKey]);
    }
    let body;
    let jsonBody;
    let bodyParseError;
    if (requestVariant && method !== "GET" && method !== "HEAD") {
      headers.push(["Content-Type", requestVariant.mediaType]);
      if (requestVariant.mediaType === "application/json") {
        if (bodyContent.trim()) {
          try {
            jsonBody = JSON.parse(bodyContent);
            body = JSON.stringify(jsonBody);
          } catch {
            bodyParseError = "Request body must be valid JSON.";
          }
        }
      } else {
        if (bodyContent) {
          body = bodyContent;
        }
      }
    }
    const missingPathParam = pathParams.find((parameter) => parameter.required && !pathValues[parameter.name]);
    return {
      method,
      url: url.toString(),
      headers,
      body,
      jsonBody,
      mediaType: requestVariant?.mediaType,
      usesPlaceholderBase,
      missingPathParam: missingPathParam?.name,
      bodyParseError
    };
  }, [operation, baseUrl, pathValues, queryValues, apiKey, requestVariant, bodyContent, pathParams]);
  const codeSnippets = useMemo(() => {
    if (!requestPreview || requestPreview.baseError) return [];
    const snippets = [];
    const { method, url, headers, body, jsonBody, mediaType } = requestPreview;
    if (url) {
      const curlParts = [`curl -X ${method} '${escapeSingleQuotes(url)}'`];
      for (const [key, value] of headers) {
        curlParts.push(`  -H '${escapeSingleQuotes(`${key}: ${value}`)}'`);
      }
      if (body) {
        curlParts.push(`  --data '${escapeSingleQuotes(body)}'`);
      }
      snippets.push({
        id: "curl",
        label: "cURL",
        language: "bash",
        code: curlParts.join(" \\\n")
      });
      const headerEntries = headers.length === 0 ? "" : headers.map(([key, value]) => `  '${key}': '${escapeSingleQuotesForJs(value)}',`).join("\n");
      const tsLines = [
        `const url = '${escapeSingleQuotesForJs(url)}';`,
        headerEntries ? `const headers = {
${headerEntries}
};` : "const headers = {};"
      ];
      if (mediaType === "application/json" && jsonBody !== void 0) {
        const payloadLiteral = JSON.stringify(jsonBody, null, 2);
        tsLines.push("", `const payload = ${payloadLiteral};`);
        tsLines.push(
          "",
          "const response = await fetch(url, {",
          `  method: '${method}',`,
          "  headers,",
          "  body: JSON.stringify(payload),",
          "});"
        );
      } else if (body) {
        tsLines.push("", `const body = \`${escapeBackticks(body)}\`;`);
        tsLines.push(
          "",
          "const response = await fetch(url, {",
          `  method: '${method}',`,
          "  headers,",
          "  body,",
          "});"
        );
      } else {
        tsLines.push(
          "",
          "const response = await fetch(url, {",
          `  method: '${method}',`,
          "  headers,",
          "});"
        );
      }
      tsLines.push("const data = await response.json();", "console.log(data);");
      snippets.push({
        id: "typescript",
        label: "TypeScript",
        language: "ts",
        code: tsLines.join("\n")
      });
      const pythonLines = ["import requests", "", `url = '${escapeSingleQuotesForJs(url)}'`];
      if (headers.length) {
        const pythonHeaders = headers.map(([key, value]) => `    '${key}': '${escapeSingleQuotesForJs(value)}',`).join("\n");
        pythonLines.push("headers = {", pythonHeaders, "}");
      } else {
        pythonLines.push("headers = {}");
      }
      if (mediaType === "application/json" && jsonBody !== void 0) {
        const pythonPayload = toPythonLiteral(jsonBody);
        pythonLines.push("", `payload = ${pythonPayload}`);
        pythonLines.push(
          `response = requests.request('${method}', url, headers=headers, json=payload)`
        );
      } else if (body) {
        pythonLines.push("", `data = ${toPythonLiteral(body)}`);
        pythonLines.push(`response = requests.request('${method}', url, headers=headers, data=data)`);
      } else {
        pythonLines.push("", `response = requests.request('${method}', url, headers=headers)`);
      }
      pythonLines.push("print(response.status_code)", "print(response.text)");
      snippets.push({
        id: "python",
        label: "Python",
        language: "python",
        code: pythonLines.join("\n")
      });
    }
    return snippets;
  }, [requestPreview]);
  useEffect(() => {
    const nextPath = {};
    for (const parameter of pathParams) {
      nextPath[parameter.name] = "";
    }
    const nextQuery = {};
    for (const parameter of queryParams) {
      nextQuery[parameter.name] = "";
    }
    setPathValues(nextPath);
    setQueryValues(nextQuery);
    if (requestVariant) {
      const example = requestVariant.entry?.example ?? requestVariant.entry?.examples?.default?.value ?? buildExampleFromSchema(requestVariant.entry?.schema);
      setBodyContent(example ? stringifyExample(requestVariant.mediaType, example) : "");
    } else {
      setBodyContent("");
    }
    setResponse(null);
    setError(null);
  }, [operation?.id, pathParams, queryParams, requestVariant]);
  if (!operation) {
    return /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-card p-5 text-sm text-muted-foreground", children: "Select an endpoint to start testing requests." });
  }
  const handleSubmit = async () => {
    if (!operation) return;
    if (!baseUrl.trim()) {
      setError("Please provide a base URL for the request.");
      return;
    }
    if (requestPreview?.baseError) {
      setError(requestPreview.baseError);
      return;
    }
    if (requestPreview?.missingPathParam) {
      setError(`Path parameter "${requestPreview.missingPathParam}" is required.`);
      return;
    }
    if (requestPreview?.bodyParseError) {
      setError(requestPreview.bodyParseError);
      return;
    }
    if (!requestPreview) {
      setError("Unable to prepare the request. Check your input and try again.");
      return;
    }
    setIsLoading(true);
    setError(null);
    setResponse(null);
    try {
      const started = performance.now();
      const res = await fetch(requestPreview.url, {
        method: requestPreview.method,
        headers: Object.fromEntries(requestPreview.headers),
        body: requestPreview.body
      });
      const duration = performance.now() - started;
      const text = await res.text();
      let parsed;
      try {
        parsed = JSON.parse(text);
      } catch {
        parsed = void 0;
      }
      setResponse({
        status: res.status,
        ok: res.ok,
        durationMs: Math.round(duration),
        body: text,
        parsed
      });
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Request failed. Check your network connection.");
    } finally {
      setIsLoading(false);
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 rounded-lg border bg-card p-5 shadow-sm", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: "Interactive tester" }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Provide the endpoint parameters and your API key to execute a live request." })
      ] }),
      /* @__PURE__ */ jsx(
        "span",
        {
          className: `inline-flex min-w-[3rem] justify-center rounded border px-2 py-0.5 text-overline font-semibold uppercase ${METHOD_STYLES[operation.method] ?? "border border-border bg-muted text-foreground"}`,
          children: operation.method
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2 text-xs", children: [
      /* @__PURE__ */ jsx("div", { className: "font-semibold text-foreground", children: "Endpoint" }),
      /* @__PURE__ */ jsx("code", { className: "rounded-md bg-muted px-3 py-2 text-xs text-primary", children: operation.path })
    ] }),
    /* @__PURE__ */ jsxs("label", { className: "space-y-2 text-sm", children: [
      /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: "Base URL" }),
      /* @__PURE__ */ jsxs(Select, { value: baseUrl, onValueChange: (value) => setBaseUrl(value), children: [
        /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
        /* @__PURE__ */ jsx(SelectContent, { children: mergedBaseUrls.map((server) => /* @__PURE__ */ jsxs(SelectItem, { value: server.url, children: [
          server.url,
          " ",
          server.description ? `\u2014 ${server.description}` : ""
        ] }, server.url)) })
      ] }),
      !baseUrl.trim() && requestPreview?.usesPlaceholderBase ? /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
        "Examples default to ",
        PLACEHOLDER_BASE_URL,
        ". Update the base URL to match your environment."
      ] }) : null,
      requestPreview?.baseError ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: requestPreview.baseError }) : null
    ] }),
    /* @__PURE__ */ jsxs("label", { className: "space-y-2 text-sm", children: [
      /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: "API key" }),
      /* @__PURE__ */ jsx(
        Input,
        {
          type: "text",
          value: apiKey,
          onChange: (event) => setApiKey(event.target.value),
          placeholder: "Paste your API key secret (omk_\u2026)"
        }
      )
    ] }),
    pathParams.length ? /* @__PURE__ */ jsxs("section", { className: "space-y-2 text-sm", children: [
      /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground", children: "Path parameters" }),
      /* @__PURE__ */ jsx("div", { className: "space-y-3", children: pathParams.map((parameter) => /* @__PURE__ */ jsxs("label", { className: "space-y-1", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs text-muted-foreground", children: [
          /* @__PURE__ */ jsx("span", { children: parameter.name }),
          parameter.required ? /* @__PURE__ */ jsx("span", { className: "text-status-warning-text", children: "required" }) : null
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            type: "text",
            value: pathValues[parameter.name] ?? "",
            onChange: (event) => setPathValues((prev) => ({
              ...prev,
              [parameter.name]: event.target.value
            })),
            placeholder: parameter.description ?? ""
          }
        )
      ] }, parameter.name)) })
    ] }) : null,
    queryParams.length ? /* @__PURE__ */ jsxs("section", { className: "space-y-2 text-sm", children: [
      /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground", children: "Query parameters" }),
      /* @__PURE__ */ jsx("div", { className: "space-y-3", children: queryParams.map((parameter) => /* @__PURE__ */ jsxs("label", { className: "space-y-1", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs text-muted-foreground", children: [
          /* @__PURE__ */ jsx("span", { children: parameter.name }),
          parameter.required ? /* @__PURE__ */ jsx("span", { className: "text-status-warning-text", children: "required" }) : null
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            type: "text",
            value: queryValues[parameter.name] ?? "",
            onChange: (event) => setQueryValues((prev) => ({
              ...prev,
              [parameter.name]: event.target.value
            })),
            placeholder: parameter.description ?? ""
          }
        )
      ] }, parameter.name)) })
    ] }) : null,
    requestVariant ? /* @__PURE__ */ jsxs("section", { className: "space-y-2 text-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: "Request body" }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: requestVariant.mediaType })
      ] }),
      /* @__PURE__ */ jsx(
        "textarea",
        {
          value: bodyContent,
          onChange: (event) => setBodyContent(event.target.value),
          rows: 8,
          className: "w-full rounded-md border border-border bg-background px-3 py-2 text-xs font-mono leading-relaxed focus-visible:border-ring focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/20",
          placeholder: "Provide request payload"
        }
      )
    ] }) : null,
    requestPreview?.bodyParseError ? /* @__PURE__ */ jsx("div", { className: "rounded border border-status-warning-border bg-status-warning-bg px-3 py-2 text-xs text-status-warning-text", children: requestPreview.bodyParseError }) : null,
    codeSnippets.length ? /* @__PURE__ */ jsxs("section", { className: "space-y-2 text-sm", children: [
      /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground", children: "Request examples" }),
      /* @__PURE__ */ jsx(CodeSnippetTabs, { snippets: codeSnippets })
    ] }) : null,
    /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        onClick: handleSubmit,
        disabled: isLoading,
        className: "inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary/90 disabled:cursor-not-allowed disabled:bg-primary/10",
        children: isLoading ? "Sending\u2026" : "Send request"
      }
    ),
    error ? /* @__PURE__ */ jsx("div", { className: "rounded border border-status-error-border bg-status-error-bg px-3 py-2 text-xs text-status-error-text", children: error }) : null,
    response ? /* @__PURE__ */ jsxs("section", { className: "space-y-2 text-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "font-medium text-foreground", children: [
          "Response \xB7 ",
          /* @__PURE__ */ jsx("span", { className: response.ok ? "text-status-success-text" : "text-destructive", children: response.status })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
          response.durationMs,
          " ms"
        ] })
      ] }),
      /* @__PURE__ */ jsx("pre", { className: "max-h-80 overflow-auto rounded-md bg-muted px-3 py-2 text-xs leading-relaxed", children: response.parsed ? formatJson(response.parsed) : response.body || "(empty response)" })
    ] }) : null
  ] });
}
export {
  ApiDocsExplorer as default
};
//# sourceMappingURL=Explorer.js.map
