"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useQueryClient } from "@tanstack/react-query";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { DictionaryEntrySelect } from "./DictionaryEntrySelect.js";
import {
  ensureDictionaryEntries,
  invalidateDictionaryEntries
} from "./hooks/useDictionaryEntries.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dictionaries").child({ component: "DictionarySelectControl" });
function DictionarySelectControl({
  dictionaryId,
  value,
  onChange,
  allowInlineCreate = true,
  selectClassName,
  disabled = false,
  priorityValues,
  seedOptions
}) {
  const t = useT();
  const queryClient = useQueryClient();
  const scopeVersion = useOrganizationScopeVersion();
  const mutationContextId = React.useMemo(
    () => `dictionaries:dictionary_entry:inline:${dictionaryId}`,
    [dictionaryId]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const [inlineCreateEnabled, setInlineCreateEnabled] = React.useState(allowInlineCreate);
  React.useEffect(() => {
    let cancelled = false;
    async function evaluateInlineCreate() {
      if (!allowInlineCreate) {
        setInlineCreateEnabled(false);
        return;
      }
      try {
        const call = await apiCall(`/api/dictionaries/${dictionaryId}`);
        if (cancelled) return;
        if (call.ok && call.result && call.result.isInherited === true) {
          setInlineCreateEnabled(false);
          return;
        }
        setInlineCreateEnabled(true);
      } catch (err) {
        logger.warn("Inline create check failed", { err });
        if (!cancelled) {
          setInlineCreateEnabled(allowInlineCreate);
        }
      }
    }
    evaluateInlineCreate().catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, [allowInlineCreate, dictionaryId, scopeVersion]);
  const effectiveAllowInlineCreate = allowInlineCreate && inlineCreateEnabled;
  const normalizedPriority = React.useMemo(() => {
    if (!Array.isArray(priorityValues) || !priorityValues.length) return [];
    const seen = /* @__PURE__ */ new Set();
    const ordered = [];
    priorityValues.forEach((code) => {
      if (typeof code !== "string") return;
      const normalized = code.trim().toLowerCase();
      if (!normalized.length || seen.has(normalized)) return;
      seen.add(normalized);
      ordered.push(normalized);
    });
    return ordered;
  }, [priorityValues]);
  const fetchOptions = React.useCallback(async () => {
    const data = await ensureDictionaryEntries(queryClient, dictionaryId, scopeVersion);
    const options = data.entries.map((entry) => ({
      value: entry.value,
      label: entry.label,
      color: entry.color ?? null,
      icon: entry.icon ?? null
    }));
    if (!normalizedPriority.length) return options;
    const byValue = /* @__PURE__ */ new Map();
    options.forEach((option) => {
      const key = option.value.trim().toLowerCase();
      if (!byValue.has(key)) byValue.set(key, option);
    });
    const prioritized = [];
    normalizedPriority.forEach((key) => {
      const match = byValue.get(key);
      if (match) {
        prioritized.push(match);
        byValue.delete(key);
      }
    });
    const remaining = [];
    byValue.forEach((option) => remaining.push(option));
    return [...prioritized, ...remaining];
  }, [dictionaryId, normalizedPriority, queryClient, scopeVersion]);
  const createOption = React.useCallback(
    async (input) => {
      const payload = {
        value: input.value,
        label: input.label ?? input.value,
        color: input.color,
        icon: input.icon
      };
      const call = await runMutation({
        operation: async () => {
          const result = await apiCall(
            `/api/dictionaries/${dictionaryId}/entries`,
            {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify(payload)
            }
          );
          if (!result.ok) {
            throw new Error(
              typeof result.result?.error === "string" ? result.result.error : "Failed to create dictionary entry"
            );
          }
          return result;
        },
        context: {
          formId: mutationContextId,
          resourceKind: "dictionaries.dictionary_entry",
          retryLastMutation
        },
        mutationPayload: payload
      });
      await invalidateDictionaryEntries(queryClient, dictionaryId);
      return {
        value: String(call.result?.value ?? input.value),
        label: typeof call.result?.label === "string" && call.result.label.length ? call.result.label : String(call.result?.value ?? input.value),
        color: typeof call.result?.color === "string" ? call.result.color : null,
        icon: typeof call.result?.icon === "string" ? call.result.icon : null
      };
    },
    [dictionaryId, mutationContextId, queryClient, runMutation, retryLastMutation]
  );
  const labels = React.useMemo(
    () => ({
      placeholder: t("dictionaries.customFields.selector.placeholder", "Select an entry"),
      addLabel: t("dictionaries.customFields.selector.add", "Add entry"),
      addPrompt: t("dictionaries.customFields.selector.dialogDescription", "Create a new entry and reuse it across records."),
      dialogTitle: t("dictionaries.config.entries.dialog.addTitle", "Add dictionary entry"),
      valueLabel: t("dictionaries.config.entries.dialog.valueLabel", "Value"),
      valuePlaceholder: t("dictionaries.config.entries.dialog.valueLabel", "Value"),
      labelLabel: t("dictionaries.config.entries.dialog.labelLabel", "Label"),
      labelPlaceholder: t("dictionaries.config.entries.dialog.labelPlaceholder", "Display name shown in UI"),
      emptyError: t("dictionaries.config.entries.error.required", "Value is required."),
      cancelLabel: t("dictionaries.config.entries.dialog.cancel", "Cancel"),
      saveLabel: t("dictionaries.config.entries.dialog.save", "Save"),
      saveShortcutHint: t("dictionaries.config.entries.dialog.saveShortcut", "\u2318/Ctrl + Enter"),
      successCreateLabel: t("dictionaries.config.entries.success.create", "Dictionary entry created."),
      errorLoad: t("dictionaries.config.entries.error.load", "Failed to load dictionary entries."),
      errorSave: t("dictionaries.config.entries.error.save", "Failed to save dictionary entry."),
      loadingLabel: t("dictionaries.config.entries.loading", "Loading entries\u2026"),
      manageTitle: t("dictionaries.customFields.manageLink", "Manage dictionaries")
    }),
    [t]
  );
  const appearanceLabels = React.useMemo(
    () => ({
      colorLabel: t("dictionaries.config.entries.dialog.colorLabel", "Color"),
      colorHelp: t("dictionaries.config.entries.dialog.colorHelp", "Pick a highlight color for this entry."),
      colorClearLabel: t("dictionaries.config.entries.dialog.colorClear", "Remove color"),
      iconLabel: t("dictionaries.config.entries.dialog.iconLabel", "Icon or emoji"),
      iconPlaceholder: t("dictionaries.config.entries.dialog.iconPlaceholder", "Type an emoji or icon token."),
      iconPickerTriggerLabel: t("dictionaries.config.entries.dialog.iconBrowse", "Browse icons and emoji"),
      iconSearchPlaceholder: t("dictionaries.config.entries.dialog.iconSearchPlaceholder", "Search icons or emojis\u2026"),
      iconSearchEmptyLabel: t("dictionaries.config.entries.dialog.iconSearchEmpty", "No icons match your search."),
      iconSuggestionsLabel: t("dictionaries.config.entries.dialog.iconSuggestions", "Suggestions"),
      iconClearLabel: t("dictionaries.config.entries.dialog.iconClear", "Remove icon"),
      previewEmptyLabel: t("dictionaries.config.entries.dialog.previewEmpty", "No appearance selected")
    }),
    [t]
  );
  return /* @__PURE__ */ jsx(
    DictionaryEntrySelect,
    {
      value: typeof value === "string" ? value : void 0,
      onChange,
      fetchOptions,
      createOption: effectiveAllowInlineCreate ? createOption : void 0,
      labels,
      appearanceLabels,
      allowAppearance: true,
      allowInlineCreate: effectiveAllowInlineCreate,
      selectClassName,
      seedOptions: seedOptions?.map((option) => ({
        value: option.value,
        label: option.label,
        color: option.color ?? null,
        icon: option.icon ?? null
      })),
      sortOptions: "none",
      disabled,
      manageHref: "/backend/config/dictionaries"
    }
  );
}
export {
  DictionarySelectControl
};
//# sourceMappingURL=DictionarySelectControl.js.map
