"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import {
  getCustomerDictionarySettingsSectionId
} from "../lib/dictionaries.js";
import { ICON_SUGGESTIONS } from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
import {
  DictionaryForm
} from "@open-mercato/core/modules/dictionaries/components/DictionaryForm";
import {
  DictionaryTable
} from "@open-mercato/core/modules/dictionaries/components/DictionaryTable";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const DEFAULT_FORM_VALUES = {
  value: "",
  label: "",
  color: null,
  icon: null
};
const DICTIONARY_HASH_SCROLL_RETRY_DELAYS_MS = [100, 350, 1e3];
function getCurrentDictionaryHashTarget() {
  if (typeof window === "undefined") return null;
  const hash = window.location.hash;
  if (!hash.startsWith("#customer-dictionary-")) return null;
  try {
    return document.getElementById(decodeURIComponent(hash.slice(1)));
  } catch {
    return document.getElementById(hash.slice(1));
  }
}
function DictionarySettings() {
  const t = useT();
  const sections = React.useMemo(() => [
    {
      kind: "person-company-roles",
      title: t("customers.config.dictionaries.sections.personCompanyRoles.title", "Role types"),
      description: t("customers.config.dictionaries.sections.personCompanyRoles.description", "Manage the ownership roles available in People tab assignments.")
    },
    {
      kind: "statuses",
      title: t("customers.config.dictionaries.sections.statuses.title", "Statuses"),
      description: t("customers.config.dictionaries.sections.statuses.description", "Define the statuses available for customer records.")
    },
    {
      kind: "deal-statuses",
      title: t("customers.config.dictionaries.sections.dealStatuses.title", "Deal statuses"),
      description: t("customers.config.dictionaries.sections.dealStatuses.description", "Manage the statuses available for deals.")
    },
    {
      kind: "job-titles",
      title: t("customers.config.dictionaries.sections.jobTitles.title", "Job titles"),
      description: t("customers.config.dictionaries.sections.jobTitles.description", "Configure job titles with their appearance.")
    },
    {
      kind: "sources",
      title: t("customers.config.dictionaries.sections.sources.title", "Sources"),
      description: t("customers.config.dictionaries.sections.sources.description", "Capture how customers were acquired.")
    },
    {
      kind: "industries",
      title: t("customers.config.dictionaries.sections.industries.title", "Industries"),
      description: t("customers.config.dictionaries.sections.industries.description", "Manage the industries used by companies.")
    },
    {
      kind: "lifecycle-stages",
      title: t("customers.config.dictionaries.sections.lifecycle.title", "Lifecycle stages"),
      description: t("customers.config.dictionaries.sections.lifecycle.description", "Configure lifecycle stages to track customer progress.")
    },
    {
      kind: "activity-types",
      title: t("customers.config.dictionaries.sections.activityTypes.title", "Activity types"),
      description: t("customers.config.dictionaries.sections.activityTypes.description", "Define the activity types used for customer interactions.")
    },
    {
      kind: "interaction-statuses",
      title: t("customers.config.dictionaries.sections.interactionStatuses.title", "Interaction statuses"),
      description: t("customers.config.dictionaries.sections.interactionStatuses.description", "Manage the statuses available for tasks and logged interactions.")
    },
    {
      kind: "address-types",
      title: t("customers.config.dictionaries.sections.addressTypes.title", "Address types"),
      description: t("customers.config.dictionaries.sections.addressTypes.description", "Define the available address types.")
    }
  ], [t]);
  React.useEffect(() => {
    const timeoutIds = [];
    let frameId = null;
    const clearScheduledScrolls = () => {
      if (frameId !== null) {
        window.cancelAnimationFrame(frameId);
        frameId = null;
      }
      while (timeoutIds.length > 0) {
        const timeoutId = timeoutIds.pop();
        if (timeoutId !== void 0) window.clearTimeout(timeoutId);
      }
    };
    const scrollToHashTarget = () => {
      getCurrentDictionaryHashTarget()?.scrollIntoView({ block: "start" });
    };
    const scheduleHashScroll = () => {
      clearScheduledScrolls();
      if (!window.location.hash.startsWith("#customer-dictionary-")) return;
      scrollToHashTarget();
      if (typeof window.requestAnimationFrame === "function") {
        frameId = window.requestAnimationFrame(scrollToHashTarget);
      }
      DICTIONARY_HASH_SCROLL_RETRY_DELAYS_MS.forEach((delay) => {
        timeoutIds.push(window.setTimeout(scrollToHashTarget, delay));
      });
    };
    scheduleHashScroll();
    window.addEventListener("hashchange", scheduleHashScroll);
    return () => {
      window.removeEventListener("hashchange", scheduleHashScroll);
      clearScheduledScrolls();
    };
  }, []);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-8", children: [
    /* @__PURE__ */ jsxs("header", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: t("customers.config.dictionaries.title", "Customers dictionaries") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("customers.config.dictionaries.description", "Manage the dictionaries used by the customers module.") })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "space-y-6", children: sections.map((section) => /* @__PURE__ */ jsx(CustomerDictionarySection, { ...section }, section.kind)) })
  ] });
}
function CustomerDictionarySection({ kind, title, description }) {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const scopeVersion = useOrganizationScopeVersion();
  const [entries, setEntries] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [dialog, setDialog] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const saveContextId = `customers-dictionary-${kind}`;
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: saveContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const mutationContext = React.useMemo(
    () => ({
      formId: saveContextId,
      resourceKind: "customers.dictionary",
      retryLastMutation
    }),
    [retryLastMutation, saveContextId]
  );
  const inheritedActionBlocked = t("customers.config.dictionaries.inherited.blocked", "Inherited entries can only be edited from the parent organization.");
  const inheritedTooltip = t("customers.config.dictionaries.inherited.tooltip", "Managed in parent organization");
  const inheritedLabel = t("customers.config.dictionaries.inherited.label", "Inherited");
  const errorLoad = t("customers.config.dictionaries.error.load", "Failed to load dictionary entries.");
  const errorSave = t("customers.config.dictionaries.error.save", "Failed to save dictionary entry.");
  const errorDelete = t("customers.config.dictionaries.error.delete", "Failed to delete dictionary entry.");
  const successSave = t("customers.config.dictionaries.success.save", "Dictionary entry saved.");
  const successDelete = t("customers.config.dictionaries.success.delete", "Dictionary entry deleted.");
  const deleteConfirmTemplate = t("customers.config.dictionaries.deleteConfirm", 'Delete "{{value}}"?');
  const roleTypeDeleteBlockedTitle = t("customers.config.dictionaries.roleTypes.deleteBlocked.title", "Role type is in use");
  const roleTypeDeleteBlockedText = t(
    "customers.config.dictionaries.roleTypes.deleteBlocked.text",
    "This role type is assigned to {{count}} records. Remove or replace those assignments before deleting it."
  );
  const usageCountLabel = t("customers.config.dictionaries.roleTypes.usageCount", "In use on {{count}} records");
  const searchPlaceholder = t("customers.config.dictionaries.searchPlaceholder", "Search entries\u2026");
  const formatCountMessage = React.useCallback((template, count) => {
    return template.replace("{{count}}", String(count));
  }, []);
  const loadEntries = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await readApiResultOrThrow(
        `/api/customers/dictionaries/${kind}`,
        void 0,
        { errorMessage: errorLoad }
      );
      if (!Array.isArray(data?.items)) throw new Error(errorLoad);
      const mapped = data.items.map((item) => ({
        id: String(item.id),
        value: String(item.value ?? ""),
        label: typeof item.label === "string" ? item.label : "",
        color: typeof item.color === "string" ? item.color : null,
        icon: typeof item.icon === "string" ? item.icon : null,
        usageCount: typeof item.usageCount === "number" ? item.usageCount : void 0,
        organizationId: typeof item.organizationId === "string" ? item.organizationId : null,
        tenantId: typeof item.tenantId === "string" ? item.tenantId : null,
        isInherited: item.isInherited === true,
        createdAt: typeof item.createdAt === "string" ? item.createdAt : null,
        updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : null
      }));
      setEntries(mapped);
    } catch (err) {
      logger.error("customers.dictionaries.list failed", { err });
      flash(errorLoad, "error");
    } finally {
      setLoading(false);
    }
  }, [errorLoad, kind, scopeVersion]);
  React.useEffect(() => {
    loadEntries().catch(() => {
    });
  }, [loadEntries]);
  const closeDialog = React.useCallback(() => {
    setDialog(null);
  }, []);
  const handleCreate = React.useCallback(() => {
    setDialog({ mode: "create" });
  }, []);
  const handleEdit = React.useCallback((entry) => {
    if (entry.isInherited) {
      flash(inheritedActionBlocked, "info");
      return;
    }
    setDialog({ mode: "edit", entry });
  }, [inheritedActionBlocked]);
  const handleDelete = React.useCallback(async (entry) => {
    if (entry.isInherited) {
      flash(inheritedActionBlocked, "info");
      return;
    }
    if (kind === "person-company-roles" && (entry.usageCount ?? 0) > 0) {
      await confirm({
        title: roleTypeDeleteBlockedTitle,
        description: formatCountMessage(roleTypeDeleteBlockedText, entry.usageCount ?? 0),
        confirmText: false,
        cancelText: t("customers.config.dictionaries.dialog.cancel", "Cancel")
      });
      return;
    }
    const message = deleteConfirmTemplate.replace("{{value}}", entry.label || entry.value);
    const confirmed = await confirm({
      title: message,
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await runMutation({
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(entry.updatedAt),
          () => apiCallOrThrow(
            `/api/customers/dictionaries/${kind}/${encodeURIComponent(entry.id)}`,
            { method: "DELETE" },
            { errorMessage: errorDelete }
          )
        ),
        context: mutationContext,
        mutationPayload: { action: "delete", id: entry.id, kind }
      });
      flash(successDelete, "success");
      await loadEntries();
    } catch (err) {
      logger.error("customers.dictionaries.delete failed", { err });
      if (kind === "person-company-roles" && err?.code === "role_type_in_use") {
        const usageCount = Number(err.usageCount ?? 0);
        await confirm({
          title: roleTypeDeleteBlockedTitle,
          description: formatCountMessage(roleTypeDeleteBlockedText, usageCount),
          confirmText: false,
          cancelText: t("customers.config.dictionaries.dialog.cancel", "Cancel")
        });
        return;
      }
      const messageValue = err instanceof Error ? err.message : errorDelete;
      flash(messageValue, "error");
    }
  }, [confirm, deleteConfirmTemplate, errorDelete, formatCountMessage, inheritedActionBlocked, kind, loadEntries, mutationContext, roleTypeDeleteBlockedText, roleTypeDeleteBlockedTitle, runMutation, successDelete, t]);
  const submitForm = React.useCallback(async (values) => {
    const payload = {
      value: values.value,
      label: values.label,
      color: values.color,
      icon: values.icon
    };
    setSubmitting(true);
    try {
      if (!dialog || dialog.mode === "create") {
        await runMutation({
          operation: () => apiCallOrThrow(
            `/api/customers/dictionaries/${kind}`,
            {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify(payload)
            },
            { errorMessage: errorSave }
          ),
          context: mutationContext,
          mutationPayload: { action: "create", kind, ...payload }
        });
        flash(successSave, "success");
      } else if (dialog.mode === "edit") {
        const target = dialog.entry;
        if (target.isInherited) {
          flash(inheritedActionBlocked, "info");
          return;
        }
        const body = {};
        if (values.value !== target.value) body.value = values.value;
        if (values.label !== target.label) body.label = values.label;
        const nextColor = values.color ?? null;
        if (nextColor !== (target.color ?? null)) body.color = nextColor;
        const nextIcon = values.icon ?? null;
        if (nextIcon !== (target.icon ?? null)) body.icon = nextIcon;
        if (Object.keys(body).length === 0) {
          closeDialog();
          return;
        }
        await runMutation({
          operation: () => withScopedApiRequestHeaders(
            buildOptimisticLockHeader(target.updatedAt),
            () => apiCallOrThrow(
              `/api/customers/dictionaries/${kind}/${encodeURIComponent(target.id)}`,
              {
                method: "PATCH",
                headers: { "content-type": "application/json" },
                body: JSON.stringify(body)
              },
              { errorMessage: errorSave }
            )
          ),
          context: mutationContext,
          mutationPayload: { action: "update", id: target.id, kind, ...body }
        });
        flash(successSave, "success");
      }
      closeDialog();
      await loadEntries();
    } catch (err) {
      logger.error("customers.dictionaries.submit failed", { err });
      throw err instanceof Error ? err : new Error(errorSave);
    } finally {
      setSubmitting(false);
    }
  }, [closeDialog, dialog, errorSave, inheritedActionBlocked, kind, loadEntries, mutationContext, runMutation, successSave]);
  const currentValues = React.useMemo(() => {
    if (dialog && dialog.mode === "edit") {
      return {
        value: dialog.entry.value,
        label: dialog.entry.label,
        color: dialog.entry.color,
        icon: dialog.entry.icon
      };
    }
    return DEFAULT_FORM_VALUES;
  }, [dialog]);
  const tableTranslations = React.useMemo(() => ({
    title,
    valueColumn: t("customers.config.dictionaries.columns.value", "Value"),
    labelColumn: t("customers.config.dictionaries.columns.label", "Label"),
    appearanceColumn: t("customers.config.dictionaries.columns.appearance", "Appearance"),
    addLabel: t("customers.config.dictionaries.actions.add", "Add entry"),
    editLabel: t("customers.config.dictionaries.actions.edit", "Edit"),
    deleteLabel: t("customers.config.dictionaries.actions.delete", "Delete"),
    refreshLabel: t("customers.config.dictionaries.actions.refresh", "Refresh"),
    inheritedLabel,
    inheritedTooltip,
    emptyLabel: t("customers.config.dictionaries.empty", "No entries yet."),
    usageCountLabel: kind === "person-company-roles" ? usageCountLabel : void 0,
    searchPlaceholder
  }), [inheritedLabel, inheritedTooltip, kind, searchPlaceholder, t, title, usageCountLabel]);
  const formTranslations = React.useMemo(() => ({
    title: dialog?.mode === "edit" ? t("customers.config.dictionaries.dialog.editTitle", "Edit entry") : t("customers.config.dictionaries.dialog.addTitle", "Add entry"),
    valueLabel: t("customers.config.dictionaries.dialog.valueLabel", "Value"),
    labelLabel: t("customers.config.dictionaries.dialog.labelLabel", "Label"),
    saveLabel: t("customers.config.dictionaries.dialog.save", "Save"),
    cancelLabel: t("customers.config.dictionaries.dialog.cancel", "Cancel"),
    appearance: {
      colorLabel: t("customers.config.dictionaries.dialog.colorLabel", "Color"),
      colorHelp: t("customers.config.dictionaries.dialog.colorHelp", "Pick a highlight color for this entry."),
      colorClearLabel: t("customers.config.dictionaries.dialog.colorClear", "Remove color"),
      iconLabel: t("customers.config.dictionaries.dialog.iconLabel", "Icon"),
      iconPlaceholder: t("customers.config.dictionaries.dialog.iconPlaceholder", "Type an emoji or pick one of the suggestions."),
      iconPickerTriggerLabel: t("customers.config.dictionaries.dialog.iconBrowse", "Browse icons and emojis"),
      iconSearchPlaceholder: t("customers.config.dictionaries.dialog.iconSearchPlaceholder", "Search icons or emojis\u2026"),
      iconSearchEmptyLabel: t("customers.config.dictionaries.dialog.iconSearchEmpty", "No icons match your search."),
      iconSuggestionsLabel: t("customers.config.dictionaries.dialog.iconSuggestions", "Suggestions"),
      iconClearLabel: t("customers.config.dictionaries.dialog.iconClear", "Remove icon"),
      previewEmptyLabel: t("customers.config.dictionaries.appearance.empty", "None")
    }
  }), [dialog, t]);
  return /* @__PURE__ */ jsxs(
    "section",
    {
      id: getCustomerDictionarySettingsSectionId(kind),
      className: "scroll-mt-24 rounded border bg-card text-card-foreground shadow-sm",
      children: [
        /* @__PURE__ */ jsxs("div", { className: "border-b px-6 py-4 space-y-1", children: [
          /* @__PURE__ */ jsx("h2", { className: "text-lg font-medium", children: title }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: description })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "px-2 py-4 sm:px-4", children: /* @__PURE__ */ jsx(
          DictionaryTable,
          {
            entries,
            loading,
            canManage: true,
            onCreate: handleCreate,
            onEdit: handleEdit,
            onDelete: handleDelete,
            onRefresh: loadEntries,
            translations: tableTranslations
          }
        ) }),
        /* @__PURE__ */ jsx(Dialog, { open: dialog !== null, onOpenChange: (open) => {
          if (!open) closeDialog();
        }, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-lg", children: [
          /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: formTranslations.title }) }),
          /* @__PURE__ */ jsx(
            DictionaryForm,
            {
              mode: dialog?.mode === "edit" ? "edit" : "create",
              initialValues: currentValues,
              onSubmit: submitForm,
              onCancel: closeDialog,
              submitting,
              translations: formTranslations,
              iconSuggestions: ICON_SUGGESTIONS
            }
          )
        ] }) }),
        ConfirmDialogElement
      ]
    }
  );
}
export {
  DictionarySettings as default
};
//# sourceMappingURL=DictionarySettings.js.map
