"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { z } from "zod";
import Link from "next/link";
import { Check, Pencil, Plus } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { extractCustomFieldEntries } from "@open-mercato/shared/lib/crud/custom-fields-client";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { EmailInput } from "@open-mercato/ui/primitives/email-input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { coerceDisplayName, deriveDisplayName, isDerivedDisplayName } from "../lib/displayName.js";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from "@open-mercato/ui/primitives/dialog";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall, apiCallOrThrow, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { PhoneNumberField } from "@open-mercato/ui/backend/inputs/PhoneNumberField";
import { isValidPhoneNumber } from "@open-mercato/shared/lib/phone";
import {
  DictionaryEntrySelect
} from "@open-mercato/core/modules/dictionaries/components/DictionaryEntrySelect";
import { RolesSection } from "./detail/RolesSection.js";
import { useQueryClient } from "@tanstack/react-query";
import { useEmailDuplicateCheck } from "../backend/hooks/useEmailDuplicateCheck.js";
import { lookupPhoneDuplicate } from "../utils/phoneDuplicates.js";
import { CustomerAddressTiles } from "./AddressTiles.js";
import {
  ensureCustomerDictionary,
  invalidateCustomerDictionary
} from "./detail/hooks/useCustomerDictionary.js";
import {
  CUSTOMER_DICTIONARIES_MANAGE_HREF,
  getCustomerDictionaryManageHref
} from "../lib/dictionaries.js";
import { normalizeCustomFieldSubmitValue } from "./detail/customFieldUtils.js";
import { CUSTOMER_PHONE_INVALID_MESSAGE_KEY } from "../data/validators.js";
const metadata = {
  navHidden: true
};
function cn(...values) {
  return values.filter(Boolean).join(" ");
}
const emailValidationSchema = z.string().email();
const EMAIL_CHECK_DEBOUNCE_MS = 350;
const createSectionHeadingField = (id, title) => ({
  id,
  label: "",
  type: "custom",
  layout: "full",
  component: () => /* @__PURE__ */ jsx("div", { className: "mt-4 border-t border-border pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: title })
});
function DictionarySelectField({
  kind,
  value,
  onChange,
  labels,
  selectClassName,
  manageHref,
  allowInlineCreate = false,
  allowAppearance = false,
  showManage = false,
  showLabelInput = true,
  showActiveAppearance = true
}) {
  const t = useT();
  const queryClient = useQueryClient();
  const scopeVersion = useOrganizationScopeVersion();
  const translate = React.useCallback(
    (key, fallback) => {
      const result = t(key);
      return result === key ? fallback : result;
    },
    [t]
  );
  const appearanceLabels = React.useMemo(
    () => ({
      colorLabel: translate("customers.config.dictionaries.dialog.colorLabel", "Color"),
      colorHelp: translate("customers.config.dictionaries.dialog.colorHelp", "Pick a highlight color for this entry."),
      colorClearLabel: translate("customers.config.dictionaries.dialog.colorClear", "Remove color"),
      iconLabel: translate("customers.config.dictionaries.dialog.iconLabel", "Icon or emoji"),
      iconPlaceholder: translate(
        "customers.config.dictionaries.dialog.iconPlaceholder",
        "Type an emoji or pick one of the suggestions."
      ),
      iconPickerTriggerLabel: translate("customers.config.dictionaries.dialog.iconBrowse", "Browse icons and emojis"),
      iconSearchPlaceholder: translate(
        "customers.config.dictionaries.dialog.iconSearchPlaceholder",
        "Search icons or emojis\u2026"
      ),
      iconSearchEmptyLabel: translate(
        "customers.config.dictionaries.dialog.iconSearchEmpty",
        "No icons match your search."
      ),
      iconSuggestionsLabel: translate("customers.config.dictionaries.dialog.iconSuggestions", "Suggestions"),
      iconClearLabel: translate("customers.config.dictionaries.dialog.iconClear", "Remove icon"),
      previewEmptyLabel: translate("customers.config.dictionaries.dialog.previewEmpty", "No appearance selected")
    }),
    [translate]
  );
  const fetchOptions = React.useCallback(async () => {
    const data = await ensureCustomerDictionary(queryClient, kind, scopeVersion);
    return data.entries.map((entry) => ({
      value: entry.value,
      label: entry.label,
      color: entry.color ?? null,
      icon: entry.icon ?? null
    }));
  }, [kind, queryClient, scopeVersion]);
  const createOption = React.useCallback(
    async (input) => {
      const call = await apiCall(
        `/api/customers/dictionaries/${kind}`,
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            value: input.value,
            label: input.label ?? input.value,
            color: input.color ?? void 0,
            icon: input.icon ?? void 0
          })
        }
      );
      const payload = call.result ?? {};
      if (!call.ok) {
        const message = typeof payload.error === "string" ? payload.error : labels.errorSave;
        throw new Error(message);
      }
      await invalidateCustomerDictionary(queryClient, kind);
      const valueCreated = typeof payload.value === "string" ? payload.value : input.value;
      const label = typeof payload.label === "string" && payload.label.trim().length ? payload.label.trim() : valueCreated;
      const color = typeof payload.color === "string" && payload.color.trim().startsWith("#") ? payload.color.trim() : null;
      const icon = typeof payload.icon === "string" && payload.icon.trim().length ? payload.icon.trim() : null;
      return { value: valueCreated, label, color, icon };
    },
    [kind, labels.errorSave, queryClient]
  );
  return /* @__PURE__ */ jsx(
    DictionaryEntrySelect,
    {
      value,
      onChange,
      fetchOptions,
      createOption,
      labels,
      manageHref: manageHref ?? getCustomerDictionaryManageHref(kind),
      selectClassName,
      allowInlineCreate,
      allowAppearance,
      showManage,
      showLabelInput,
      sortOptions: "none",
      showActiveAppearance
    }
  );
}
const createPrimaryEmailField = (t) => ({
  id: "primaryEmail",
  label: t("customers.people.form.primaryEmail"),
  type: "custom",
  component: function PrimaryEmailField({ value, setValue, error, autoFocus, disabled, recordId }) {
    const [inputValue, setInputValue] = React.useState(() => typeof value === "string" ? value : "");
    const trimmedInput = inputValue.trim();
    const isValidEmail = React.useMemo(
      () => !!trimmedInput.length && emailValidationSchema.safeParse(trimmedInput).success,
      [trimmedInput]
    );
    const { duplicate, checking } = useEmailDuplicateCheck(inputValue, {
      recordId: typeof recordId === "string" ? recordId : null,
      disabled: disabled || !!error || !isValidEmail,
      debounceMs: EMAIL_CHECK_DEBOUNCE_MS,
      matchMode: "prefix"
    });
    React.useEffect(() => {
      setInputValue(typeof value === "string" ? value : "");
    }, [value]);
    return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(
        EmailInput,
        {
          value: inputValue,
          onChange: (event) => {
            const nextValue = event.target.value;
            setInputValue(nextValue);
            setValue(nextValue);
          },
          placeholder: t("customers.people.form.primaryEmailPlaceholder", "name@example.com"),
          spellCheck: false,
          autoFocus,
          "data-crud-focus-target": "",
          disabled
        }
      ),
      !error && duplicate ? /* @__PURE__ */ jsxs("p", { className: "text-xs text-status-warning-text", children: [
        t("customers.people.form.emailDuplicateNotice", void 0, { name: duplicate.displayName }),
        " ",
        /* @__PURE__ */ jsx(Link, { className: "font-medium text-primary underline underline-offset-2", href: `/backend/customers/people-v2/${duplicate.id}`, children: t("customers.people.form.emailDuplicateLink") })
      ] }) : null,
      !error && !duplicate && checking ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customers.people.form.emailChecking") }) : null
    ] });
  }
});
const dictionaryFieldDefinitions = [
  {
    id: "status",
    kind: "statuses",
    labelKey: "customers.people.form.status",
    placeholderKey: "customers.people.form.status.placeholder",
    addLabelKey: "customers.people.form.dictionary.addStatus",
    promptKey: "customers.people.form.dictionary.promptStatus",
    dialogTitleKey: "customers.people.form.dictionary.dialogTitleStatus",
    layout: "half"
  },
  {
    id: "lifecycleStage",
    kind: "lifecycle-stages",
    labelKey: "customers.people.form.lifecycleStage",
    placeholderKey: "customers.people.form.lifecycleStage.placeholder",
    addLabelKey: "customers.people.form.dictionary.addLifecycleStage",
    promptKey: "customers.people.form.dictionary.promptLifecycleStage",
    dialogTitleKey: "customers.people.form.dictionary.dialogTitleLifecycleStage",
    layout: "half"
  },
  {
    id: "source",
    kind: "sources",
    labelKey: "customers.people.form.source",
    placeholderKey: "customers.people.form.source.placeholder",
    addLabelKey: "customers.people.form.dictionary.addSource",
    promptKey: "customers.people.form.dictionary.promptSource",
    dialogTitleKey: "customers.people.form.dictionary.dialogTitleSource",
    layout: "half"
  }
];
const buildDictionaryLabels = (t, definition) => ({
  placeholder: t(definition.placeholderKey),
  addLabel: t(definition.addLabelKey),
  addPrompt: t(definition.promptKey),
  dialogTitle: t(definition.dialogTitleKey),
  valueLabel: t("customers.people.form.dictionary.valueLabel", "Value"),
  valuePlaceholder: t("customers.people.form.dictionary.valuePlaceholder", "Value"),
  labelLabel: t("customers.config.dictionaries.dialog.labelLabel", "Label"),
  labelPlaceholder: t("customers.people.form.dictionary.labelPlaceholder", "Display name shown in UI"),
  emptyError: t("customers.people.form.dictionary.errorRequired"),
  cancelLabel: t("customers.people.form.dictionary.cancel"),
  saveLabel: t("customers.people.form.dictionary.save"),
  successCreateLabel: void 0,
  errorLoad: t("customers.people.form.dictionary.errorLoad"),
  errorSave: t("customers.people.form.dictionary.error"),
  loadingLabel: t("customers.people.form.dictionary.loading"),
  manageTitle: t("customers.people.form.dictionary.manage")
});
const companyDictionaryFieldDefinitions = [
  {
    id: "status",
    kind: "statuses",
    labelKey: "customers.companies.form.status",
    placeholderKey: "customers.companies.form.status.placeholder",
    addLabelKey: "customers.companies.form.dictionary.addStatus",
    promptKey: "customers.companies.form.dictionary.promptStatus",
    dialogTitleKey: "customers.companies.form.dictionary.dialogTitleStatus",
    layout: "third"
  },
  {
    id: "lifecycleStage",
    kind: "lifecycle-stages",
    labelKey: "customers.companies.form.lifecycleStage",
    placeholderKey: "customers.companies.form.lifecycleStage.placeholder",
    addLabelKey: "customers.companies.form.dictionary.addLifecycleStage",
    promptKey: "customers.companies.form.dictionary.promptLifecycleStage",
    dialogTitleKey: "customers.companies.form.dictionary.dialogTitleLifecycleStage",
    layout: "third"
  },
  {
    id: "source",
    kind: "sources",
    labelKey: "customers.companies.form.source",
    placeholderKey: "customers.companies.form.source.placeholder",
    addLabelKey: "customers.companies.form.dictionary.addSource",
    promptKey: "customers.companies.form.dictionary.promptSource",
    dialogTitleKey: "customers.companies.form.dictionary.dialogTitleSource",
    layout: "third"
  }
];
const createPrimaryPhoneField = (t) => ({
  id: "primaryPhone",
  label: t("customers.people.form.primaryPhone"),
  type: "custom",
  component: function PrimaryPhoneField({ value, setValue, error, autoFocus, disabled, recordId }) {
    const currentRecordId = React.useMemo(() => typeof recordId === "string" ? recordId : null, [recordId]);
    const duplicateLookup = React.useCallback(
      async (digits) => {
        if (disabled || error) return null;
        return lookupPhoneDuplicate(digits, { recordId: currentRecordId });
      },
      [currentRecordId, disabled, error]
    );
    return /* @__PURE__ */ jsx(
      PhoneNumberField,
      {
        value: typeof value === "string" ? value : null,
        onValueChange: (next) => setValue(typeof next === "string" ? next : ""),
        externalError: error,
        autoFocus,
        disabled,
        placeholder: t("customers.people.form.primaryPhonePlaceholder", "+1 555 123 4567"),
        checkingLabel: t("customers.people.form.phoneChecking"),
        duplicateLabel: (match) => t("customers.people.form.phoneDuplicateNotice", void 0, { name: match.label }),
        duplicateLinkLabel: t("customers.people.form.phoneDuplicateLink"),
        invalidLabel: t("customers.people.form.primaryPhone.invalid", "Enter a valid phone number with country code (e.g. +1 212 555 1234)"),
        minDigits: 7,
        onDuplicateLookup: !disabled && !error ? duplicateLookup : void 0
      }
    );
  }
});
const blankToUndefined = (value) => {
  if (typeof value !== "string") return void 0;
  const trimmed = value.trim();
  return trimmed.length ? trimmed : void 0;
};
function mergeCompanyOptions(options, selected) {
  if (!selected) return options;
  if (options.some((option) => option.value === selected.value)) return options;
  return [selected, ...options];
}
function normalizeCompanyOption(raw) {
  if (!raw || typeof raw !== "object") return null;
  const candidate = raw;
  const id = typeof candidate.id === "string" ? candidate.id : null;
  if (!id) return null;
  const displayName = typeof candidate.display_name === "string" && candidate.display_name.trim().length ? candidate.display_name.trim() : typeof candidate.displayName === "string" && candidate.displayName.trim().length ? candidate.displayName.trim() : null;
  if (!displayName) return null;
  return { value: id, label: displayName };
}
function CompanySelectField({ value, onChange, labels }) {
  const [options, setOptions] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [newCompany, setNewCompany] = React.useState("");
  const [saving, setSaving] = React.useState(false);
  const [formError, setFormError] = React.useState(null);
  const loadCompanyOption = React.useCallback(
    async (companyId) => {
      const payload = await readApiResultOrThrow(
        `/api/customers/companies?id=${encodeURIComponent(companyId)}&pageSize=1`,
        void 0,
        { errorMessage: labels.errorLoad }
      );
      const items = Array.isArray(payload?.items) ? payload.items : [];
      return items.map((item) => normalizeCompanyOption(item)).find((option) => option?.value === companyId) ?? null;
    },
    [labels.errorLoad]
  );
  const loadOptions = React.useCallback(async () => {
    setLoading(true);
    try {
      const payload = await readApiResultOrThrow(
        "/api/customers/companies?pageSize=100&sortField=name&sortDir=asc",
        void 0,
        { errorMessage: labels.errorLoad }
      );
      const items = Array.isArray(payload?.items) ? payload.items : [];
      const normalized = items.map((item) => normalizeCompanyOption(item)).filter((item) => item !== null).sort(
        (a, b) => a.label.localeCompare(b.label, void 0, { sensitivity: "base" })
      );
      const selected = value && !normalized.some((option) => option.value === value) ? await loadCompanyOption(value).catch(() => null) : null;
      setOptions(mergeCompanyOptions(normalized, selected));
    } catch (err) {
      const message = err instanceof Error ? err.message : labels.errorLoad;
      flash(message, "error");
      setOptions([]);
    } finally {
      setLoading(false);
    }
  }, [labels.errorLoad, loadCompanyOption, value]);
  React.useEffect(() => {
    loadOptions().catch(() => {
    });
  }, [loadOptions]);
  React.useEffect(() => {
    if (!value || options.some((option) => option.value === value)) return;
    loadCompanyOption(value).then((selected) => {
      setOptions((current) => mergeCompanyOptions(current, selected));
    }).catch(() => {
    });
  }, [loadCompanyOption, options, value]);
  const handleDialogChange = React.useCallback((open) => {
    setDialogOpen(open);
    if (!open) {
      setNewCompany("");
      setFormError(null);
      setSaving(false);
    }
  }, []);
  const handleDialogSubmit = React.useCallback(async () => {
    if (saving) return;
    const trimmed = newCompany.trim();
    if (!trimmed) {
      setFormError(labels.emptyError);
      return;
    }
    setSaving(true);
    try {
      const call = await apiCallOrThrow(
        "/api/customers/companies",
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ displayName: trimmed })
        },
        { errorMessage: labels.errorSave }
      );
      const payload = call.result ?? {};
      const createdId = typeof payload?.id === "string" ? payload.id : typeof payload?.entityId === "string" ? payload.entityId : null;
      await loadOptions();
      if (createdId) {
        onChange(createdId);
      }
      setDialogOpen(false);
      setNewCompany("");
      setFormError(null);
    } catch (err) {
      const message = err instanceof Error ? err.message : labels.errorSave;
      flash(message, "error");
    } finally {
      setSaving(false);
    }
  }, [labels.emptyError, labels.errorSave, loadOptions, newCompany, onChange, saving]);
  const handleInputKeyDown = React.useCallback(
    (event) => {
      if (event.key === "Enter") {
        event.preventDefault();
        handleDialogSubmit().catch(() => {
        });
      }
    },
    [handleDialogSubmit]
  );
  const disabled = loading || saving;
  const selectedOption = value ? options.find((option) => option.value === value) : null;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsxs(
        Select,
        {
          value: value || void 0,
          onValueChange: (next) => onChange(next || void 0),
          disabled: loading,
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: labels.placeholder, children: selectedOption?.label }) }),
            /* @__PURE__ */ jsx(SelectContent, { children: options.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.value, children: option.label }, option.value)) })
          ]
        }
      ),
      /* @__PURE__ */ jsxs(Dialog, { open: dialogOpen, onOpenChange: handleDialogChange, children: [
        /* @__PURE__ */ jsx(DialogTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "icon",
            disabled,
            "aria-label": labels.addLabel,
            title: labels.addLabel,
            children: /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4", "aria-hidden": true })
          }
        ) }),
        /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-sm", children: [
          /* @__PURE__ */ jsxs(DialogHeader, { children: [
            /* @__PURE__ */ jsx(DialogTitle, { children: labels.dialogTitle }),
            labels.addPrompt ? /* @__PURE__ */ jsx(DialogDescription, { children: labels.addPrompt }) : null
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
            /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", children: labels.inputLabel }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  placeholder: labels.inputPlaceholder,
                  value: newCompany,
                  onChange: (event) => {
                    setNewCompany(event.target.value);
                    if (formError) setFormError(null);
                  },
                  onKeyDown: handleInputKeyDown,
                  autoFocus: true,
                  disabled: saving
                }
              )
            ] }),
            formError ? /* @__PURE__ */ jsx("p", { className: "text-sm text-status-error-text", children: formError }) : null,
            /* @__PURE__ */ jsxs(DialogFooter, { children: [
              /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => setDialogOpen(false), disabled: saving, children: labels.cancelLabel }),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  onClick: () => {
                    handleDialogSubmit().catch(() => {
                    });
                  },
                  disabled: saving || !newCompany.trim(),
                  children: saving ? `${labels.saveLabel}\u2026` : labels.saveLabel
                }
              )
            ] })
          ] })
        ] })
      ] })
    ] }),
    loading ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: labels.loadingLabel }) : null
  ] });
}
const createPersonFormSchema = () => z.object({
  displayName: z.string().trim().min(1),
  firstName: z.string().trim().min(1),
  lastName: z.string().trim().min(1),
  jobTitle: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  primaryEmail: z.string().trim().email().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val),
  primaryPhone: z.string().trim().max(50).refine((value) => isValidPhoneNumber(value), { message: CUSTOMER_PHONE_INVALID_MESSAGE_KEY }).optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  status: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  lifecycleStage: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  source: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  description: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  companyEntityId: z.string().trim().uuid().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional()
}).passthrough();
const createDisplayNameSection = (t) => function DisplayNameSection({ values, setValue, errors }) {
  const [editing, setEditing] = React.useState(false);
  const [manualOverride, setManualOverride] = React.useState(() => {
    const current = typeof values.displayName === "string" ? values.displayName : "";
    const firstInit = typeof values.firstName === "string" ? values.firstName : "";
    const lastInit = typeof values.lastName === "string" ? values.lastName : "";
    return !isDerivedDisplayName(current, firstInit, lastInit);
  });
  const first = typeof values.firstName === "string" ? values.firstName.trim() : "";
  const last = typeof values.lastName === "string" ? values.lastName.trim() : "";
  const derived = React.useMemo(() => deriveDisplayName(first, last), [first, last]);
  React.useEffect(() => {
    if (!manualOverride) {
      const target = derived || "";
      const current = typeof values.displayName === "string" ? values.displayName : "";
      if (current !== target) {
        setValue("displayName", target);
      }
    }
  }, [manualOverride, derived, setValue, values.displayName]);
  const currentValue = typeof values.displayName === "string" ? values.displayName : "";
  const previewValue = currentValue || derived;
  const placeholder = t("customers.people.form.displayNamePreview.empty");
  const error = errors.displayName;
  const toggleEditing = () => {
    if (!editing && !manualOverride) {
      const target = derived || previewValue || "";
      setValue("displayName", target);
      setManualOverride(true);
    }
    setEditing((state) => !state);
  };
  const handleChange = (event) => {
    if (!manualOverride) setManualOverride(true);
    setValue("displayName", event.target.value);
  };
  const handleReset = () => {
    setManualOverride(false);
    setEditing(false);
  };
  return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-muted/30 p-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsx("div", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", children: t("customers.people.form.displayNamePreview") }),
        editing ? /* @__PURE__ */ jsxs("div", { className: "mt-2 space-y-2", children: [
          /* @__PURE__ */ jsx(
            Input,
            {
              value: currentValue,
              onChange: handleChange,
              placeholder: t("customers.people.form.displayName.placeholder")
            }
          ),
          error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-status-error-text", children: error }) : null
        ] }) : /* @__PURE__ */ jsx("div", { className: "mt-1 text-base font-medium", children: previewValue || placeholder })
      ] }),
      /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: toggleEditing, children: editing ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(Check, { className: "mr-2 h-4 w-4" }),
        t("customers.people.form.displayName.done")
      ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(Pencil, { className: "mr-2 h-4 w-4" }),
        t("customers.people.form.displayName.edit")
      ] }) })
    ] }),
    manualOverride ? /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: handleReset, disabled: !derived, children: t("customers.people.form.displayName.reset") }) }) : null
  ] });
};
const createPersonFormFields = (t) => {
  const contactSection = createSectionHeadingField("__contactInformationSection", t("customers.people.form.sections.contactInformation"));
  const companySection = createSectionHeadingField("__companyInformationSection", t("customers.people.form.sections.companyInformation"));
  const dictionaryFields = dictionaryFieldDefinitions.map((definition) => ({
    id: definition.id,
    label: t(definition.labelKey),
    type: "custom",
    layout: definition.layout ?? "third",
    component: ({ value, setValue }) => /* @__PURE__ */ jsx(
      DictionarySelectField,
      {
        kind: definition.kind,
        value: typeof value === "string" ? value : void 0,
        onChange: (next) => setValue(next),
        labels: buildDictionaryLabels(t, definition),
        allowInlineCreate: true,
        allowAppearance: true,
        showManage: true
      }
    )
  }));
  return [
    { id: "displayName", label: t("customers.people.form.displayName.label"), type: "text", required: true },
    { id: "firstName", label: t("customers.people.form.firstName"), type: "text", required: true, layout: "half" },
    { id: "lastName", label: t("customers.people.form.lastName"), type: "text", required: true, layout: "half" },
    {
      id: "jobTitle",
      label: t("customers.people.form.jobTitle", "Job title"),
      type: "custom",
      layout: "half",
      component: ({ value, setValue }) => /* @__PURE__ */ jsx(
        DictionarySelectField,
        {
          kind: "job-titles",
          value: typeof value === "string" ? value : void 0,
          onChange: (next) => setValue(next),
          labels: {
            placeholder: t("customers.people.form.jobTitle.placeholder", "Select a job title"),
            addLabel: t("customers.people.form.dictionary.addJobTitle", "Add job title"),
            addPrompt: t("customers.people.form.dictionary.promptJobTitle", "Enter a new job title"),
            dialogTitle: t("customers.people.form.dictionary.dialogTitleJobTitle", "Add job title"),
            valueLabel: t("customers.people.form.dictionary.valueLabel", "Value"),
            valuePlaceholder: t("customers.people.form.dictionary.valuePlaceholder", "Value"),
            labelLabel: t("customers.config.dictionaries.dialog.labelLabel", "Label"),
            labelPlaceholder: t("customers.people.form.dictionary.labelPlaceholder", "Display name shown in UI"),
            emptyError: t("customers.people.form.dictionary.errorRequired"),
            cancelLabel: t("customers.people.form.dictionary.cancel"),
            saveLabel: t("customers.people.form.dictionary.save"),
            successCreateLabel: void 0,
            errorLoad: t("customers.people.form.dictionary.errorLoad"),
            errorSave: t("customers.people.form.dictionary.error"),
            loadingLabel: t("customers.people.form.dictionary.loading"),
            manageTitle: t("customers.people.form.dictionary.manage")
          },
          allowInlineCreate: true,
          allowAppearance: true,
          showManage: true
        }
      )
    },
    contactSection,
    createPrimaryEmailField(t),
    createPrimaryPhoneField(t),
    companySection,
    {
      id: "companyEntityId",
      label: t("customers.people.form.company"),
      type: "custom",
      layout: "half",
      component: ({ value, setValue }) => /* @__PURE__ */ jsx(
        CompanySelectField,
        {
          value: typeof value === "string" ? value : void 0,
          onChange: (next) => setValue(next),
          labels: {
            placeholder: t("customers.people.form.company.placeholder"),
            addLabel: t("customers.people.form.company.add"),
            addPrompt: t("customers.people.form.company.prompt"),
            dialogTitle: t("customers.people.form.company.dialogTitle"),
            inputLabel: t("customers.people.form.company.inputLabel"),
            inputPlaceholder: t("customers.people.form.company.inputPlaceholder"),
            emptyError: t("customers.people.form.dictionary.errorRequired"),
            cancelLabel: t("customers.people.form.dictionary.cancel"),
            saveLabel: t("customers.people.form.dictionary.save"),
            errorLoad: t("customers.people.form.dictionary.errorLoad"),
            errorSave: t("customers.people.form.dictionary.error"),
            loadingLabel: t("customers.people.form.company.loading")
          }
        }
      )
    },
    ...dictionaryFields,
    { id: "description", label: t("customers.people.form.description"), type: "textarea" },
    {
      id: "addresses",
      label: "",
      type: "custom",
      layout: "full",
      component: ({ value, setValue }) => {
        const addresses = Array.isArray(value) ? value : [];
        return /* @__PURE__ */ jsx(
          CustomerAddressTiles,
          {
            addresses,
            t,
            emptyLabel: t("customers.people.detail.empty.addresses"),
            gridClassName: "grid gap-4 min-[480px]:grid-cols-1 xl:grid-cols-2",
            showCoordinateFields: true,
            onCreate: async (payload) => {
              const nextId = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `tmp-${Math.random().toString(36).slice(2)}`;
              const next = {
                id: nextId,
                name: payload.name ?? void 0,
                purpose: payload.purpose ?? void 0,
                companyName: payload.companyName ?? void 0,
                addressLine1: payload.addressLine1,
                addressLine2: payload.addressLine2 ?? void 0,
                buildingNumber: payload.buildingNumber ?? void 0,
                flatNumber: payload.flatNumber ?? void 0,
                city: payload.city ?? void 0,
                region: payload.region ?? void 0,
                postalCode: payload.postalCode ?? void 0,
                country: payload.country ?? void 0,
                latitude: payload.latitude ?? void 0,
                longitude: payload.longitude ?? void 0,
                isPrimary: payload.isPrimary ?? false
              };
              const current = Array.isArray(addresses) ? addresses : [];
              const nextAddresses = next.isPrimary === true ? [next, ...current.map((item) => ({ ...item, isPrimary: false }))] : [next, ...current];
              setValue(nextAddresses);
            },
            onUpdate: async (id, payload) => {
              const current = Array.isArray(addresses) ? addresses : [];
              const updated = current.map((item) => {
                if (item.id !== id) {
                  return payload.isPrimary ? { ...item, isPrimary: false } : item;
                }
                return {
                  ...item,
                  name: payload.name ?? null,
                  purpose: payload.purpose ?? null,
                  companyName: payload.companyName ?? null,
                  addressLine1: payload.addressLine1,
                  addressLine2: payload.addressLine2 ?? null,
                  buildingNumber: payload.buildingNumber ?? null,
                  flatNumber: payload.flatNumber ?? null,
                  city: payload.city ?? null,
                  region: payload.region ?? null,
                  postalCode: payload.postalCode ?? null,
                  country: payload.country ?? null,
                  latitude: payload.latitude ?? null,
                  longitude: payload.longitude ?? null,
                  isPrimary: payload.isPrimary ?? false
                };
              });
              setValue(updated);
            },
            onDelete: async (id) => {
              const current = Array.isArray(addresses) ? addresses : [];
              setValue(current.filter((item) => item.id !== id));
            }
          }
        );
      }
    }
  ];
};
const createPersonFormGroups = (t) => [
  {
    id: "details",
    title: t("customers.people.form.groups.details"),
    column: 1,
    component: createDisplayNameSection(t),
    fields: [
      "firstName",
      "lastName",
      "__contactInformationSection",
      "primaryEmail",
      "primaryPhone",
      "__companyInformationSection",
      "jobTitle",
      "companyEntityId",
      "status",
      "lifecycleStage",
      "source"
    ]
  },
  {
    id: "addresses",
    title: t("customers.people.form.groups.addresses"),
    column: 1,
    fields: ["addresses"]
  },
  {
    id: "notes",
    title: t("customers.people.form.groups.notes"),
    column: 2,
    fields: ["description"]
  },
  {
    id: "customFields",
    title: t("customers.people.form.groups.custom"),
    column: 2,
    kind: "customFields"
  }
];
function buildPersonPayload(values, organizationId) {
  const payload = {};
  const displayNameValue = typeof values.displayName === "string" ? values.displayName.trim() : "";
  if (!displayNameValue) {
    throw new Error("DISPLAY_NAME_REQUIRED");
  }
  payload.displayName = displayNameValue;
  payload.firstName = typeof values.firstName === "string" ? values.firstName.trim() : "";
  payload.lastName = typeof values.lastName === "string" ? values.lastName.trim() : "";
  const assign = (key, val) => {
    if (val === null) {
      payload[key] = null;
      return;
    }
    const normalized = blankToUndefined(val);
    if (normalized !== void 0) payload[key] = normalized;
  };
  assign("jobTitle", typeof values.jobTitle === "string" ? values.jobTitle : void 0);
  assign("primaryEmail", typeof values.primaryEmail === "string" ? values.primaryEmail : void 0);
  assign("primaryPhone", typeof values.primaryPhone === "string" ? values.primaryPhone : void 0);
  assign("status", typeof values.status === "string" ? values.status : void 0);
  assign("lifecycleStage", typeof values.lifecycleStage === "string" ? values.lifecycleStage : void 0);
  assign("source", typeof values.source === "string" ? values.source : void 0);
  assign(
    "companyEntityId",
    typeof values.companyEntityId === "string" ? values.companyEntityId : values.companyEntityId === null ? null : void 0
  );
  assign("description", typeof values.description === "string" ? values.description : void 0);
  const customFields = collectCustomFieldValues(values, {
    transform: (value) => normalizeCustomFieldSubmitValue(value)
  });
  if (Object.keys(customFields).length) {
    payload.customFields = customFields;
  }
  if (organizationId) payload.organizationId = organizationId;
  return payload;
}
const createCompanyFormSchema = () => z.object({
  displayName: z.string().trim().min(1),
  primaryEmail: z.string().trim().email().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val),
  primaryPhone: z.string().trim().max(50).refine((value) => isValidPhoneNumber(value), { message: CUSTOMER_PHONE_INVALID_MESSAGE_KEY }).optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  status: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  lifecycleStage: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  source: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  legalName: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  brandName: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  domain: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  websiteUrl: z.string().trim().url().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  industry: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  sizeBucket: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional(),
  annualRevenue: z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional()
}).passthrough();
const createCompanyFormFields = (t) => {
  const dictionaryFields = companyDictionaryFieldDefinitions.map((definition) => ({
    id: definition.id,
    label: t(definition.labelKey),
    type: "custom",
    layout: definition.layout ?? "third",
    component: ({ value, setValue }) => /* @__PURE__ */ jsx(
      DictionarySelectField,
      {
        kind: definition.kind,
        value: typeof value === "string" ? value : void 0,
        onChange: (next) => setValue(next),
        labels: buildDictionaryLabels(t, definition)
      }
    )
  }));
  return [
    {
      id: "displayName",
      label: t("customers.companies.form.displayName.label", "Display name"),
      type: "text",
      required: true
    },
    {
      id: "primaryEmail",
      label: t("customers.companies.detail.highlights.primaryEmail", "Primary email"),
      type: "text",
      layout: "half",
      placeholder: t("customers.companies.form.primaryEmailPlaceholder", "name@example.com")
    },
    {
      id: "primaryPhone",
      label: t("customers.companies.detail.highlights.primaryPhone", "Primary phone"),
      type: "custom",
      layout: "half",
      component: ({ value, setValue, error, disabled, autoFocus }) => /* @__PURE__ */ jsx(
        PhoneNumberField,
        {
          value: typeof value === "string" ? value : null,
          onValueChange: (next) => setValue(typeof next === "string" ? next : ""),
          externalError: error,
          autoFocus,
          disabled,
          placeholder: t("customers.companies.form.primaryPhonePlaceholder", "+1 555 123 4567"),
          invalidLabel: t("customers.people.form.primaryPhone.invalid", "Enter a valid phone number with country code (e.g. +1 212 555 1234)"),
          minDigits: 7
        }
      )
    },
    ...dictionaryFields,
    {
      id: "legalName",
      label: t("customers.companies.detail.fields.legalName", "Legal name"),
      type: "text",
      layout: "half"
    },
    {
      id: "brandName",
      label: t("customers.companies.detail.fields.brandName", "Brand name"),
      type: "text",
      layout: "half"
    },
    {
      id: "domain",
      label: t("customers.companies.detail.fields.domain", "Domain"),
      type: "text",
      layout: "half",
      placeholder: t("customers.companies.detail.fields.domainPlaceholder", "example.com"),
      description: t("customers.companies.detail.fields.domainHelp", "Use a plain domain like example.com.")
    },
    {
      id: "websiteUrl",
      label: t("customers.companies.detail.highlights.website", "Website"),
      type: "text",
      layout: "half",
      placeholder: t("customers.companies.detail.highlights.websitePlaceholder", "https://example.com"),
      description: t("customers.companies.detail.fields.websiteHelp", "Use a full URL like https://example.com.")
    },
    {
      id: "industry",
      label: t("customers.companies.detail.highlights.industry", "Industry"),
      type: "text",
      layout: "half"
    },
    {
      id: "sizeBucket",
      label: t("customers.companies.detail.fields.sizeBucket", "Company size"),
      type: "text",
      layout: "half"
    },
    {
      id: "annualRevenue",
      label: t("customers.companies.detail.highlights.annualRevenue", "Annual revenue"),
      type: "text",
      layout: "half",
      placeholder: t("customers.companies.detail.highlights.annualRevenuePlaceholder", "Enter amount")
    },
    {
      id: "description",
      label: t("customers.companies.detail.fields.description", "Description"),
      type: "textarea"
    },
    {
      id: "addresses",
      label: "",
      type: "custom",
      layout: "full",
      component: ({ value, setValue }) => {
        const addresses = Array.isArray(value) ? value : [];
        return /* @__PURE__ */ jsx(
          CustomerAddressTiles,
          {
            addresses,
            t,
            emptyLabel: t("customers.companies.detail.empty.addresses"),
            gridClassName: "grid gap-4 min-[480px]:grid-cols-1 xl:grid-cols-2",
            showCoordinateFields: true,
            onCreate: async (payload) => {
              const nextId = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `tmp-${Math.random().toString(36).slice(2)}`;
              const next = {
                id: nextId,
                name: payload.name ?? void 0,
                purpose: payload.purpose ?? void 0,
                companyName: payload.companyName ?? void 0,
                addressLine1: payload.addressLine1,
                addressLine2: payload.addressLine2 ?? void 0,
                buildingNumber: payload.buildingNumber ?? void 0,
                flatNumber: payload.flatNumber ?? void 0,
                city: payload.city ?? void 0,
                region: payload.region ?? void 0,
                postalCode: payload.postalCode ?? void 0,
                country: payload.country ?? void 0,
                latitude: payload.latitude ?? void 0,
                longitude: payload.longitude ?? void 0,
                isPrimary: payload.isPrimary ?? false
              };
              const current = Array.isArray(addresses) ? addresses : [];
              const nextAddresses = next.isPrimary === true ? [next, ...current.map((item) => ({ ...item, isPrimary: false }))] : [next, ...current];
              setValue(nextAddresses);
            },
            onUpdate: async (id, payload) => {
              const current = Array.isArray(addresses) ? addresses : [];
              const updated = current.map((item) => {
                if (item.id !== id) {
                  return payload.isPrimary ? { ...item, isPrimary: false } : item;
                }
                return {
                  ...item,
                  name: payload.name ?? null,
                  purpose: payload.purpose ?? null,
                  companyName: payload.companyName ?? null,
                  addressLine1: payload.addressLine1,
                  addressLine2: payload.addressLine2 ?? null,
                  buildingNumber: payload.buildingNumber ?? null,
                  flatNumber: payload.flatNumber ?? null,
                  city: payload.city ?? null,
                  region: payload.region ?? null,
                  postalCode: payload.postalCode ?? null,
                  country: payload.country ?? null,
                  latitude: payload.latitude ?? null,
                  longitude: payload.longitude ?? null,
                  isPrimary: payload.isPrimary ?? false
                };
              });
              setValue(updated);
            },
            onDelete: async (id) => {
              const current = Array.isArray(addresses) ? addresses : [];
              setValue(current.filter((item) => item.id !== id));
            }
          }
        );
      }
    }
  ];
};
const createCompanyFormGroups = (t) => [
  {
    id: "details",
    title: t("customers.companies.form.groups.details"),
    column: 1,
    fields: ["displayName", "primaryEmail", "primaryPhone", "status", "lifecycleStage", "source"]
  },
  {
    id: "profile",
    title: t("customers.companies.form.groups.profile"),
    column: 1,
    fields: ["legalName", "brandName", "domain", "websiteUrl", "industry", "sizeBucket", "annualRevenue"]
  },
  {
    id: "addresses",
    title: t("customers.companies.form.groups.addresses"),
    column: 1,
    fields: ["addresses"]
  },
  {
    id: "notes",
    title: t("customers.companies.form.groups.notes"),
    column: 2,
    fields: ["description"]
  },
  {
    id: "customFields",
    title: t("customers.companies.form.groups.custom"),
    column: 2,
    kind: "customFields"
  }
];
function buildCompanyPayload(values, organizationId) {
  const payload = {};
  const displayNameValue = blankToUndefined(
    typeof values.displayName === "string" ? values.displayName : void 0
  );
  if (!displayNameValue) {
    throw new Error("DISPLAY_NAME_REQUIRED");
  }
  payload.displayName = displayNameValue;
  const assign = (key, val) => {
    const normalized = blankToUndefined(val);
    if (normalized !== void 0) payload[key] = normalized;
  };
  assign("primaryEmail", typeof values.primaryEmail === "string" ? values.primaryEmail : void 0);
  assign("primaryPhone", typeof values.primaryPhone === "string" ? values.primaryPhone : void 0);
  assign("status", typeof values.status === "string" ? values.status : void 0);
  assign("lifecycleStage", typeof values.lifecycleStage === "string" ? values.lifecycleStage : void 0);
  assign("source", typeof values.source === "string" ? values.source : void 0);
  assign("legalName", typeof values.legalName === "string" ? values.legalName : void 0);
  assign("brandName", typeof values.brandName === "string" ? values.brandName : void 0);
  assign("domain", typeof values.domain === "string" ? values.domain?.toLowerCase() : void 0);
  assign("websiteUrl", typeof values.websiteUrl === "string" ? values.websiteUrl : void 0);
  assign("industry", typeof values.industry === "string" ? values.industry : void 0);
  assign("sizeBucket", typeof values.sizeBucket === "string" ? values.sizeBucket : void 0);
  assign("description", typeof values.description === "string" ? values.description : void 0);
  const rawRevenue = typeof values.annualRevenue === "string" ? values.annualRevenue.trim() : "";
  if (rawRevenue.length) {
    const normalized = rawRevenue.replace(/,/g, "").replace(/\s+/g, "");
    if (!/^\d+(\.\d{1,2})?$/.test(normalized)) {
      throw new Error("ANNUAL_REVENUE_INVALID");
    }
    payload.annualRevenue = normalized;
  }
  const customFields = collectCustomFieldValues(values, {
    transform: (value) => normalizeCustomFieldSubmitValue(value)
  });
  if (Object.keys(customFields).length) {
    payload.customFields = customFields;
  }
  if (organizationId) payload.organizationId = organizationId;
  return payload;
}
const optionalString = () => z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? void 0 : val).optional();
const clearableUrlField = () => z.string().trim().url().optional().or(z.literal("")).transform((val) => val === "" ? null : val).optional();
const clearableEmailField = () => z.string().trim().email().optional().or(z.literal("")).transform((val) => val === "" ? null : val).optional();
const clearableDomainField = () => z.string().trim().max(200).optional().or(z.literal("")).transform((val) => val === "" ? null : val).optional();
const clearableTextField = () => z.string().trim().optional().or(z.literal("")).transform((val) => val === "" ? null : val).optional();
const clearablePhoneField = () => z.string().trim().max(50).refine((value) => value === "" || isValidPhoneNumber(value), { message: CUSTOMER_PHONE_INVALID_MESSAGE_KEY }).optional().or(z.literal("")).transform((val) => val === "" ? null : val).optional();
const createCompanyEditSchema = () => createCompanyFormSchema().extend({
  id: z.string().uuid(),
  primaryEmail: clearableEmailField(),
  primaryPhone: clearablePhoneField(),
  websiteUrl: clearableUrlField(),
  domain: clearableDomainField(),
  legalName: clearableTextField(),
  brandName: clearableTextField(),
  sizeBucket: clearableTextField(),
  annualRevenue: clearableTextField(),
  description: clearableTextField()
});
const createPersonEditSchema = () => createPersonFormSchema().extend({
  id: z.string().uuid(),
  department: optionalString(),
  primaryEmail: clearableEmailField(),
  primaryPhone: clearablePhoneField(),
  linkedInUrl: clearableUrlField(),
  twitterUrl: clearableUrlField()
});
const buildIndustryLabels = (t) => ({
  placeholder: t("customers.companies.form.industry.placeholder", "Select industry\u2026"),
  addLabel: t("customers.companies.form.dictionary.addIndustry", "Add industry"),
  addPrompt: t("customers.companies.form.dictionary.promptIndustry", "Enter a new industry."),
  dialogTitle: t("customers.companies.form.dictionary.dialogTitleIndustry", "Add industry"),
  valueLabel: t("customers.people.form.dictionary.valueLabel", "Value"),
  valuePlaceholder: t("customers.people.form.dictionary.valuePlaceholder", "Value"),
  labelLabel: t("customers.config.dictionaries.dialog.labelLabel", "Label"),
  labelPlaceholder: t("customers.people.form.dictionary.labelPlaceholder", "Display name shown in UI"),
  emptyError: t("customers.people.form.dictionary.errorRequired"),
  cancelLabel: t("customers.people.form.dictionary.cancel"),
  saveLabel: t("customers.people.form.dictionary.save"),
  successCreateLabel: void 0,
  errorLoad: t("customers.people.form.dictionary.errorLoad"),
  errorSave: t("customers.people.form.dictionary.error"),
  loadingLabel: t("customers.people.form.dictionary.loading"),
  manageTitle: t("customers.people.form.dictionary.manage")
});
const createCompanyEditFields = (t) => {
  const baseFields = createCompanyFormFields(t);
  const industryLabels = buildIndustryLabels(t);
  return baseFields.map((field) => {
    if (field.id === "industry") {
      return {
        id: "industry",
        label: t("customers.companies.detail.fields.industry", "Industry"),
        type: "custom",
        layout: "half",
        component: ({ value, setValue }) => /* @__PURE__ */ jsx(
          DictionarySelectField,
          {
            kind: "industries",
            value: typeof value === "string" ? value : void 0,
            onChange: (next) => setValue(next),
            labels: industryLabels
          }
        )
      };
    }
    return field;
  });
};
const createPersonEditFields = (t) => {
  const baseFields = createPersonFormFields(t);
  return [
    ...baseFields,
    {
      id: "department",
      label: t("customers.people.form.department", "Department"),
      type: "text",
      layout: "half"
    },
    {
      id: "linkedInUrl",
      label: t("customers.people.form.linkedInUrl", "LinkedIn URL"),
      type: "text",
      layout: "half",
      placeholder: t("customers.people.form.linkedInUrl.placeholder", "https://linkedin.com/in/...")
    },
    {
      id: "twitterUrl",
      label: t("customers.people.form.twitterUrl", "Twitter / X URL"),
      type: "text",
      layout: "half",
      placeholder: t("customers.people.form.twitterUrl.placeholder", "https://x.com/...")
    }
  ];
};
const createCompanyEditGroups = (t) => [
  {
    id: "details",
    title: t("customers.companies.form.groups.details"),
    column: 1,
    fields: ["displayName", "primaryEmail", "primaryPhone", "status", "lifecycleStage", "source"]
  },
  {
    id: "roles",
    title: t("customers.roles.groupTitle", "Roles"),
    column: 1,
    component: ({ values }) => values.id ? /* @__PURE__ */ jsx(
      RolesSection,
      {
        entityType: "company",
        entityId: values.id,
        entityName: typeof values.displayName === "string" ? values.displayName : null
      }
    ) : null
  },
  {
    id: "profile",
    title: t("customers.companies.form.groups.profile"),
    column: 1,
    fields: ["legalName", "brandName", "domain", "websiteUrl", "industry", "sizeBucket", "annualRevenue"]
  },
  {
    id: "notes",
    title: t("customers.companies.form.groups.notes"),
    column: 2,
    fields: ["description"]
  },
  {
    id: "customFields",
    title: t("customers.companies.form.groups.custom"),
    column: 2,
    kind: "customFields"
  }
];
const createCompanyDaneFiremyGroups = (t) => [
  {
    id: "identity",
    title: t("customers.companies.form.groups.identity", "To\u017Csamo\u015B\u0107").toUpperCase(),
    column: 1,
    fields: ["displayName", "legalName", "brandName"]
  },
  {
    id: "contact",
    title: t("customers.companies.form.groups.contact", "Kontakt").toUpperCase(),
    column: 1,
    fields: ["primaryEmail", "primaryPhone", "domain", "websiteUrl"]
  },
  {
    id: "classification",
    title: t("customers.companies.form.groups.classification", "Klasyfikacja").toUpperCase(),
    column: 1,
    fields: ["status", "lifecycleStage", "source"]
  },
  {
    id: "businessProfile",
    title: t("customers.companies.form.groups.businessProfile", "Profil biznesowy").toUpperCase(),
    column: 1,
    fields: ["industry", "sizeBucket", "annualRevenue"]
  },
  {
    id: "notes",
    title: t("customers.companies.form.groups.notes", "Notatki"),
    column: 1,
    fields: ["description"]
  },
  {
    id: "customFields",
    title: t("customers.companies.form.groups.customAttributes", "Atrybuty niestandardowe"),
    column: 1,
    kind: "customFields"
  }
];
const createPersonEditGroups = (t) => [
  {
    id: "details",
    title: t("customers.people.form.groups.details"),
    column: 1,
    fields: [
      "firstName",
      "lastName",
      "__contactInformationSection",
      "primaryEmail",
      "primaryPhone",
      "__companyInformationSection",
      "jobTitle",
      "companyEntityId",
      "status",
      "lifecycleStage",
      "source"
    ],
    component: createDisplayNameSection(t)
  },
  {
    id: "roles",
    title: t("customers.roles.groupTitle", "Roles"),
    column: 1,
    component: ({ values }) => values.id ? /* @__PURE__ */ jsx(
      RolesSection,
      {
        entityType: "person",
        entityId: values.id,
        entityName: typeof values.displayName === "string" ? values.displayName : null
      }
    ) : null
  },
  {
    id: "social",
    title: t("customers.people.form.groups.social", "Social & links"),
    column: 1,
    fields: ["department", "linkedInUrl", "twitterUrl"]
  },
  {
    id: "notes",
    title: t("customers.people.form.groups.notes"),
    column: 2,
    fields: ["description"]
  },
  {
    id: "customFields",
    title: t("customers.people.form.groups.custom"),
    column: 2,
    kind: "customFields"
  }
];
const createPersonPersonalDataGroups = (t, options) => {
  const entityName = options?.entityName?.trim() || null;
  const rolesTitle = entityName ? t("customers.roles.groupTitle.person", "My roles with {{name}}", { name: entityName }) : t("customers.people.form.groups.roles", "My roles");
  return [
    {
      id: "personalDataDisplay",
      title: t("customers.people.form.groups.displayName", "Display name"),
      column: 1,
      bare: true,
      component: createDisplayNameSection(t)
    },
    {
      id: "personalData",
      title: t("customers.people.form.groups.personalData", "Personal data"),
      column: 1,
      fields: ["firstName", "lastName", "jobTitle", "primaryEmail", "primaryPhone"]
    },
    {
      id: "companyRole",
      title: t("customers.people.form.groups.companyRole", "Company & role"),
      column: 1,
      fields: ["companyEntityId", "status", "lifecycleStage", "source"]
    },
    {
      id: "customFields",
      title: t("customers.people.form.groups.customAttributes", "Custom attributes"),
      column: 1,
      kind: "customFields"
    },
    {
      id: "roles",
      title: rolesTitle,
      column: 1,
      component: ({ values }) => values.id ? /* @__PURE__ */ jsx(
        RolesSection,
        {
          entityType: "person",
          entityId: values.id,
          entityName: typeof values.displayName === "string" ? values.displayName : null
        }
      ) : null
    }
  ];
};
const assignClearable = (payload, key, raw) => {
  if (raw === null) {
    payload[key] = null;
    return;
  }
  if (typeof raw !== "string") return;
  const trimmed = raw.trim();
  payload[key] = trimmed.length ? trimmed : null;
};
function buildCompanyEditPayload(values, organizationId) {
  const payload = buildCompanyPayload(values, organizationId);
  payload.id = values.id;
  assignClearable(payload, "primaryEmail", values.primaryEmail);
  assignClearable(payload, "primaryPhone", values.primaryPhone);
  assignClearable(payload, "websiteUrl", values.websiteUrl);
  assignClearable(payload, "domain", typeof values.domain === "string" ? values.domain.toLowerCase() : values.domain);
  assignClearable(payload, "legalName", values.legalName);
  assignClearable(payload, "brandName", values.brandName);
  assignClearable(payload, "sizeBucket", values.sizeBucket);
  assignClearable(payload, "description", values.description);
  const annualRevenueRaw = values.annualRevenue;
  const annualRevenueBlank = annualRevenueRaw === null || typeof annualRevenueRaw === "string" && annualRevenueRaw.trim().length === 0;
  if (annualRevenueBlank) payload.annualRevenue = null;
  return payload;
}
function buildPersonEditPayload(values, organizationId) {
  const payload = buildPersonPayload(values, organizationId);
  payload.id = values.id;
  const department = typeof values.department === "string" ? values.department.trim() : "";
  if (department.length) payload.department = department;
  assignClearable(payload, "primaryEmail", values.primaryEmail);
  assignClearable(payload, "primaryPhone", values.primaryPhone);
  assignClearable(payload, "linkedInUrl", values.linkedInUrl);
  assignClearable(payload, "twitterUrl", values.twitterUrl);
  return payload;
}
function mapCompanyOverviewToFormValues(overview) {
  const rawPhone = overview.company.primaryPhone;
  const phoneValue = rawPhone == null ? "" : String(rawPhone);
  return {
    id: overview.company.id,
    displayName: coerceDisplayName(overview.company.displayName),
    primaryEmail: overview.company.primaryEmail ?? "",
    primaryPhone: phoneValue,
    status: overview.company.status ?? "",
    lifecycleStage: overview.company.lifecycleStage ?? "",
    source: overview.company.source ?? "",
    description: overview.company.description ?? "",
    legalName: overview.profile?.legalName ?? "",
    brandName: overview.profile?.brandName ?? "",
    domain: overview.profile?.domain ?? "",
    websiteUrl: overview.profile?.websiteUrl ?? "",
    industry: overview.profile?.industry ?? "",
    sizeBucket: overview.profile?.sizeBucket ?? "",
    annualRevenue: overview.profile?.annualRevenue ?? "",
    ...extractCustomFieldEntries({ customFields: overview.customFields })
  };
}
function mapPersonOverviewToFormValues(overview) {
  const rawPhone = overview.person.primaryPhone;
  const phoneValue = rawPhone == null ? "" : String(rawPhone);
  return {
    id: overview.person.id,
    displayName: coerceDisplayName(overview.person.displayName),
    firstName: overview.profile?.firstName ?? "",
    lastName: overview.profile?.lastName ?? "",
    primaryEmail: overview.person.primaryEmail ?? "",
    primaryPhone: phoneValue,
    companyEntityId: overview.profile?.companyEntityId ?? "",
    jobTitle: overview.profile?.jobTitle ?? "",
    status: overview.person.status ?? "",
    lifecycleStage: overview.person.lifecycleStage ?? "",
    source: overview.person.source ?? "",
    description: overview.person.description ?? "",
    department: overview.profile?.department ?? "",
    linkedInUrl: overview.profile?.linkedInUrl ?? "",
    twitterUrl: overview.profile?.twitterUrl ?? "",
    ...extractCustomFieldEntries({ customFields: overview.customFields })
  };
}
export {
  CUSTOMER_DICTIONARIES_MANAGE_HREF,
  CompanySelectField,
  DictionarySelectField,
  buildCompanyEditPayload,
  buildCompanyPayload,
  buildPersonEditPayload,
  buildPersonPayload,
  createCompanyDaneFiremyGroups,
  createCompanyEditFields,
  createCompanyEditGroups,
  createCompanyEditSchema,
  createCompanyFormFields,
  createCompanyFormGroups,
  createCompanyFormSchema,
  createDisplayNameSection,
  createPersonEditFields,
  createPersonEditGroups,
  createPersonEditSchema,
  createPersonFormFields,
  createPersonFormGroups,
  createPersonFormSchema,
  createPersonPersonalDataGroups,
  getCustomerDictionaryManageHref,
  mapCompanyOverviewToFormValues,
  mapPersonOverviewToFormValues,
  metadata
};
//# sourceMappingURL=formConfig.js.map
