"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "../../lib/utils";
import { ChevronRight, FileText, Folder, BookOpen, Palette, Puzzle, Search, X } from "lucide-react";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { Input } from "../ui/input";
import { THEME_REGISTRY } from "@nextsparkjs/registries/theme-registry";
function DocsSidebar({ sections }) {
  var _a, _b, _c, _d, _e;
  const pathname = usePathname();
  const t = useTranslations("docs");
  const getActiveElements = () => {
    const parts = pathname.split("/").filter(Boolean);
    if (parts[0] !== "docs" || parts.length < 3) {
      return { category: null, section: null, plugin: null };
    }
    const category = parts[1];
    if (category === "plugins" && parts.length >= 5) {
      return {
        category: "plugins",
        plugin: parts[2],
        section: parts[3]
      };
    } else if (parts.length >= 4) {
      return {
        category,
        section: parts[2],
        plugin: null
      };
    }
    return { category: null, section: null, plugin: null };
  };
  const activeElements = getActiveElements();
  const activeTheme = process.env.NEXT_PUBLIC_ACTIVE_THEME || "default";
  const themeAppConfig = (_a = THEME_REGISTRY[activeTheme]) == null ? void 0 : _a.appConfig;
  const themeConfig = ((_b = themeAppConfig == null ? void 0 : themeAppConfig.docs) == null ? void 0 : _b.theme) ?? { enabled: true, open: false, label: "Theme" };
  const pluginsConfig = ((_c = themeAppConfig == null ? void 0 : themeAppConfig.docs) == null ? void 0 : _c.plugins) ?? { enabled: true, open: false, label: "Plugins" };
  const coreConfig = ((_d = themeAppConfig == null ? void 0 : themeAppConfig.docs) == null ? void 0 : _d.core) ?? { enabled: true, open: false, label: "Core" };
  const [expandedSections, setExpandedSections] = useState(() => {
    return activeElements.section ? /* @__PURE__ */ new Set([activeElements.section]) : /* @__PURE__ */ new Set();
  });
  const [expandedCategories, setExpandedCategories] = useState(() => {
    const expanded = /* @__PURE__ */ new Set();
    if (activeElements.category) {
      expanded.add(activeElements.category);
    }
    if (!activeElements.category) {
      if (themeConfig.open) expanded.add("theme");
      if (pluginsConfig.open) expanded.add("plugins");
      if (coreConfig.open) expanded.add("core");
    }
    return expanded;
  });
  const [searchQuery, setSearchQuery] = useState("");
  const filterSections = (sections2) => {
    if (!searchQuery.trim()) return sections2;
    const query = searchQuery.toLowerCase().trim();
    return sections2.map((section) => {
      const sectionMatches = section.title.toLowerCase().includes(query);
      const matchingPages = section.pages.filter(
        (page) => page.title.toLowerCase().includes(query)
      );
      if (sectionMatches || matchingPages.length > 0) {
        return {
          ...section,
          pages: sectionMatches ? section.pages : matchingPages
        };
      }
      return null;
    }).filter((section) => section !== null);
  };
  const toggleSection = (slug) => {
    const newExpanded = new Set(expandedSections);
    if (newExpanded.has(slug)) {
      newExpanded.delete(slug);
    } else {
      newExpanded.add(slug);
    }
    setExpandedSections(newExpanded);
  };
  const toggleCategory = (category) => {
    const newExpanded = new Set(expandedCategories);
    if (newExpanded.has(category)) {
      newExpanded.delete(category);
    } else {
      newExpanded.add(category);
    }
    setExpandedCategories(newExpanded);
  };
  const handleKeyDown = (e, slug) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      toggleSection(slug);
    }
  };
  const handleCategoryKeyDown = (e, category) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      toggleCategory(category);
    }
  };
  const coreSections = filterSections(sections.filter((s) => s.source === "core"));
  const themeSections = filterSections(sections.filter((s) => s.source === "theme"));
  const pluginSections = filterSections(sections.filter((s) => s.source === "plugin"));
  const isProduction = process.env.NODE_ENV === "production";
  const showPluginsDocsInProd = ((_e = themeAppConfig == null ? void 0 : themeAppConfig.docs) == null ? void 0 : _e.showPluginsDocsInProd) ?? false;
  const finalPluginsEnabled = pluginsConfig.enabled && (!isProduction || showPluginsDocsInProd);
  const visibleCoreSections = coreConfig.enabled ? coreSections : [];
  const visibleThemeSections = themeConfig.enabled ? themeSections : [];
  const visiblePluginSections = finalPluginsEnabled ? pluginSections : [];
  const pluginsByName = visiblePluginSections.reduce((acc, section) => {
    if (!section.pluginName) return acc;
    if (!acc[section.pluginName]) {
      acc[section.pluginName] = [];
    }
    acc[section.pluginName].push(section);
    return acc;
  }, {});
  const [expandedPlugins, setExpandedPlugins] = useState(() => {
    return activeElements.plugin ? /* @__PURE__ */ new Set([activeElements.plugin]) : /* @__PURE__ */ new Set();
  });
  const togglePlugin = (pluginName) => {
    const newExpanded = new Set(expandedPlugins);
    if (newExpanded.has(pluginName)) {
      newExpanded.delete(pluginName);
    } else {
      newExpanded.add(pluginName);
    }
    setExpandedPlugins(newExpanded);
  };
  const handlePluginKeyDown = (e, pluginName) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      togglePlugin(pluginName);
    }
  };
  const renderSections = (categorySections, category, pluginName) => {
    return categorySections.map((section) => {
      const isExpanded = searchQuery.trim() ? true : expandedSections.has(section.slug);
      const isActive = activeElements.section === section.slug;
      return /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsxs(
          "button",
          {
            onClick: () => toggleSection(section.slug),
            onKeyDown: (e) => handleKeyDown(e, section.slug),
            className: cn(
              "flex items-center w-full text-left px-2 py-1.5 rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
              isActive ? "bg-primary/10 text-primary font-semibold hover:bg-primary/15" : "hover:bg-accent"
            ),
            "aria-expanded": isExpanded,
            "aria-controls": `section-${section.slug}`,
            "data-cy": `docs-section-toggle-${section.slug}`,
            children: [
              /* @__PURE__ */ jsx(
                ChevronRight,
                {
                  className: cn(
                    "h-4 w-4 mr-1 transition-transform",
                    isExpanded && "rotate-90"
                  ),
                  "aria-hidden": "true"
                }
              ),
              /* @__PURE__ */ jsx(Folder, { className: cn(
                "h-4 w-4 mr-2",
                isActive && "text-primary"
              ), "aria-hidden": "true" }),
              /* @__PURE__ */ jsx("span", { className: "text-sm font-medium flex-1", children: section.title })
            ]
          }
        ),
        isExpanded && /* @__PURE__ */ jsx(
          "div",
          {
            className: "ml-6 space-y-0.5",
            id: `section-${section.slug}`,
            "data-cy": `docs-section-pages-${section.slug}`,
            children: section.pages.map((page) => {
              const href = pluginName ? `/docs/plugins/${pluginName}/${section.slug}/${page.slug}` : `/docs/${category}/${section.slug}/${page.slug}`;
              const isActive2 = pathname === href;
              return /* @__PURE__ */ jsxs(
                Link,
                {
                  href,
                  className: cn(
                    "flex items-center px-2 py-1.5 rounded-md text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                    isActive2 ? "bg-accent text-accent-foreground font-medium" : "hover:bg-accent/50"
                  ),
                  "aria-current": isActive2 ? "page" : void 0,
                  "data-cy": `docs-page-link-${page.slug}`,
                  children: [
                    /* @__PURE__ */ jsx(FileText, { className: "h-3.5 w-3.5 mr-2", "aria-hidden": "true" }),
                    /* @__PURE__ */ jsx("span", { children: page.title })
                  ]
                },
                page.slug
              );
            })
          }
        )
      ] }, section.slug);
    });
  };
  const renderPluginSections = (pluginName, pluginSections2) => {
    const isPluginExpanded = searchQuery.trim() ? true : expandedPlugins.has(pluginName);
    const isPluginActive = activeElements.plugin === pluginName;
    const pluginDisplayName = pluginName.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
    return /* @__PURE__ */ jsxs("div", { className: "mb-3", children: [
      /* @__PURE__ */ jsxs(
        "button",
        {
          onClick: () => togglePlugin(pluginName),
          onKeyDown: (e) => handlePluginKeyDown(e, pluginName),
          className: cn(
            "flex items-center w-full text-left px-2 py-1.5 rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
            isPluginActive ? "bg-purple-500/10 text-purple-700 dark:text-purple-400 font-semibold hover:bg-purple-500/15" : "hover:bg-accent"
          ),
          "aria-expanded": isPluginExpanded,
          "data-cy": `docs-plugin-toggle-${pluginName}`,
          children: [
            /* @__PURE__ */ jsx(
              ChevronRight,
              {
                className: cn(
                  "h-4 w-4 mr-1 transition-transform",
                  isPluginExpanded && "rotate-90"
                ),
                "aria-hidden": "true"
              }
            ),
            /* @__PURE__ */ jsx(Puzzle, { className: cn(
              "h-4 w-4 mr-2",
              isPluginActive ? "text-purple-700 dark:text-purple-400" : "text-purple-600 dark:text-purple-400"
            ), "aria-hidden": "true" }),
            /* @__PURE__ */ jsxs("span", { className: "text-sm font-medium", children: [
              pluginDisplayName,
              " Plugin"
            ] })
          ]
        }
      ),
      isPluginExpanded && /* @__PURE__ */ jsx("div", { className: "ml-4 mt-1 space-y-1", children: renderSections(pluginSections2, "core", pluginName) })
    ] }, pluginName);
  };
  const renderCategory = (category, categorySections, icon, label) => {
    const isExpanded = searchQuery.trim() ? true : expandedCategories.has(category);
    const isCategoryActive = activeElements.category === category;
    return /* @__PURE__ */ jsxs("div", { className: "mb-6", children: [
      /* @__PURE__ */ jsxs(
        "button",
        {
          onClick: () => toggleCategory(category),
          onKeyDown: (e) => handleCategoryKeyDown(e, category),
          className: cn(
            "flex items-center w-full text-left px-2 py-2 mb-2 rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
            isCategoryActive ? "bg-accent text-accent-foreground hover:bg-accent" : "hover:bg-accent/50"
          ),
          "aria-expanded": isExpanded,
          "data-cy": `docs-category-toggle-${category}`,
          children: [
            /* @__PURE__ */ jsx(
              ChevronRight,
              {
                className: cn(
                  "h-4 w-4 mr-2 transition-transform",
                  isExpanded && "rotate-90"
                ),
                "aria-hidden": "true"
              }
            ),
            icon,
            /* @__PURE__ */ jsx("span", { className: cn(
              "text-sm font-semibold",
              isCategoryActive && "font-bold"
            ), children: label })
          ]
        }
      ),
      isExpanded && /* @__PURE__ */ jsx("div", { className: "ml-2 space-y-1", children: category === "plugins" ? Object.keys(pluginsByName).length > 0 ? Object.entries(pluginsByName).map(
        ([pluginName, pluginSections2]) => renderPluginSections(pluginName, pluginSections2)
      ) : /* @__PURE__ */ jsx("p", { className: "px-2 py-2 text-sm text-muted-foreground italic", children: "No documentation available" }) : categorySections.length > 0 ? renderSections(categorySections, category) : /* @__PURE__ */ jsx("p", { className: "px-2 py-2 text-sm text-muted-foreground italic", children: "No documentation available" }) })
    ] });
  };
  return /* @__PURE__ */ jsxs(
    "nav",
    {
      className: "h-full overflow-y-auto p-4",
      "aria-label": t("sidebar.label"),
      "data-cy": "docs-sidebar-nav",
      children: [
        /* @__PURE__ */ jsxs("div", { className: "mb-6", children: [
          /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold mb-2", children: t("title") }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mb-4", children: t("description") }),
          /* @__PURE__ */ jsxs("div", { className: "relative", children: [
            /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" }),
            /* @__PURE__ */ jsx(
              Input,
              {
                type: "text",
                placeholder: "Buscar en documentaci\xF3n...",
                value: searchQuery,
                onChange: (e) => setSearchQuery(e.target.value),
                className: "pl-9 pr-9",
                "data-cy": "docs-search-input"
              }
            ),
            searchQuery && /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => setSearchQuery(""),
                className: "absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors",
                "aria-label": "Limpiar b\xFAsqueda",
                "data-cy": "docs-search-clear",
                children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
              }
            )
          ] })
        ] }),
        searchQuery.trim() && visibleCoreSections.length === 0 && visibleThemeSections.length === 0 && visiblePluginSections.length === 0 && /* @__PURE__ */ jsx("div", { className: "text-center py-8 px-4", children: /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
          "No se encontraron resultados para ",
          /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
            '"',
            searchQuery,
            '"'
          ] })
        ] }) }),
        visibleThemeSections.length > 0 && renderCategory(
          "theme",
          visibleThemeSections,
          /* @__PURE__ */ jsx(Palette, { className: "h-4 w-4 mr-2", "aria-hidden": "true" }),
          themeConfig.label
        ),
        visiblePluginSections.length > 0 && renderCategory(
          "plugins",
          visiblePluginSections,
          /* @__PURE__ */ jsx(Puzzle, { className: "h-4 w-4 mr-2", "aria-hidden": "true" }),
          pluginsConfig.label
        ),
        visibleCoreSections.length > 0 && renderCategory(
          "core",
          visibleCoreSections,
          /* @__PURE__ */ jsx(BookOpen, { className: "h-4 w-4 mr-2", "aria-hidden": "true" }),
          coreConfig.label
        )
      ]
    }
  );
}
export {
  DocsSidebar
};
