"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Cog, GripVertical, Languages, Pencil, Plus, Trash2 } from "lucide-react";
import { Button } from "../../primitives/button.js";
import { IconButton } from "../../primitives/icon-button.js";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../primitives/select.js";
import { CUSTOM_FIELD_KINDS } from "@open-mercato/shared/modules/entities/kinds";
import { FieldRegistry } from "../fields/registry.js";
import { slugify } from "@open-mercato/shared/lib/slugify";
import { useConfirmDialog } from "../confirm-dialog/index.js";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "../../primitives/dialog.js";
import {
  normalizeCustomFieldOptions
} from "@open-mercato/shared/modules/entities/options";
const DEFAULT_KIND_OPTIONS = CUSTOM_FIELD_KINDS.map((k) => ({
  value: k,
  label: k.charAt(0).toUpperCase() + k.slice(1)
}));
const FIELDSET_ICON_OPTIONS = [
  { value: "layers", label: "Layers" },
  { value: "tag", label: "Tag" },
  { value: "sparkles", label: "Sparkles" },
  { value: "package", label: "Package" },
  { value: "shirt", label: "Shirt" },
  { value: "grid", label: "Grid" },
  { value: "shoppingBag", label: "Shopping bag" },
  { value: "shoppingCart", label: "Shopping cart" },
  { value: "store", label: "Store" },
  { value: "users", label: "Users" },
  { value: "briefcase", label: "Briefcase" },
  { value: "building", label: "Building" },
  { value: "bookOpen", label: "Book open" },
  { value: "bookmark", label: "Bookmark" },
  { value: "camera", label: "Camera" },
  { value: "car", label: "Car" },
  { value: "clock", label: "Clock" },
  { value: "cloud", label: "Cloud" },
  { value: "compass", label: "Compass" },
  { value: "creditCard", label: "Credit card" },
  { value: "database", label: "Database" },
  { value: "flame", label: "Flame" },
  { value: "gift", label: "Gift" },
  { value: "globe", label: "Globe" },
  { value: "heart", label: "Heart" },
  { value: "key", label: "Key" },
  { value: "map", label: "Map" },
  { value: "palette", label: "Palette" },
  { value: "shield", label: "Shield" },
  { value: "star", label: "Star" },
  { value: "truck", label: "Truck" },
  { value: "zap", label: "Zap" },
  { value: "coins", label: "Coins" }
];
function slugifyFieldsetCode(value) {
  return slugify(value, { replacement: "", allowedChars: "_-" });
}
function ensureUniqueFieldsetCode(base, existing) {
  const sanitizedBase = slugifyFieldsetCode(base) || "fieldset";
  let candidate = sanitizedBase;
  let counter = 1;
  const existingCodes = new Set(existing.map((fs) => fs.code));
  while (existingCodes.has(candidate)) {
    counter += 1;
    candidate = `${sanitizedBase}_${counter}`;
  }
  return candidate;
}
function normalizeGroupValue(raw) {
  if (!raw) return null;
  if (typeof raw === "string") {
    const code2 = raw.trim();
    return code2 ? { code: code2 } : null;
  }
  if (typeof raw !== "object") return null;
  const entry = raw;
  const code = typeof entry.code === "string" ? entry.code.trim() : "";
  if (!code) return null;
  const group = { code };
  if (typeof entry.title === "string" && entry.title.trim()) group.title = entry.title.trim();
  if (typeof entry.hint === "string" && entry.hint.trim()) group.hint = entry.hint.trim();
  return group;
}
function FieldDefinitionsEditor({
  definitions,
  errors,
  deletedKeys,
  kindOptions = DEFAULT_KIND_OPTIONS,
  orderNotice,
  infoNote = /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground mt-2", children: "Supported kinds: text, multiline, integer, float, boolean, select (with options/optionsUrl), currency (fixed currencies list), relation (with related entity and options URL)." }),
  addButtonLabel = "Add Field",
  fieldsets = [],
  activeFieldset = null,
  onActiveFieldsetChange,
  onFieldsetsChange,
  onFieldsetCodeChange,
  onFieldsetRemoved,
  singleFieldsetPerRecord,
  onSingleFieldsetPerRecordChange,
  onAddField,
  onRemoveField,
  onDefinitionChange,
  onRestoreField,
  onReorder,
  onTranslate,
  listRef,
  listProps,
  translate
}) {
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const dragIndex = React.useRef(null);
  const hasFieldsets = fieldsets.length > 0;
  const t = React.useCallback((key, fallback) => translate ? translate(key, fallback) : fallback, [translate]);
  const resolvedActiveFieldset = React.useMemo(() => {
    if (!hasFieldsets) return activeFieldset ?? null;
    if (activeFieldset === null) return null;
    return fieldsets.some((fs) => fs.code === activeFieldset) ? activeFieldset : fieldsets[0]?.code ?? null;
  }, [activeFieldset, fieldsets, hasFieldsets]);
  const filteredDefinitions = React.useMemo(
    () => definitions.map((definition, index) => ({ definition, index })).filter(({ definition }) => {
      if (!hasFieldsets) return true;
      const assigned = typeof definition.configJson?.fieldset === "string" ? definition.configJson.fieldset : void 0;
      if (!resolvedActiveFieldset) return !assigned;
      return assigned === resolvedActiveFieldset;
    }),
    [definitions, hasFieldsets, resolvedActiveFieldset]
  );
  const activeFieldsetConfig = hasFieldsets && resolvedActiveFieldset ? fieldsets.find((fs) => fs.code === resolvedActiveFieldset) ?? null : null;
  const handleActiveFieldsetChange = (value) => {
    if (!onActiveFieldsetChange) return;
    onActiveFieldsetChange(value ? value : null);
  };
  const handleFieldsetPatch = (code, patch) => {
    if (!onFieldsetsChange) return;
    const next = fieldsets.map((fs) => fs.code === code ? { ...fs, ...patch } : fs);
    onFieldsetsChange(next);
  };
  const handleFieldsetCodeInput = (code, nextValue) => {
    if (!onFieldsetsChange) return;
    const target = fieldsets.find((fs) => fs.code === code);
    if (!target) return;
    const sanitized = slugifyFieldsetCode(nextValue);
    if (!sanitized) return;
    const next = fieldsets.map((fs) => fs.code === code ? { ...fs, code: sanitized } : fs);
    onFieldsetsChange(next);
    onFieldsetCodeChange?.(code, sanitized);
    onActiveFieldsetChange?.(sanitized);
  };
  const handleAddFieldset = () => {
    if (!onFieldsetsChange) return;
    const code = ensureUniqueFieldsetCode(`fieldset_${fieldsets.length + 1}`, fieldsets);
    const nextFieldsets = [...fieldsets, { code, label: "New fieldset", icon: "layers" }];
    onFieldsetsChange(nextFieldsets);
    onActiveFieldsetChange?.(code);
  };
  const handleRemoveFieldset = async () => {
    if (!onFieldsetsChange) return;
    if (!resolvedActiveFieldset) return;
    const confirmed = await confirm({
      title: `Delete fieldset "${resolvedActiveFieldset}"?`,
      text: "This will move its fields to Unassigned.",
      variant: "destructive"
    });
    if (!confirmed) return;
    const next = fieldsets.filter((fs) => fs.code !== resolvedActiveFieldset);
    onFieldsetsChange(next);
    onFieldsetRemoved?.(resolvedActiveFieldset);
    const fallback = next[0]?.code ?? null;
    onActiveFieldsetChange?.(fallback);
  };
  const registerGroup = React.useCallback(
    (fieldsetCode, group) => {
      if (!onFieldsetsChange || !fieldsetCode) return;
      const next = fieldsets.map((fs) => {
        if (fs.code !== fieldsetCode) return fs;
        const list = Array.isArray(fs.groups) ? fs.groups : [];
        const existingIndex = list.findIndex((entry) => entry.code === group.code);
        if (existingIndex >= 0) {
          const updated = [...list];
          updated[existingIndex] = { ...list[existingIndex], ...group };
          return { ...fs, groups: updated };
        }
        return { ...fs, groups: [...list, group] };
      });
      onFieldsetsChange(next);
    },
    [fieldsets, onFieldsetsChange]
  );
  const removeGroup = React.useCallback(
    (fieldsetCode, groupCode) => {
      if (!onFieldsetsChange || !fieldsetCode || !groupCode) return;
      const next = fieldsets.map((fs) => {
        if (fs.code !== fieldsetCode) return fs;
        const list = Array.isArray(fs.groups) ? fs.groups : [];
        return { ...fs, groups: list.filter((entry) => entry.code !== groupCode) };
      });
      onFieldsetsChange(next);
    },
    [fieldsets, onFieldsetsChange]
  );
  const availableGroups = activeFieldsetConfig?.groups ?? [];
  const canToggleSingleFieldset = hasFieldsets && fieldsets.length > 1;
  const singleFieldsetChecked = singleFieldsetPerRecord !== false;
  const handleReorder = React.useCallback(
    (from, to) => {
      if (from === to) return;
      onReorder?.(from, to);
    },
    [onReorder]
  );
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: listRef,
      className: "space-y-3",
      ...listProps,
      children: [
        hasFieldsets ? /* @__PURE__ */ jsxs("div", { className: "rounded border bg-card p-3 space-y-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
            /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "Fieldset" }),
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: resolvedActiveFieldset || void 0,
                onValueChange: (value) => handleActiveFieldsetChange(value ?? ""),
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { size: "sm", className: "w-auto min-w-[10rem]", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Unassigned fields" }) }),
                  /* @__PURE__ */ jsx(SelectContent, { children: fieldsets.map((fs) => /* @__PURE__ */ jsx(SelectItem, { value: fs.code, children: fs.label || fs.code }, fs.code)) })
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: handleAddFieldset,
                className: "text-xs",
                children: [
                  /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
                  " Add"
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: handleRemoveFieldset,
                disabled: !resolvedActiveFieldset,
                className: "text-xs",
                children: [
                  /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" }),
                  " Delete"
                ]
              }
            )
          ] }),
          resolvedActiveFieldset && activeFieldsetConfig ? /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-4 gap-3", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Code" }),
              /* @__PURE__ */ jsx(
                "input",
                {
                  className: "border rounded w-full px-2 py-1 text-sm font-mono",
                  value: activeFieldsetConfig.code,
                  onChange: (event) => handleFieldsetCodeInput(activeFieldsetConfig.code, event.target.value)
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Label" }),
              /* @__PURE__ */ jsx(
                "input",
                {
                  className: "border rounded w-full px-2 py-1 text-sm",
                  value: activeFieldsetConfig.label,
                  onChange: (event) => handleFieldsetPatch(activeFieldsetConfig.code, { label: event.target.value })
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Icon" }),
              /* @__PURE__ */ jsxs(
                Select,
                {
                  value: activeFieldsetConfig.icon || void 0,
                  onValueChange: (value) => handleFieldsetPatch(activeFieldsetConfig.code, {
                    icon: value || void 0
                  }),
                  children: [
                    /* @__PURE__ */ jsx(SelectTrigger, { size: "sm", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Default" }) }),
                    /* @__PURE__ */ jsx(SelectContent, { children: FIELDSET_ICON_OPTIONS.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.value, children: option.label }, option.value)) })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Description" }),
              /* @__PURE__ */ jsx(
                "input",
                {
                  className: "border rounded w-full px-2 py-1 text-sm",
                  value: activeFieldsetConfig.description ?? "",
                  onChange: (event) => handleFieldsetPatch(activeFieldsetConfig.code, { description: event.target.value })
                }
              )
            ] })
          ] }) : null,
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
            /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(
                "input",
                {
                  type: "checkbox",
                  disabled: !canToggleSingleFieldset,
                  checked: singleFieldsetChecked,
                  onChange: (event) => onSingleFieldsetPerRecordChange?.(event.target.checked)
                }
              ),
              "Single fieldset per entity"
            ] }),
            !canToggleSingleFieldset ? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "(add at least two fieldsets to toggle)" }) : null
          ] })
        ] }) : /* @__PURE__ */ jsxs("div", { className: "rounded border border-dashed bg-muted/30 p-4 text-sm text-muted-foreground flex flex-col gap-3", children: [
          /* @__PURE__ */ jsx("div", { children: "No fieldsets defined yet. Fieldsets let you group custom fields for different variants of the same entity (e.g., Fashion vs. Sport products)." }),
          /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: handleAddFieldset,
              children: [
                /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }),
                "Add first fieldset"
              ]
            }
          ) })
        ] }),
        orderNotice?.dirty && /* @__PURE__ */ jsx("div", { className: "sticky top-0 z-sticky -mt-1 -mb-1", children: /* @__PURE__ */ jsx("div", { className: "inline-flex items-center gap-2 text-xs px-2 py-1 rounded border bg-amber-50 text-amber-800 shadow-sm", children: orderNotice?.saving ? "Saving order\u2026" : orderNotice?.message ?? "Reordered \u2014 saving soon" }) }),
        filteredDefinitions.map(({ definition, index }) => {
          const assignedFieldset = typeof definition.configJson?.fieldset === "string" ? definition.configJson.fieldset : null;
          const groupOptions = assignedFieldset ? fieldsets.find((fs) => fs.code === assignedFieldset)?.groups ?? [] : availableGroups;
          return /* @__PURE__ */ jsx(
            "div",
            {
              className: "group",
              draggable: true,
              onDragStart: () => {
                dragIndex.current = index;
              },
              onDragOver: (event) => {
                event.preventDefault();
              },
              onDrop: () => {
                const from = dragIndex.current;
                if (from == null) return;
                dragIndex.current = null;
                handleReorder(from, index);
              },
              onDragEnd: () => {
                dragIndex.current = null;
              },
              tabIndex: 0,
              onKeyDown: (event) => {
                if (!event.altKey) return;
                if (event.key === "ArrowUp" || event.key === "Up") {
                  event.preventDefault();
                  handleReorder(index, Math.max(0, index - 1));
                }
                if (event.key === "ArrowDown" || event.key === "Down") {
                  event.preventDefault();
                  handleReorder(index, Math.min(definitions.length - 1, index + 1));
                }
              },
              children: /* @__PURE__ */ jsx(
                FieldDefinitionCard,
                {
                  definition,
                  error: errors?.[index],
                  kindOptions,
                  onChange: (next) => onDefinitionChange(index, next),
                  onRemove: () => onRemoveField(index),
                  allowFieldsetSelection: hasFieldsets,
                  fieldsets,
                  activeFieldset: resolvedActiveFieldset,
                  availableGroups: groupOptions,
                  onRegisterGroup: registerGroup,
                  onRemoveGroup: removeGroup,
                  onTranslate: onTranslate ? () => onTranslate(definition, index) : void 0,
                  translate: t
                }
              )
            },
            definition.key || `def-${index}`
          );
        }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: onAddField,
              children: [
                /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }),
                " ",
                addButtonLabel
              ]
            }
          ),
          infoNote,
          deletedKeys && deletedKeys.length > 0 && onRestoreField ? /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground mt-2", children: [
            "Restore deleted fields:",
            " ",
            deletedKeys.map((key, idx) => /* @__PURE__ */ jsxs("span", { children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "link",
                  className: "h-auto p-0 text-blue-600",
                  onClick: () => onRestoreField(key),
                  children: key
                }
              ),
              idx < deletedKeys.length - 1 ? ", " : ""
            ] }, key))
          ] }) : null
        ] }),
        ConfirmDialogElement
      ]
    }
  );
}
const FieldDefinitionCard = React.memo(function FieldDefinitionCard2({
  definition,
  error,
  kindOptions,
  onChange,
  onRemove,
  allowFieldsetSelection = false,
  fieldsets = [],
  activeFieldset,
  availableGroups = [],
  onRegisterGroup,
  onRemoveGroup,
  onTranslate,
  translate
}) {
  const [local, setLocal] = React.useState(definition);
  const localRef = React.useRef(definition);
  const [optionValueDraft, setOptionValueDraft] = React.useState("");
  const [optionLabelDraft, setOptionLabelDraft] = React.useState("");
  const [optionDialogOpen, setOptionDialogOpen] = React.useState(false);
  const [optionFormError, setOptionFormError] = React.useState(null);
  const [groupDialogOpen, setGroupDialogOpen] = React.useState(false);
  const [groupDraft, setGroupDraft] = React.useState({ code: "", title: "", hint: "" });
  const [editingGroupCode, setEditingGroupCode] = React.useState(null);
  const [groupError, setGroupError] = React.useState(null);
  const currentFieldsetValue = React.useMemo(
    () => typeof local.configJson?.fieldset === "string" ? local.configJson.fieldset : "",
    [local.configJson?.fieldset]
  );
  const t = React.useCallback((key, fallback) => translate ? translate(key, fallback) : fallback, [translate]);
  React.useEffect(() => {
    localRef.current = definition;
    setLocal(definition);
  }, [definition.key]);
  React.useEffect(() => {
    setOptionValueDraft("");
    setOptionLabelDraft("");
    setGroupDialogOpen(false);
    setGroupDraft({ code: "", title: "", hint: "" });
    setEditingGroupCode(null);
    setGroupError(null);
  }, [definition.key]);
  React.useEffect(() => {
    if (!currentFieldsetValue) {
      setGroupDialogOpen(false);
      setGroupDraft({ code: "", title: "", hint: "" });
      setEditingGroupCode(null);
      setGroupError(null);
    }
  }, [currentFieldsetValue]);
  const currentGroup = React.useMemo(() => normalizeGroupValue(local.configJson?.group), [local]);
  const groupOptions = React.useMemo(() => {
    const list = Array.isArray(availableGroups) ? [...availableGroups] : [];
    if (currentGroup && !list.some((entry) => entry.code === currentGroup.code)) {
      list.push(currentGroup);
    }
    return list;
  }, [availableGroups, currentGroup]);
  const resolvedOptions = React.useMemo(
    () => normalizeCustomFieldOptions(local.configJson?.options),
    [local.configJson?.options]
  );
  const sanitize = (def) => {
    if (!def.configJson || !Array.isArray(def.configJson.options)) return def;
    const normalizedOptions = normalizeCustomFieldOptions(def.configJson.options);
    return {
      ...def,
      configJson: {
        ...def.configJson,
        options: normalizedOptions
      }
    };
  };
  const replaceLocal = React.useCallback((next) => {
    localRef.current = next;
    setLocal(next);
    return next;
  }, []);
  const apply = (patch, propagateNow = false) => {
    const current = localRef.current;
    const resolvedPatch = typeof patch === "function" ? patch(current) : patch;
    const next = { ...current, ...resolvedPatch };
    const resolvedNext = propagateNow ? sanitize(next) : next;
    replaceLocal(resolvedNext);
    if (propagateNow) {
      onChange(resolvedNext);
    }
  };
  const commit = () => {
    const sanitized = sanitize(localRef.current);
    replaceLocal(sanitized);
    onChange(sanitized);
  };
  const handleFieldsetSelect = (value) => {
    const nextConfig = { ...localRef.current.configJson || {} };
    if (value) nextConfig.fieldset = value;
    else delete nextConfig.fieldset;
    delete nextConfig.group;
    const next = { ...localRef.current, configJson: nextConfig };
    replaceLocal(next);
    onChange(next);
  };
  const handleGroupSelect = (value) => {
    if (!currentFieldsetValue) return;
    if (!value) {
      const nextConfig2 = { ...local.configJson || {} };
      delete nextConfig2.group;
      apply({ configJson: nextConfig2 }, true);
      return;
    }
    const match = groupOptions.find((group) => group.code === value);
    const nextGroup = match ?? { code: value };
    const nextConfig = { ...local.configJson || {} };
    nextConfig.group = nextGroup;
    apply({ configJson: nextConfig }, true);
    onRegisterGroup?.(currentFieldsetValue, nextGroup);
  };
  const handleOpenGroupDialog = (group) => {
    if (!currentFieldsetValue) return;
    if (group) {
      setGroupDraft({
        code: group.code,
        title: group.title ?? "",
        hint: group.hint ?? ""
      });
      setEditingGroupCode(group.code);
    } else {
      setGroupDraft({ code: "", title: "", hint: "" });
      setEditingGroupCode(null);
    }
    setGroupError(null);
    setGroupDialogOpen(true);
  };
  const handleGroupDialogSubmit = () => {
    if (!currentFieldsetValue) return;
    const code = slugifyFieldsetCode(groupDraft.code || "");
    if (!code) {
      setGroupError("Group code is required.");
      return;
    }
    const group = {
      code,
      title: groupDraft.title.trim() || void 0,
      hint: groupDraft.hint.trim() || void 0
    };
    onRegisterGroup?.(currentFieldsetValue, group);
    const shouldAttachToField = !editingGroupCode || currentGroup?.code === editingGroupCode;
    if (shouldAttachToField) {
      const nextConfig = { ...local.configJson || {} };
      nextConfig.group = group;
      apply({ configJson: nextConfig }, true);
    }
    setGroupDraft({ code: "", title: "", hint: "" });
    setEditingGroupCode(null);
    setGroupDialogOpen(false);
  };
  const handleRemoveGroupEntry = (code) => {
    if (!currentFieldsetValue) return;
    onRemoveGroup?.(currentFieldsetValue, code);
    if (currentGroup?.code === code) {
      handleGroupSelect("");
    }
    if (editingGroupCode === code) {
      setGroupDraft({ code: "", title: "", hint: "" });
      setEditingGroupCode(null);
    }
  };
  const handleEditGroupEntry = (group) => {
    handleOpenGroupDialog(group);
  };
  const resetOptionDialog = () => {
    setOptionValueDraft("");
    setOptionLabelDraft("");
    setOptionFormError(null);
  };
  const handleOpenOptionDialog = () => {
    resetOptionDialog();
    setOptionDialogOpen(true);
  };
  const handleCloseOptionDialog = () => {
    resetOptionDialog();
    setOptionDialogOpen(false);
  };
  const handleAddOption = () => {
    const value = optionValueDraft.trim();
    const label = optionLabelDraft.trim();
    if (!value) {
      setOptionFormError("Value is required");
      return;
    }
    setOptionFormError(null);
    const nextOptions = Array.isArray(local.configJson?.options) ? [...local.configJson.options] : [];
    nextOptions.push({ value, label: label || value });
    apply({ configJson: { ...local.configJson || {}, options: nextOptions } }, true);
    handleCloseOptionDialog();
  };
  const handleRemoveOption = (index) => {
    const nextOptions = Array.isArray(local.configJson?.options) ? [...local.configJson.options] : [];
    nextOptions.splice(index, 1);
    apply({ configJson: { ...local.configJson || {}, options: nextOptions } }, true);
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs("div", { className: "rounded border p-3 bg-card transition-colors hover:border-muted-foreground/60", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
          /* @__PURE__ */ jsx("span", { className: "inline-flex items-center justify-center h-5 w-5 rounded hover:bg-muted cursor-grab active:cursor-grabbing", children: /* @__PURE__ */ jsx(GripVertical, { className: "h-4 w-4 opacity-70" }) }),
          "Drag to reorder"
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2 text-sm", children: [
            /* @__PURE__ */ jsx("input", { type: "checkbox", checked: local.isActive !== false, onChange: (event) => {
              apply({ isActive: event.target.checked }, true);
            } }),
            " Active"
          ] }),
          onTranslate && /* @__PURE__ */ jsx(IconButton, { variant: "outline", size: "sm", onClick: onTranslate, "aria-label": "Translate field", children: /* @__PURE__ */ jsx(Languages, { className: "h-4 w-4" }) }),
          /* @__PURE__ */ jsx(IconButton, { variant: "outline", size: "sm", onClick: onRemove, "aria-label": "Remove field", children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-1 md:grid-cols-12 gap-3 items-center", children: [
        /* @__PURE__ */ jsxs("div", { className: "md:col-span-6", children: [
          /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Key" }),
          /* @__PURE__ */ jsx(
            "input",
            {
              className: `rounded w-full px-2 py-1 text-sm font-mono ${error?.key ? "border-red-500 border" : "border"}`,
              placeholder: "snake_case",
              value: local.key,
              onChange: (event) => apply({ key: event.target.value }),
              onBlur: commit
            }
          ),
          error?.key ? /* @__PURE__ */ jsx("div", { className: "text-xs text-red-600 mt-1", children: error.key }) : null
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "md:col-span-6", children: [
          /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Kind" }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: local.kind || void 0,
              onValueChange: (value) => {
                apply({ kind: value ?? "" }, true);
              },
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { className: error?.kind ? "border-destructive" : void 0, children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                /* @__PURE__ */ jsx(SelectContent, { children: kindOptions.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.value, children: option.label }, option.value)) })
              ]
            }
          ),
          error?.kind ? /* @__PURE__ */ jsx("div", { className: "text-xs text-red-600 mt-1", children: error.kind }) : null
        ] })
      ] }),
      allowFieldsetSelection ? /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-1 md:grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Assign to fieldset" }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: currentFieldsetValue || void 0,
              onValueChange: (value) => handleFieldsetSelect(value ?? ""),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Unassigned" }) }),
                /* @__PURE__ */ jsx(SelectContent, { children: (fieldsets || []).map((fs) => /* @__PURE__ */ jsx(SelectItem, { value: fs.code, children: fs.label || fs.code }, fs.code)) })
              ]
            }
          )
        ] }),
        currentFieldsetValue ? /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between", children: /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Group" }) }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mt-1", children: [
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: currentGroup?.code || void 0,
                onValueChange: (value) => handleGroupSelect(value ?? ""),
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { className: "flex-1", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "No group" }) }),
                  /* @__PURE__ */ jsx(SelectContent, { children: groupOptions.map((group) => /* @__PURE__ */ jsx(SelectItem, { value: group.code, children: group.title || group.code }, group.code)) })
                ]
              }
            ),
            /* @__PURE__ */ jsx(
              IconButton,
              {
                variant: "outline",
                className: "text-muted-foreground",
                onClick: () => handleOpenGroupDialog(),
                "aria-label": "Create group",
                children: /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" })
              }
            ),
            /* @__PURE__ */ jsx(
              IconButton,
              {
                variant: "outline",
                className: "text-muted-foreground",
                onClick: () => handleOpenGroupDialog(),
                "aria-label": "Edit groups",
                children: /* @__PURE__ */ jsx(Cog, { className: "h-4 w-4" })
              }
            )
          ] })
        ] }) : null
      ] }) : null,
      /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-1 md:grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Label" }),
          /* @__PURE__ */ jsx(
            "input",
            {
              className: "border rounded w-full px-2 py-1 text-sm",
              value: typeof local.configJson?.label === "string" ? local.configJson.label : "",
              onChange: (event) => apply({ configJson: { ...local.configJson || {}, label: event.target.value } }),
              onBlur: commit
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Description" }),
          /* @__PURE__ */ jsx(
            "input",
            {
              className: "border rounded w-full px-2 py-1 text-sm",
              value: typeof local.configJson?.description === "string" ? local.configJson.description : "",
              onChange: (event) => apply({ configJson: { ...local.configJson || {}, description: event.target.value } }),
              onBlur: commit
            }
          )
        ] }),
        (local.kind === "text" || local.kind === "multiline") && /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Editor" }),
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: typeof local.configJson?.editor === "string" && local.configJson.editor ? local.configJson.editor : void 0,
                onValueChange: (value) => {
                  apply({ configJson: { ...local.configJson || {}, editor: value || void 0 } }, true);
                },
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Default" }) }),
                  /* @__PURE__ */ jsxs(SelectContent, { children: [
                    /* @__PURE__ */ jsx(SelectItem, { value: "markdown", children: "Markdown (UIW)" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "simpleMarkdown", children: "Simple Markdown" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "htmlRichText", children: "HTML Rich Text" })
                  ] })
                ]
              }
            )
          ] }),
          local.kind === "text" && /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("div", { className: "md:col-span-2", children: /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2 text-xs", children: [
              /* @__PURE__ */ jsx("input", { type: "checkbox", checked: !!local.configJson?.multi, onChange: (event) => {
                apply({ configJson: { ...local.configJson || {}, multi: event.target.checked } }, true);
              } }),
              " Multiple"
            ] }) }),
            !!local.configJson?.multi && /* @__PURE__ */ jsxs("div", { className: "md:col-span-2", children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Multi-select input style" }),
              /* @__PURE__ */ jsxs(
                Select,
                {
                  value: local.configJson?.input === "listbox" ? "listbox" : "default",
                  onValueChange: (value) => {
                    const nextConfig = { ...local.configJson || {} };
                    if (value === "listbox") nextConfig.input = "listbox";
                    else delete nextConfig.input;
                    apply({ configJson: nextConfig }, true);
                  },
                  children: [
                    /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                    /* @__PURE__ */ jsxs(SelectContent, { children: [
                      /* @__PURE__ */ jsx(SelectItem, { value: "default", children: "Default" }),
                      /* @__PURE__ */ jsx(SelectItem, { value: "listbox", children: "Listbox (searchable)" })
                    ] })
                  ]
                }
              )
            ] })
          ] })
        ] }),
        local.kind === "select" && /* @__PURE__ */ jsxs("div", { className: "md:col-span-6 space-y-3", children: [
          /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Options" }),
          /* @__PURE__ */ jsx("div", { className: "space-y-2", children: resolvedOptions.length > 0 ? resolvedOptions.map((option, idx) => /* @__PURE__ */ jsxs(
            "div",
            {
              className: "flex items-center justify-between rounded border px-3 py-2 text-xs bg-muted",
              children: [
                /* @__PURE__ */ jsxs("div", { children: [
                  /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground", children: option.label }),
                  /* @__PURE__ */ jsx("div", { className: "text-muted-foreground font-mono text-overline", children: option.value })
                ] }),
                /* @__PURE__ */ jsx(
                  IconButton,
                  {
                    variant: "ghost",
                    size: "xs",
                    className: "text-red-500 hover:text-red-700",
                    onClick: () => handleRemoveOption(idx),
                    "aria-label": "Remove option",
                    children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" })
                  }
                )
              ]
            },
            `${option.value}-${idx}`
          )) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "No options defined." }) }),
          /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              className: "text-xs",
              onClick: handleOpenOptionDialog,
              children: [
                /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
                "Add option"
              ]
            }
          ) })
        ] }),
        (local.kind === "select" || local.kind === "relation") && /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Options URL" }),
            /* @__PURE__ */ jsx(
              "input",
              {
                className: "border rounded w-full px-2 py-1 text-sm",
                placeholder: "/api/...",
                value: typeof local.configJson?.optionsUrl === "string" ? local.configJson.optionsUrl : "",
                onChange: (event) => apply({ configJson: { ...local.configJson || {}, optionsUrl: event.target.value } }),
                onBlur: commit
              }
            )
          ] }),
          local.kind === "relation" && /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Related Entity ID" }),
            /* @__PURE__ */ jsx(
              "input",
              {
                className: "border rounded w-full px-2 py-1 text-sm font-mono",
                placeholder: "module:entity",
                value: typeof local.configJson?.relatedEntityId === "string" ? local.configJson.relatedEntityId : "",
                onChange: (event) => {
                  const relatedEntityId = event.target.value;
                  const defOptionsUrl = relatedEntityId ? `/api/entities/relations/options?entityId=${encodeURIComponent(relatedEntityId)}` : "";
                  apply({
                    configJson: {
                      ...local.configJson || {},
                      relatedEntityId,
                      optionsUrl: local.configJson?.optionsUrl || defOptionsUrl
                    }
                  });
                },
                onBlur: commit
              }
            )
          ] })
        ] }),
        local.kind === "currency" && /* @__PURE__ */ jsxs("div", { className: "md:col-span-2", children: [
          /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Options source" }),
          /* @__PURE__ */ jsx("div", { className: "rounded border bg-muted px-2 py-1 text-xs text-muted-foreground", children: "/api/currencies/options" })
        ] }),
        (local.kind === "integer" || local.kind === "float") && /* @__PURE__ */ jsxs("div", { className: "md:col-span-2", children: [
          /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Units (optional)" }),
          /* @__PURE__ */ jsx(
            "input",
            {
              className: "border rounded w-full px-2 py-1 text-sm",
              placeholder: "kg, cm, etc.",
              value: typeof local.configJson?.unit === "string" ? local.configJson.unit : "",
              onChange: (event) => apply({ configJson: { ...local.configJson || {}, unit: event.target.value } }),
              onBlur: commit
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-3 pt-3 border-t", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-2", children: [
          /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", children: "Validation rules" }),
          /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              className: "text-xs",
              onClick: () => {
                apply((current) => {
                  const list = Array.isArray(current.configJson?.validation) ? [...current.configJson.validation] : [];
                  list.push({ rule: "required", message: "This field is required" });
                  return { configJson: { ...current.configJson || {}, validation: list } };
                }, true);
              },
              children: [
                /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
                "Add rule"
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          (Array.isArray(local.configJson?.validation) ? local.configJson.validation : []).map((rule, index) => /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-12 gap-2 items-center", children: [
            /* @__PURE__ */ jsx("div", { className: "md:col-span-3", children: /* @__PURE__ */ jsxs(
              Select,
              {
                value: rule?.rule || "required",
                onValueChange: (value) => {
                  const nextRule = value;
                  apply((current) => {
                    const list = Array.isArray(current.configJson?.validation) ? [...current.configJson.validation] : [];
                    const existing = list[index] || {};
                    list[index] = { ...existing, rule: nextRule, message: existing.message || rule?.message || "" };
                    return { configJson: { ...current.configJson || {}, validation: list } };
                  }, true);
                },
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                  /* @__PURE__ */ jsxs(SelectContent, { children: [
                    /* @__PURE__ */ jsx(SelectItem, { value: "required", children: "required" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "date", children: "date" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "integer", children: "integer" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "float", children: "float" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "lt", children: "lt" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "lte", children: "lte" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "gt", children: "gt" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "gte", children: "gte" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "eq", children: "eq" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "ne", children: "ne" }),
                    /* @__PURE__ */ jsx(SelectItem, { value: "regex", children: "regex" })
                  ] })
                ]
              }
            ) }),
            /* @__PURE__ */ jsx("div", { className: "md:col-span-4", children: /* @__PURE__ */ jsx(
              "input",
              {
                className: "border rounded w-full px-2 py-1 text-sm",
                placeholder: rule?.rule === "regex" ? "Pattern (e.g. ^[a-z]+$)" : ["lt", "lte", "gt", "gte"].includes(rule?.rule) ? "Number" : "\u2014",
                value: rule?.param ?? "",
                onChange: (event) => {
                  const value = ["lt", "lte", "gt", "gte"].includes(rule?.rule) ? Number(event.target.value) : event.target.value;
                  apply((current) => {
                    const list = Array.isArray(current.configJson?.validation) ? [...current.configJson.validation] : [];
                    const existing = list[index] || {};
                    list[index] = { ...existing, ...rule, param: value };
                    return { configJson: { ...current.configJson || {}, validation: list } };
                  });
                },
                onBlur: commit,
                disabled: rule?.rule === "required" || rule?.rule === "date" || rule?.rule === "integer" || rule?.rule === "float"
              }
            ) }),
            /* @__PURE__ */ jsx("div", { className: "md:col-span-4", children: /* @__PURE__ */ jsx(
              "input",
              {
                className: "border rounded w-full px-2 py-1 text-sm",
                placeholder: "Error message",
                value: rule?.message || "",
                onChange: (event) => {
                  const message = event.target.value;
                  apply((current) => {
                    const list = Array.isArray(current.configJson?.validation) ? [...current.configJson.validation] : [];
                    const existing = list[index] || {};
                    list[index] = { ...existing, ...rule, message };
                    return { configJson: { ...current.configJson || {}, validation: list } };
                  });
                },
                onBlur: commit
              }
            ) }),
            /* @__PURE__ */ jsx("div", { className: "md:col-span-1 flex justify-end", children: /* @__PURE__ */ jsx(
              IconButton,
              {
                variant: "outline",
                size: "sm",
                "aria-label": "Remove rule",
                onClick: () => {
                  apply((current) => {
                    const list = Array.isArray(current.configJson?.validation) ? [...current.configJson.validation] : [];
                    list.splice(index, 1);
                    return { configJson: { ...current.configJson || {}, validation: list } };
                  }, true);
                },
                children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
              }
            ) })
          ] }, index)),
          (!Array.isArray(local.configJson?.validation) || local.configJson.validation.length === 0) && /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: "No validation rules defined." })
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "mt-3", children: (() => {
        const Editor = FieldRegistry.getDefEditor(local.kind);
        if (!Editor) return null;
        return /* @__PURE__ */ jsx(
          Editor,
          {
            def: { key: local.key, kind: local.kind, configJson: local.configJson },
            onChange: (patch) => apply({ configJson: { ...local.configJson || {}, ...patch || {} } }, true)
          }
        );
      })() }),
      (() => {
        if (local.kind === "dictionary") return null;
        if (local.kind === "relation" || local.kind === "attachment") return null;
        const currentDefault = local.configJson?.defaultValue;
        if (local.kind === "boolean") {
          const boolDefault = currentDefault === true ? "true" : currentDefault === false ? "false" : "";
          return /* @__PURE__ */ jsxs("div", { className: "mt-3", children: [
            /* @__PURE__ */ jsx("label", { className: "text-xs", children: t("entities.customFields.fields.defaultValue", "Default value") }),
            /* @__PURE__ */ jsxs(
              "select",
              {
                className: "border rounded w-full px-2 py-1 text-sm",
                value: boolDefault,
                onChange: (event) => {
                  const raw = event.target.value;
                  const value = raw === "true" ? true : raw === "false" ? false : void 0;
                  apply({ configJson: { ...local.configJson || {}, defaultValue: value } }, true);
                },
                children: [
                  /* @__PURE__ */ jsx("option", { value: "", children: t("entities.customFields.fields.defaultValueNone", "No default") }),
                  /* @__PURE__ */ jsx("option", { value: "true", children: t("entities.customFields.fields.defaultValueTrue", "Checked (true)") }),
                  /* @__PURE__ */ jsx("option", { value: "false", children: t("entities.customFields.fields.defaultValueFalse", "Unchecked (false)") })
                ]
              }
            )
          ] });
        }
        if (local.kind === "select" && !local.configJson?.multi) {
          const opts = normalizeCustomFieldOptions(local.configJson?.options || []);
          if (opts.length > 0) {
            return /* @__PURE__ */ jsxs("div", { className: "mt-3", children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs", children: t("entities.customFields.fields.defaultValue", "Default value") }),
              /* @__PURE__ */ jsxs(
                "select",
                {
                  className: "border rounded w-full px-2 py-1 text-sm",
                  value: typeof currentDefault === "string" || typeof currentDefault === "number" ? String(currentDefault) : "",
                  onChange: (event) => {
                    const raw = event.target.value;
                    if (!raw) {
                      apply({ configJson: { ...local.configJson || {}, defaultValue: void 0 } }, true);
                      return;
                    }
                    const matched = opts.find((o) => String(o.value) === raw);
                    const typed = matched ? matched.value : raw;
                    apply({ configJson: { ...local.configJson || {}, defaultValue: typed } }, true);
                  },
                  children: [
                    /* @__PURE__ */ jsx("option", { value: "", children: t("entities.customFields.fields.defaultValueNone", "No default") }),
                    opts.map((option) => /* @__PURE__ */ jsx("option", { value: String(option.value), children: option.label }, String(option.value)))
                  ]
                }
              )
            ] });
          }
        }
        if (local.kind === "integer" || local.kind === "float") {
          return /* @__PURE__ */ jsxs("div", { className: "mt-3", children: [
            /* @__PURE__ */ jsx("label", { className: "text-xs", children: t("entities.customFields.fields.defaultValue", "Default value") }),
            /* @__PURE__ */ jsx(
              "input",
              {
                type: "number",
                step: local.kind === "integer" ? "1" : "any",
                className: "border rounded w-full px-2 py-1 text-sm",
                value: typeof currentDefault === "number" ? String(currentDefault) : "",
                onChange: (event) => {
                  const raw = event.target.value;
                  const parsed = raw === "" ? void 0 : local.kind === "integer" ? parseInt(raw, 10) : parseFloat(raw);
                  const value = parsed !== void 0 && !isNaN(parsed) ? parsed : void 0;
                  apply({ configJson: { ...local.configJson || {}, defaultValue: value } });
                },
                onBlur: commit,
                placeholder: t("entities.customFields.fields.defaultValuePlaceholder", "No default")
              }
            )
          ] });
        }
        if (["text", "multiline", "date", "datetime", "currency"].includes(local.kind)) {
          return /* @__PURE__ */ jsxs("div", { className: "mt-3", children: [
            /* @__PURE__ */ jsx("label", { className: "text-xs", children: t("entities.customFields.fields.defaultValue", "Default value") }),
            /* @__PURE__ */ jsx(
              "input",
              {
                className: "border rounded w-full px-2 py-1 text-sm",
                value: typeof currentDefault === "string" ? currentDefault : "",
                onChange: (event) => {
                  const value = event.target.value;
                  apply({ configJson: { ...local.configJson || {}, defaultValue: value || void 0 } });
                },
                onBlur: commit,
                placeholder: t("entities.customFields.fields.defaultValuePlaceholder", "No default")
              }
            )
          ] });
        }
        return null;
      })(),
      /* @__PURE__ */ jsxs("div", { className: "mt-3 pt-2 border-t flex flex-wrap items-center gap-4", children: [
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("entities.customFields.fields.visibility", "Visibility:") }),
        /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2 text-xs", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              checked: local.configJson?.listVisible !== false,
              onChange: (event) => {
                apply({ configJson: { ...local.configJson || {}, listVisible: event.target.checked } }, true);
              }
            }
          ),
          t("entities.customFields.fields.listVisible", "List")
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2 text-xs", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              checked: !!local.configJson?.filterable,
              onChange: (event) => {
                apply({ configJson: { ...local.configJson || {}, filterable: event.target.checked } }, true);
              }
            }
          ),
          t("entities.customFields.fields.filterable", "Filter")
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2 text-xs", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              checked: local.configJson?.formEditable !== false,
              onChange: (event) => {
                apply({ configJson: { ...local.configJson || {}, formEditable: event.target.checked } }, true);
              }
            }
          ),
          t("entities.customFields.fields.formEditable", "Form")
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2 text-xs", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              checked: !!local.configJson?.encrypted,
              onChange: (event) => {
                apply({ configJson: { ...local.configJson || {}, encrypted: event.target.checked } }, true);
              }
            }
          ),
          t("entities.customFields.fields.encrypted", "Encrypted")
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      Dialog,
      {
        open: optionDialogOpen,
        onOpenChange: (open) => {
          setOptionDialogOpen(open);
          if (!open) resetOptionDialog();
        },
        children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-sm", children: [
          /* @__PURE__ */ jsxs(DialogHeader, { children: [
            /* @__PURE__ */ jsx(DialogTitle, { children: "Add option" }),
            /* @__PURE__ */ jsx(DialogDescription, { children: "Provide the stored value and optional label shown to users." })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-4 py-2", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Value" }),
              /* @__PURE__ */ jsx(
                "input",
                {
                  className: "mt-1 w-full rounded border px-2 py-1 text-sm font-mono",
                  placeholder: "unique_value",
                  value: optionValueDraft,
                  onChange: (event) => {
                    setOptionFormError(null);
                    setOptionValueDraft(event.target.value);
                  }
                }
              ),
              optionFormError ? /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-red-600", children: optionFormError }) : null
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs", children: "Label" }),
              /* @__PURE__ */ jsx(
                "input",
                {
                  className: "mt-1 w-full rounded border px-2 py-1 text-sm",
                  placeholder: "Label shown to users (optional)",
                  value: optionLabelDraft,
                  onChange: (event) => setOptionLabelDraft(event.target.value)
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs(DialogFooter, { children: [
            /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: handleCloseOptionDialog, children: "Cancel" }),
            /* @__PURE__ */ jsx(Button, { size: "sm", onClick: handleAddOption, children: "Add option" })
          ] })
        ] })
      }
    ),
    /* @__PURE__ */ jsx(
      Dialog,
      {
        open: groupDialogOpen,
        onOpenChange: (open) => {
          setGroupDialogOpen(open);
          if (!open) {
            setGroupError(null);
            setEditingGroupCode(null);
            setGroupDraft({ code: "", title: "", hint: "" });
          }
        },
        children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-md", children: [
          /* @__PURE__ */ jsxs(DialogHeader, { children: [
            /* @__PURE__ */ jsx(DialogTitle, { children: editingGroupCode ? "Edit group" : "New group" }),
            /* @__PURE__ */ jsx(DialogDescription, { children: editingGroupCode ? "Update the selected group for this fieldset." : "Add a reusable group for this fieldset." })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Group code" }),
              /* @__PURE__ */ jsx(
                "input",
                {
                  className: "mt-1 w-full rounded border px-2 py-1 text-sm font-mono disabled:cursor-not-allowed disabled:bg-muted/50 disabled:text-muted-foreground",
                  value: groupDraft.code,
                  onChange: (event) => {
                    setGroupDraft((prev) => ({ ...prev, code: event.target.value }));
                    if (groupError) setGroupError(null);
                  },
                  disabled: !!editingGroupCode,
                  placeholder: "e.g. buying_committee"
                }
              ),
              groupError ? /* @__PURE__ */ jsx("div", { className: "text-xs text-red-600 mt-1", children: groupError }) : null
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Label" }),
              /* @__PURE__ */ jsx(
                "input",
                {
                  className: "mt-1 w-full rounded border px-2 py-1 text-sm",
                  value: groupDraft.title,
                  onChange: (event) => setGroupDraft((prev) => ({ ...prev, title: event.target.value })),
                  placeholder: "Buying committee"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Hint" }),
              /* @__PURE__ */ jsx(
                "input",
                {
                  className: "mt-1 w-full rounded border px-2 py-1 text-sm",
                  value: groupDraft.hint,
                  onChange: (event) => setGroupDraft((prev) => ({ ...prev, hint: event.target.value })),
                  placeholder: "Visible to merchandisers"
                }
              )
            ] }),
            currentFieldsetValue && groupOptions.length > 0 ? /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("div", { className: "text-xs font-medium mb-1", children: "Existing groups" }),
              /* @__PURE__ */ jsx("div", { className: "space-y-2 max-h-40 overflow-y-auto", children: groupOptions.map((group) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded border px-3 py-2 text-sm", children: [
                /* @__PURE__ */ jsxs("div", { children: [
                  /* @__PURE__ */ jsx("div", { className: "font-medium", children: group.title || group.code }),
                  /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground font-mono", children: group.code }),
                  group.hint ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: group.hint }) : null
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx(
                    IconButton,
                    {
                      variant: "ghost",
                      size: "xs",
                      className: "text-muted-foreground hover:text-foreground",
                      onClick: () => handleEditGroupEntry(group),
                      "aria-label": `Edit ${group.code}`,
                      children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    IconButton,
                    {
                      variant: "ghost",
                      size: "xs",
                      className: "text-red-500 hover:text-red-600",
                      onClick: () => handleRemoveGroupEntry(group.code),
                      "aria-label": `Delete ${group.code}`,
                      children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
                    }
                  )
                ] })
              ] }, group.code)) })
            ] }) : null
          ] }),
          /* @__PURE__ */ jsxs(DialogFooter, { children: [
            /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => setGroupDialogOpen(false), children: "Cancel" }),
            /* @__PURE__ */ jsx(Button, { size: "sm", onClick: handleGroupDialogSubmit, children: "Save group" })
          ] })
        ] })
      }
    )
  ] });
});
FieldDefinitionCard.displayName = "FieldDefinitionCard";
export {
  FieldDefinitionsEditor
};
//# sourceMappingURL=FieldDefinitionsEditor.js.map
