"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Ellipsis } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { ColorPicker } from "@open-mercato/ui/primitives/color-picker";
import { Input } from "@open-mercato/ui/primitives/input";
import { ICON_LIBRARY, ICON_SUGGESTIONS, renderDictionaryColor, renderDictionaryIcon } from "./dictionaryAppearance.js";
const ICON_PICKER_LIMIT = 240;
function AppearanceSelector({
  icon,
  color,
  onIconChange,
  onColorChange,
  labels,
  disabled = false,
  iconSuggestions = ICON_SUGGESTIONS,
  iconLibrary,
  className,
  previewLabel
}) {
  const normalizedIcon = icon ?? "";
  const normalizedColor = color ?? "#000000";
  const hasAppearance = Boolean(icon) || Boolean(color);
  const trimmedPreviewLabel = typeof previewLabel === "string" ? previewLabel.trim() : "";
  const hasPreviewContent = hasAppearance || trimmedPreviewLabel.length > 0;
  const iconOptions = React.useMemo(() => iconLibrary && iconLibrary.length ? iconLibrary : ICON_LIBRARY, [iconLibrary]);
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const [iconSearch, setIconSearch] = React.useState("");
  const pickerContainerRef = React.useRef(null);
  const searchInputRef = React.useRef(null);
  const closePicker = React.useCallback(() => {
    setPickerOpen(false);
    setIconSearch("");
  }, []);
  const handleIconSelection = React.useCallback(
    (next) => {
      onIconChange(next);
      closePicker();
    },
    [closePicker, onIconChange]
  );
  React.useEffect(() => {
    if (!pickerOpen) return;
    const handlePointerDown = (event) => {
      const target = event.target;
      if (pickerContainerRef.current?.contains(target)) return;
      closePicker();
    };
    const handleKeyDown = (event) => {
      if (event.key === "Escape") closePicker();
    };
    document.addEventListener("pointerdown", handlePointerDown);
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("pointerdown", handlePointerDown);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [closePicker, pickerOpen]);
  React.useEffect(() => {
    if (!pickerOpen) return;
    const frame = window.requestAnimationFrame(() => {
      searchInputRef.current?.focus();
      searchInputRef.current?.select();
    });
    return () => window.cancelAnimationFrame(frame);
  }, [pickerOpen]);
  React.useEffect(() => {
    if (!disabled) return;
    closePicker();
  }, [closePicker, disabled]);
  const filteredIcons = React.useMemo(() => {
    const term = iconSearch.trim().toLowerCase();
    if (!term) {
      return iconOptions.slice(0, ICON_PICKER_LIMIT);
    }
    const matches = iconOptions.filter((option) => {
      const haystack = [option.label, option.value, ...option.keywords ?? []].join(" ").toLowerCase();
      return haystack.includes(term);
    });
    return matches.slice(0, ICON_PICKER_LIMIT);
  }, [iconOptions, iconSearch]);
  return /* @__PURE__ */ jsxs("div", { className: ["space-y-4", className].filter(Boolean).join(" "), children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm font-medium", children: [
        labels.colorLabel,
        labels.colorHelp ? /* @__PURE__ */ jsx("span", { className: "text-xs font-normal text-muted-foreground", children: labels.colorHelp }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
        /* @__PURE__ */ jsx(
          ColorPicker,
          {
            value: normalizedColor,
            onChange: (next) => onColorChange(next),
            disabled,
            "aria-label": labels.colorLabel
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            onClick: () => onColorChange(null),
            disabled: disabled || !color,
            children: labels.colorClearLabel
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", children: labels.iconLabel }),
      /* @__PURE__ */ jsxs("div", { ref: pickerContainerRef, className: "relative", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              value: normalizedIcon,
              onChange: (event) => onIconChange(event.target.value),
              placeholder: labels.iconPlaceholder,
              className: "flex-1",
              disabled
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "icon",
              onClick: () => setPickerOpen((prev) => !prev),
              "aria-label": labels.iconPickerTriggerLabel,
              "aria-expanded": pickerOpen,
              "aria-haspopup": "dialog",
              disabled,
              children: /* @__PURE__ */ jsx(Ellipsis, { className: "h-4 w-4" })
            }
          )
        ] }),
        pickerOpen ? /* @__PURE__ */ jsx("div", { className: "absolute left-0 right-0 top-full z-dropdown mt-2 rounded-md border border-border bg-popover p-3 shadow-lg", children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsx(
            Input,
            {
              ref: searchInputRef,
              type: "search",
              value: iconSearch,
              onChange: (event) => setIconSearch(event.target.value),
              placeholder: labels.iconSearchPlaceholder,
              "aria-label": labels.iconSearchPlaceholder,
              autoComplete: "off"
            }
          ),
          /* @__PURE__ */ jsx("div", { className: "max-h-64 overflow-y-auto pr-1", children: filteredIcons.length ? /* @__PURE__ */ jsx("div", { className: "grid grid-cols-6 gap-2 sm:grid-cols-8", children: filteredIcons.map((option) => {
            const isSelected = normalizedIcon === option.value;
            return /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "ghost",
                size: "icon",
                className: isSelected ? "bg-primary/10 text-primary ring-1 ring-primary/60" : void 0,
                onClick: () => handleIconSelection(option.value),
                title: option.label,
                "aria-label": option.label,
                "aria-pressed": isSelected,
                children: renderDictionaryIcon(option.value, "h-4 w-4")
              },
              option.value
            );
          }) }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: labels.iconSearchEmptyLabel }) }),
          iconSuggestions.length ? /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", children: labels.iconSuggestionsLabel }),
            /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: iconSuggestions.map((suggestion) => {
              const isSelected = normalizedIcon === suggestion.value;
              return /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "outline",
                  size: "sm",
                  className: `text-xs ${isSelected ? "border-primary bg-primary/10 text-primary" : ""}`,
                  onClick: () => handleIconSelection(suggestion.value),
                  children: [
                    renderDictionaryIcon(suggestion.value, "h-3 w-3"),
                    suggestion.label
                  ]
                },
                suggestion.value
              );
            }) })
          ] }) : null,
          /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: () => onIconChange(null), children: labels.iconClearLabel }) })
        ] }) }) : null
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", children: "Preview" }),
      /* @__PURE__ */ jsx("div", { className: "flex items-center gap-3 rounded border border-dashed border-border px-3 py-2", children: hasPreviewContent ? /* @__PURE__ */ jsxs(Fragment, { children: [
        renderDictionaryIcon(icon, "h-5 w-5"),
        renderDictionaryColor(color, "h-4 w-4 rounded-full"),
        trimmedPreviewLabel ? /* @__PURE__ */ jsx("span", { className: "text-sm", children: trimmedPreviewLabel }) : null
      ] }) : /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: labels.previewEmptyLabel }) })
    ] })
  ] });
}
function useAppearanceState(initialIcon, initialColor) {
  const [icon, setIcon] = React.useState(initialIcon);
  const [color, setColor] = React.useState(initialColor);
  return React.useMemo(
    () => ({
      icon,
      color,
      setIcon,
      setColor
    }),
    [icon, color]
  );
}
export {
  AppearanceSelector,
  useAppearanceState
};
//# sourceMappingURL=AppearanceSelector.js.map
