import { j as jsxRuntimeExports } from "../../../../../../../_virtual/jsx-runtime.js";
import { useState, useRef, useEffect, useMemo, startTransition } from "react";
import "../../../../../../../node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import "../../../../../../../node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/react-hot-toast/dist/index.js";
import { Icon } from "../../../../../../../node_modules/.pnpm/@iconify_react@6.0.0_react@19.1.1/node_modules/@iconify/react/dist/iconify.js";
import collections from "../../../../shared/misc/iconify-collections.json.js";
import { tx as D, css as E } from "../../../../../../style-system/dist/twind.js";
import { useVirtualizer } from "../../../../../../../node_modules/.pnpm/@tanstack_react-virtual@3.13.12_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/@tanstack/react-virtual/dist/esm/index.js";
import { RxMagnifyingGlass } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/rx/index.js";
import { FieldTitle } from "../field-factory.js";
import { Root as P, Trigger as s, Content as i } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/popover.js";
import { Button as o } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/button.js";
import { Root as C, Trigger as u, Content as g, Item as v } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/select.js";
import { Root as u$1, Slot as c } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/text-field.js";
const blaclistedCollections = [
  "logos",
  // Color logos, not suitable for icon selection
  "bitcoin-icons",
  // Contains only Bitcoin-related icons, not suitable for general use
  "brandico",
  // Contains too few icons, not suitable for general use
  "bpmn",
  // Contains only BPMN icons, not suitable for general use
  "bytesize",
  // Contains only a few icons, not suitable for general use
  "catppuccin",
  // Contains colored icons
  "charm",
  // Contains only a few icons, not suitable for general use
  "codex",
  // Contains only a few icons, not suitable for general use
  "emojione",
  // Colored emojis, not suitable for general use
  "covid"
  // Colored emojis, not suitable for general use
];
const availableCollections = Object.entries(
  collections
).map(([code, col]) => ({
  code,
  ...col
})).filter(
  (collection) => blaclistedCollections.includes(collection.code) === false && typeof collection.total === "number" && collection.total > 0
).sort((a, b) => a.name.localeCompare(b.name));
function* generateIconsFromCategories(categories, collectionPrefix) {
  for (const categoryIcons of Object.values(categories)) {
    if (Array.isArray(categoryIcons)) {
      for (const iconName of categoryIcons) {
        yield `${collectionPrefix}:${iconName}`;
      }
    }
  }
}
const IconifyField = ({ currentValue, onChange, title, description, schema, defaultCollection }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [selectedCollection, setSelectedCollection] = useState(
    defaultCollection ?? availableCollections[0].code
  );
  const [categories, setCategories] = useState({});
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState([]);
  const [isSearching, setIsSearching] = useState(false);
  const parentRef = useRef(null);
  useEffect(() => {
    async function proceed() {
      if (!selectedCollection) {
        return {};
      }
      setLoading(true);
      try {
        const response = await fetch(`https://api.iconify.design/collection?prefix=${selectedCollection}`);
        if (!response.ok) {
          console.error("Failed to fetch icons for collection:", selectedCollection);
          return {};
        }
        const data = await response.json();
        const processedCategories = {};
        if (data.categories) {
          Object.entries(data.categories).forEach(([categoryName, icons]) => {
            if (Array.isArray(icons)) {
              processedCategories[categoryName] = icons;
            }
          });
        }
        if (data.uncategorized && Array.isArray(data.uncategorized)) {
          processedCategories.uncategorized = data.uncategorized;
        }
        if (Object.keys(processedCategories).length === 0 && data.icons && Array.isArray(data.icons)) {
          processedCategories.uncategorized = data.icons;
        }
        setCategories(processedCategories);
      } catch (error) {
        console.error("Error fetching icons:", error);
        setCategories({});
      } finally {
        setLoading(false);
      }
    }
    proceed();
  }, [selectedCollection]);
  useEffect(() => {
    if (!searchQuery.trim()) {
      setSearchResults([]);
      setIsSearching(false);
      return;
    }
    const searchIcons = async () => {
      setIsSearching(true);
      try {
        const response = await fetch(
          `https://api.iconify.design/search?query=${encodeURIComponent(searchQuery)}&limit=150`
        );
        if (!response.ok) {
          console.error("Failed to search icons:", response.statusText);
          setSearchResults([]);
          return;
        }
        const data = await response.json();
        const results = data.icons ?? [];
        setSearchResults(results);
      } catch (error) {
        console.error("Error searching icons:", error);
        setSearchResults([]);
      } finally {
        setIsSearching(false);
      }
    };
    const timeoutId = setTimeout(searchIcons, 300);
    return () => clearTimeout(timeoutId);
  }, [searchQuery]);
  const collectionIcons = useMemo(() => {
    if (searchQuery.trim()) {
      return searchResults;
    }
    if (!categories || Object.keys(categories).length === 0 || !selectedCollection) {
      return [];
    }
    const iconGenerator = generateIconsFromCategories(categories, selectedCollection);
    const icons = Array.from(iconGenerator);
    return icons;
  }, [categories, selectedCollection, searchQuery, searchResults]);
  const ITEMS_PER_ROW = 6;
  const ITEM_HEIGHT = 48;
  const rowCount = Math.ceil(collectionIcons.length / ITEMS_PER_ROW);
  const rowData = useMemo(() => {
    const rows = [];
    for (let i2 = 0; i2 < rowCount; i2++) {
      const startIndex = i2 * ITEMS_PER_ROW;
      const endIndex = Math.min(startIndex + ITEMS_PER_ROW, collectionIcons.length);
      rows.push(collectionIcons.slice(startIndex, endIndex));
    }
    return rows;
  }, [collectionIcons, rowCount]);
  const virtualizer = useVirtualizer({
    count: rowCount,
    enabled: isOpen && selectedCollection !== null,
    getScrollElement: () => parentRef.current,
    estimateSize: () => ITEM_HEIGHT,
    overscan: 5,
    // Render 5 extra rows for smooth scrolling
    useAnimationFrameWithResizeObserver: true
    // Use animation frame for smoother scrolling
  });
  useEffect(() => {
    if (!isOpen) {
      return;
    }
    startTransition(() => {
      virtualizer.measure();
    });
  }, [isOpen, virtualizer]);
  const handleIconSelect = (iconName) => {
    onChange(iconName);
    setIsOpen(false);
  };
  const getSelectedCollectionInfo = () => {
    return availableCollections.find((col) => col.code === selectedCollection);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between flex-1 gap-1", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title, description }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 justify-between", children: [
      currentValue && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { icon: currentValue, className: "w-6 h-6 text-upstart-500" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(P, { open: isOpen, onOpenChange: setIsOpen, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(s, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(o, { type: "button", variant: "soft", size: "1", radius: "full", children: "Choose icon" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(i, { className: "w-80 p-4 bg-white border border-gray-200 rounded-lg shadow-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              C,
              {
                name: "collection",
                defaultValue: selectedCollection ?? void 0,
                onValueChange: (value) => {
                  setLoading(true);
                  startTransition(() => {
                    setSelectedCollection(value);
                  });
                },
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(u, { radius: "medium", variant: "surface", className: "!w-full capitalize" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(g, { position: "popper", children: availableCollections.map((collection) => /* @__PURE__ */ jsxRuntimeExports.jsxs(v, { value: collection.code, className: "capitalize", children: [
                    collection.name,
                    " (",
                    collection.total,
                    " icons)"
                  ] }, collection.code)) })
                ]
              }
            ),
            getSelectedCollectionInfo() && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 mt-1", children: getSelectedCollectionInfo()?.author && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
              "Icons by ",
              getSelectedCollectionInfo().author.name
            ] }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: D("mt-6"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            u$1,
            {
              value: searchQuery,
              onChange: (e) => setSearchQuery(e.target.value),
              placeholder: "Search icons across all collections...",
              size: "2",
              variant: "surface",
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(c, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(RxMagnifyingGlass, { height: "16", width: "16" }) })
            }
          ) }),
          searchQuery.trim() && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500", children: isSearching ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Searching..." }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
            collectionIcons.length,
            " icons found",
            searchQuery && ` for "${searchQuery}"`
          ] }) }),
          (loading || isSearching) && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center py-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500", children: isSearching ? "Searching icons..." : "Loading icons..." }) }),
          !loading && !isSearching && collectionIcons.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              ref: parentRef,
              className: D(
                "h-[320px] overflow-auto scrollbar-thin",
                E({
                  scrollbarColor: "var(--violet-4) var(--violet-1)"
                })
              ),
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  style: {
                    height: `${virtualizer.getTotalSize()}px`,
                    width: "100%",
                    position: "relative"
                  },
                  children: virtualizer.getVirtualItems().map((virtualRow) => {
                    const rowIcons = rowData[virtualRow.index];
                    if (!rowIcons) {
                      return null;
                    }
                    return /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        style: {
                          position: "absolute",
                          top: 0,
                          left: 0,
                          width: "100%",
                          height: `${virtualRow.size}px`,
                          transform: `translateY(${virtualRow.start}px)`
                        },
                        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-6 gap-2 px-1 py-2", children: [
                          rowIcons.map((iconName) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "button",
                            {
                              type: "button",
                              onClick: () => handleIconSelect(iconName),
                              className: `p-2 rounded hover:bg-upstart-100 flex items-center justify-center transition-colors ${currentValue === iconName ? "bg-upstart-100 border border-upstart-500" : "border border-transparent"}`,
                              children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { icon: iconName, className: "w-5 h-5" })
                            },
                            iconName
                          )),
                          rowIcons.length < ITEMS_PER_ROW && Array.from({ length: ITEMS_PER_ROW - rowIcons.length }).map((_, index) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2" }, `empty-${index}`))
                        ] })
                      },
                      virtualRow.index
                    );
                  })
                }
              )
            }
          ),
          !loading && !isSearching && collectionIcons.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center text-gray-500 text-sm py-4", children: searchQuery.trim() ? `No icons found for "${searchQuery}"` : "No icons found in this collection" })
        ] }) })
      ] })
    ] })
  ] });
};
export {
  IconifyField as default
};
//# sourceMappingURL=iconify.js.map
