"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useMemo } from "react";
import { useTranslations } from "next-intl";
import { useQuery } from "@tanstack/react-query";
import { Search, Plus, LayoutGrid, LayoutList, Layers, ClipboardPaste } from "lucide-react";
import { Input } from "../../ui/input.js";
import { ScrollArea } from "../../ui/scroll-area.js";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
import { getCategoryConfig } from "./category-helpers.js";
import { TreeView } from "./tree-view.js";
import { PatternCard } from "./pattern-card.js";
function getTeamId() {
  if (typeof window !== "undefined") {
    return localStorage.getItem("activeTeamId");
  }
  return null;
}
function buildApiHeaders() {
  const headers = {};
  const teamId = getTeamId();
  if (teamId) {
    headers["x-team-id"] = teamId;
  }
  return headers;
}
function BlockPicker({
  blocks,
  onAddBlock,
  onAddPattern,
  entityConfig,
  entityFields,
  onEntityFieldChange,
  showFieldsTab,
  showPatternsTab = false,
  // TreeView props
  pageBlocks,
  selectedBlockId,
  onSelectBlock,
  onReorderBlocks,
  onCopyBlock,
  onDuplicateBlock,
  onRemoveBlock,
  onPasteBlock,
  hasClipboardBlock
}) {
  const t = useTranslations("admin.builder");
  const tPatterns = useTranslations("patterns");
  const [activeTab, setActiveTab] = useState("blocks");
  const [search, setSearch] = useState("");
  const [selectedCategory, setSelectedCategory] = useState(null);
  const { data: patternsData, isLoading: patternsLoading } = useQuery({
    queryKey: ["patterns", "published"],
    queryFn: async () => {
      const response = await fetch("/api/v1/patterns?status=published", {
        headers: buildApiHeaders()
      });
      if (!response.ok) throw new Error("Failed to fetch patterns");
      return response.json();
    },
    enabled: showPatternsTab && activeTab === "patterns"
  });
  const categories = useMemo(() => {
    const uniqueCategories = [...new Set(blocks.map((block) => block.category))];
    return uniqueCategories.sort();
  }, [blocks]);
  const filteredBlocks = useMemo(() => {
    return blocks.filter((block) => {
      const matchesSearch = search === "" || block.name.toLowerCase().includes(search.toLowerCase()) || block.description.toLowerCase().includes(search.toLowerCase());
      const matchesCategory = !selectedCategory || block.category === selectedCategory;
      return matchesSearch && matchesCategory;
    });
  }, [blocks, search, selectedCategory]);
  const filteredPatterns = useMemo(() => {
    const patterns = (patternsData == null ? void 0 : patternsData.data) || [];
    if (search === "") return patterns;
    return patterns.filter(
      (pattern) => {
        var _a;
        return pattern.title.toLowerCase().includes(search.toLowerCase()) || ((_a = pattern.description) == null ? void 0 : _a.toLowerCase().includes(search.toLowerCase()));
      }
    );
  }, [patternsData, search]);
  return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col bg-card", "data-cy": sel("blockEditor.blockPicker.container"), children: [
    /* @__PURE__ */ jsxs("div", { className: "flex border-b border-border", children: [
      /* @__PURE__ */ jsxs(
        "button",
        {
          className: cn(
            "flex-1 py-3 text-sm font-medium transition-colors relative cursor-pointer",
            activeTab === "blocks" ? "text-primary bg-primary/5" : "text-muted-foreground hover:text-foreground hover:bg-muted/50"
          ),
          onClick: () => setActiveTab("blocks"),
          "data-cy": sel("blockEditor.blockPicker.tabBlocks"),
          children: [
            /* @__PURE__ */ jsx(LayoutGrid, { className: "h-4 w-4 inline mr-2" }),
            t("sidebar.tabs.blocks"),
            activeTab === "blocks" && /* @__PURE__ */ jsx(
              "div",
              {
                className: "absolute bottom-0 left-0 right-0 h-0.5 bg-primary",
                "data-cy": sel("blockEditor.blockPicker.tabIndicator")
              }
            )
          ]
        }
      ),
      showPatternsTab && /* @__PURE__ */ jsxs(
        "button",
        {
          className: cn(
            "flex-1 py-3 text-sm font-medium transition-colors relative cursor-pointer",
            activeTab === "patterns" ? "text-primary bg-primary/5" : "text-muted-foreground hover:text-foreground hover:bg-muted/50"
          ),
          onClick: () => setActiveTab("patterns"),
          "data-cy": sel("blockEditor.blockPicker.tabPatterns"),
          children: [
            /* @__PURE__ */ jsx(Layers, { className: "h-4 w-4 inline mr-2" }),
            t("sidebar.tabs.patterns"),
            activeTab === "patterns" && /* @__PURE__ */ jsx("div", { className: "absolute bottom-0 left-0 right-0 h-0.5 bg-primary" })
          ]
        }
      ),
      /* @__PURE__ */ jsxs(
        "button",
        {
          className: cn(
            "flex-1 py-3 text-sm font-medium transition-colors relative cursor-pointer",
            activeTab === "layout" ? "text-primary bg-primary/5" : "text-muted-foreground hover:text-foreground hover:bg-muted/50"
          ),
          onClick: () => setActiveTab("layout"),
          "data-cy": sel("blockEditor.blockPicker.tabLayout"),
          children: [
            /* @__PURE__ */ jsx(LayoutList, { className: "h-4 w-4 inline mr-2" }),
            t("sidebar.tabs.layout"),
            activeTab === "layout" && /* @__PURE__ */ jsx("div", { className: "absolute bottom-0 left-0 right-0 h-0.5 bg-primary" })
          ]
        }
      )
    ] }),
    activeTab === "blocks" ? /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs("div", { className: "p-4 border-b border-border sticky top-0 bg-card z-10", children: [
        /* @__PURE__ */ jsxs("div", { className: "relative", "data-cy": sel("blockEditor.blockPicker.searchWrapper"), children: [
          /* @__PURE__ */ jsx(
            Search,
            {
              className: "absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground",
              "data-cy": sel("blockEditor.blockPicker.searchIcon")
            }
          ),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "block-search",
              name: "block-search",
              type: "text",
              placeholder: t("sidebar.search.placeholder"),
              value: search,
              onChange: (e) => setSearch(e.target.value),
              className: "pl-9",
              "data-cy": sel("blockEditor.blockPicker.searchInput")
            }
          )
        ] }),
        /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex gap-2 mt-3 overflow-x-auto pb-1 scrollbar-thin",
            "data-cy": sel("blockEditor.blockPicker.categoryChips"),
            children: [
              /* @__PURE__ */ jsx(
                "button",
                {
                  className: cn(
                    "px-2.5 py-1 text-xs font-medium rounded-md whitespace-nowrap transition-colors cursor-pointer",
                    !selectedCategory ? "bg-foreground text-background" : "bg-muted text-muted-foreground hover:bg-muted-foreground/20"
                  ),
                  onClick: () => setSelectedCategory(null),
                  "data-cy": sel("blockEditor.blockPicker.categoryActive"),
                  children: t("sidebar.categories.all")
                }
              ),
              categories.map((category) => {
                const config = getCategoryConfig(category);
                const Icon = config.icon;
                const isActive = selectedCategory === category;
                return /* @__PURE__ */ jsxs(
                  "button",
                  {
                    className: cn(
                      "px-2.5 py-1 text-xs font-medium rounded-md whitespace-nowrap transition-colors capitalize flex items-center gap-1.5 cursor-pointer",
                      isActive ? `${config.bgColor} ${config.textColor} ${config.borderColor} border` : "bg-muted text-muted-foreground hover:bg-muted-foreground/20"
                    ),
                    onClick: () => setSelectedCategory(category),
                    "data-cy": sel("blockEditor.blockPicker.categoryChip", { category }),
                    children: [
                      /* @__PURE__ */ jsx(Icon, { className: "h-3 w-3" }),
                      category
                    ]
                  },
                  category
                );
              })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsx(ScrollArea, { className: "flex-1 p-4", "data-cy": sel("blockEditor.blockPicker.blockList"), children: /* @__PURE__ */ jsx("div", { className: "space-y-3", children: filteredBlocks.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-center py-8 text-muted-foreground", children: /* @__PURE__ */ jsx("p", { className: "text-sm", children: t("sidebar.empty") }) }) : filteredBlocks.map((block) => {
        const categoryConfig = getCategoryConfig(block.category);
        const CategoryIcon = categoryConfig.icon;
        return /* @__PURE__ */ jsxs(
          "div",
          {
            className: "group relative bg-background border border-border rounded-lg p-3 hover:border-primary hover:shadow-md transition-[border-color,box-shadow] cursor-pointer",
            onClick: () => onAddBlock(block.slug),
            "data-cy": sel("blockEditor.blockPicker.blockCard", { slug: block.slug }),
            children: [
              /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between mb-2", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: cn(
                        "w-6 h-6 rounded flex items-center justify-center text-xs",
                        categoryConfig.bgColor,
                        categoryConfig.textColor
                      ),
                      "data-cy": sel("blockEditor.blockPicker.blockIcon", { slug: block.slug }),
                      children: /* @__PURE__ */ jsx(CategoryIcon, { className: "h-3.5 w-3.5" })
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: "font-medium text-sm text-foreground",
                      "data-cy": sel("blockEditor.blockPicker.blockName", { slug: block.slug }),
                      children: block.name
                    }
                  )
                ] }),
                /* @__PURE__ */ jsx(
                  "span",
                  {
                    className: "text-[10px] uppercase font-bold text-muted-foreground bg-muted px-1.5 py-0.5 rounded capitalize",
                    "data-cy": sel("blockEditor.blockPicker.blockCategory", { slug: block.slug }),
                    children: block.category
                  }
                )
              ] }),
              /* @__PURE__ */ jsx(
                "p",
                {
                  className: "text-xs text-muted-foreground line-clamp-2",
                  "data-cy": sel("blockEditor.blockPicker.blockDescription", { slug: block.slug }),
                  children: block.description
                }
              ),
              /* @__PURE__ */ jsx("div", { className: "absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity", children: /* @__PURE__ */ jsx(
                "button",
                {
                  className: "w-6 h-6 bg-foreground text-background rounded flex items-center justify-center text-xs shadow-md hover:scale-110 transition-transform cursor-pointer",
                  onClick: (e) => {
                    e.stopPropagation();
                    onAddBlock(block.slug);
                  },
                  "data-cy": sel("blockEditor.blockPicker.addButton", { slug: block.slug }),
                  title: t("sidebar.addBlock"),
                  children: /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" })
                }
              ) })
            ]
          },
          block.slug
        );
      }) }) })
    ] }) : activeTab === "patterns" ? (
      // Patterns Tab
      /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("div", { className: "p-4 border-b border-border sticky top-0 bg-card z-10", children: /* @__PURE__ */ jsxs("div", { className: "relative", "data-cy": sel("blockEditor.blockPicker.patternsSearchWrapper"), children: [
          /* @__PURE__ */ jsx(
            Search,
            {
              className: "absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground",
              "data-cy": sel("blockEditor.blockPicker.patternsSearchIcon")
            }
          ),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              placeholder: tPatterns("picker.search"),
              value: search,
              onChange: (e) => setSearch(e.target.value),
              className: "pl-9",
              "data-cy": sel("blockEditor.blockPicker.patternsSearch")
            }
          )
        ] }) }),
        /* @__PURE__ */ jsx(ScrollArea, { className: "flex-1 p-4", "data-cy": sel("blockEditor.blockPicker.patternsList"), children: patternsLoading ? /* @__PURE__ */ jsx("div", { className: "text-center py-8 text-muted-foreground", children: /* @__PURE__ */ jsx("p", { className: "text-sm", children: tPatterns("picker.loading") || "Loading patterns..." }) }) : filteredPatterns.length === 0 ? /* @__PURE__ */ jsxs(
          "div",
          {
            className: "text-center py-8 text-muted-foreground",
            "data-cy": sel("blockEditor.blockPicker.patternsEmpty"),
            children: [
              /* @__PURE__ */ jsx(Layers, { className: "h-12 w-12 mx-auto mb-3 opacity-20" }),
              /* @__PURE__ */ jsx("p", { className: "text-sm font-medium mb-1", children: search ? tPatterns("picker.noResults") : tPatterns("list.empty") }),
              /* @__PURE__ */ jsx("p", { className: "text-xs", children: search ? tPatterns("picker.noResults") : tPatterns("list.emptyDescription") })
            ]
          }
        ) : /* @__PURE__ */ jsx("div", { className: "space-y-3", children: filteredPatterns.map((pattern) => /* @__PURE__ */ jsx(
          PatternCard,
          {
            pattern,
            onSelect: (patternId) => {
              if (onAddPattern) {
                onAddPattern(patternId);
                setSearch("");
              }
            }
          },
          pattern.id
        )) }) })
      ] })
    ) : (
      // Layout Tab - Tree View
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full", children: [
        hasClipboardBlock && onPasteBlock && /* @__PURE__ */ jsx("div", { className: "p-3 border-b border-border", children: /* @__PURE__ */ jsxs(
          "button",
          {
            className: "w-full flex items-center justify-center gap-2 px-3 py-2 text-sm font-medium rounded-md bg-primary/10 text-primary hover:bg-primary/20 transition-colors cursor-pointer",
            onClick: onPasteBlock,
            "data-cy": sel("blockEditor.blockPicker.pasteBlock"),
            children: [
              /* @__PURE__ */ jsx(ClipboardPaste, { className: "h-4 w-4" }),
              t("layout.pasteBlock")
            ]
          }
        ) }),
        /* @__PURE__ */ jsx(
          TreeView,
          {
            blocks: pageBlocks,
            selectedBlockId,
            onSelectBlock,
            onReorder: onReorderBlocks,
            onCopy: onCopyBlock,
            onDuplicate: onDuplicateBlock,
            onRemove: onRemoveBlock,
            emptyMessage: t("layout.empty")
          }
        )
      ] })
    )
  ] });
}
export {
  BlockPicker
};
