'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { useToast } from '@/components/crm/ToastProvider';
import { publicEnv } from '@/config/env';
import { getCreateForm } from '@/features/create-forms/api.client';
import { accessChoices, sameAssignees } from '@/features/custom-properties/access-assignees';
import {
  shownInForms,
  showInFormsBox,
  showInFormsCreate,
  showInFormsUpdate,
  showInFormsValue,
} from '@/features/custom-properties/show-in-forms';
import {
  accessBody,
  assigneesOf,
  changeCustomPropertyType,
  createCustomProperty,
  NO_ASSIGNEES,
  updateCustomProperty,
  type AccessAssignees,
  type ConditionalOptions,
  type CustomPropertyDefinition,
  type PropertyAccess,
  type PropertyOption,
  type PropertyType,
  type RollupConfig,
} from '@/features/custom-properties/api.client';
import { crmUserSettingsPatch } from '@/features/custom-properties/crm-user';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { getPropertyFillRate, listPropertyUsage, type PropertyUsage } from '../api.client';
import { createConflictNotice, duplicateNotice } from '../createConflict';
import { optionSaveProblem } from '../optionChecks';
import { AccessAssigneesField, hasAssignees } from './AccessAssigneesField';
import {
  associationsOf,
  byText,
  customProperties,
  FIELD_KINDS,
  fieldTypeLabel,
  isFileKind,
  isOptionType,
  isHomeGroup,
  kindCanBeUnique,
  kindOf,
  liveGroups,
  toInternalName,
  type DataModel,
  type DmObject,
  PROPERTY_ASSET_KINDS,
  propertyAssetCount,
  propertyAssetHref,
} from '../model';
import {
  createTypeBody,
  emptyRollup,
  formulaErrorOf,
  formulaPatch,
  rollupProblem,
  rollupResult,
  switchRollup,
} from '../worked-out';
import { DmIcon, TypeIcon } from './icons';
import { Modal, SelectMenu } from './primitives';
import {
  EMPTY_RULES,
  rulesDraftOf,
  rulesKind,
  rulesOf,
  ValidationRulesFields,
  type RulesDraft,
} from './ValidationRules';
import { CalculationFields, RollupFields, useRollupFields } from './WorkedOutFields';
import { CrmUserFields } from './CrmUserFields';
import { ADMIN_ONLY, propertyEditorLock } from './viewOnly';

/** Types a saved field may change to (the API's PROPERTY_TYPE_CHANGES); values are converted. */
const TYPE_CHANGES: Record<PropertyType, readonly PropertyType[]> = {
  text: ['textarea', 'number', 'select', 'multiselect'],
  textarea: ['text'],
  number: ['text'],
  select: ['multiselect', 'text'],
  multiselect: ['select', 'text'],
  date: ['datetime', 'text'],
  datetime: ['date', 'text'],
  boolean: ['text'],
};

/** CRM user and File fields keep their type, and no saved field becomes one (#247). */
export const fixedType = (p: { fieldType?: string | null }) =>
  p.fieldType === 'owner' || isFileKind(p);

/** The kinds a saved field of `type` may move to in Field type. */
export const editKinds = (type: PropertyType) =>
  FIELD_KINDS.filter(
    (x) => !x.worked && !fixedType(x) && (x.type === type || TYPE_CHANGES[type].includes(x.type)),
  );

const NONE = '__none__';

export type PropertyEditorMode = 'create' | 'edit' | 'clone';

/** What the quick Create property panel hands over with "Edit more options". */
export interface PropertySeed {
  label: string;
  /** Set when the internal name was typed rather than derived from the label. */
  name?: string;
  kind: string;
  desc: string;
  unique: boolean;
}

/** The group a new field goes in: the "<Object> information" group, else the first one. */
export function defaultGroupName(
  groups: Array<{ name: string; label: string }>,
  object: Pick<DmObject, 'key' | 'singular'>,
): string | null {
  return (
    (
      groups.find((g) => isHomeGroup(g, object)) ??
      groups.find((g) => /information/i.test(g.label)) ??
      groups[0]
    )?.name ?? null
  );
}

export type PropertyEditorSection =
  | 'details'
  | 'type'
  | 'docs'
  | 'rules'
  | 'conditional'
  | 'access'
  | 'preview'
  | 'smart'
  | 'autofill'
  | 'usage'
  | 'quality'
  | 'sources';
type Section = PropertyEditorSection;

/** Editor sections hidden for Users (`fieldOnly`): see `fieldOnly` in PropertyEditor. */
const NOT_FOR_FIELD_ONLY = new Set<Section>([
  'conditional',
  'smart',
  'autofill',
  'usage',
  'quality',
  'sources',
]);

/**
 * Fields the business can't edit: built-in, activity default and HubSpot fields. Its own
 * calculated fields (Events ROI…) keep their label, group, documentation and access editable;
 * only their value is the CRM's.
 */
export const isCrmOwned = (p: CustomPropertyDefinition) =>
  Boolean(p.system || p.standard || p.crmProvided);

/** How the CRM works out the business's calculated fields (calculated-fields/rules.ts). */
const FORMULAS: Record<string, string> = {
  'event.total_cost':
    'Airfare + Badges + Exhibiting Costs + F&B Costs + Hotels + Marketing & Signage + Misc/Other Costs + Sponsorship Costs + Show Services + Shipping + Swag (an empty cost counts as 0)',
  'event.travel__accommodations_cost': 'Airfare + Hotels',
  'event.marketing__swag_cost': 'Marketing & Signage + Swag',
  'event.show_services__shipping_costs': 'Show Services + Shipping',
  'event.remaining_budget': "Event Budget − Total Event Cost (empty when there's no budget)",
  'event.roi': '(Total Closed Won Revenue − Total Event Cost) ÷ Total Event Cost (0 without costs)',
  'event.pipelinetospend_ratio': 'Total Pipeline Value ÷ Total Event Cost × 100 (0 without costs)',
  'event.total_deals_created': 'Number of deals linked to the event',
  'event.total_pipeline_value': 'Sum of the amounts of linked deals that are not closed won',
  'event.total_closed_won_revenue':
    'Sum of the amounts of linked deals in the Closed Won stage of the Sales Pipeline',
  'deal.days_until_close': 'Working days (weekends skipped) between Create Date and Close Date',
};

interface Draft {
  label: string;
  name: string;
  kind: string;
  group: string;
  desc: string;
  instructions: string;
  required: boolean;
  unique: boolean;
  /** Offered when building forms. */
  showInForms: boolean;
  options: PropertyOption[];
  access: PropertyAccess;
  /** `assigned` access: who sees and changes the values. */
  assignees: AccessAssignees;
  /** HUB-354: validation rules as typed. */
  rules: RulesDraft;
  /** HUB-349 calculation: the expression and the result type. */
  formula: string;
  resultType: PropertyType;
  /** HUB-350 rollup or property sync. */
  rollup: RollupConfig;
  /** DMG8 (C1): the option value (or 'true' / 'false') new records get; '' for none. */
  defaultValue: string;
  /** DMG8 (C2): how the options look. */
  optionStyle: OptionStyle;
  /** DMG9: CRM user fields: several users per record. */
  multipleUsers: boolean;
  /** DMG9: CRM user fields: only users of these teams ([] = any user). */
  userTeamIds: string[];
  /** HubSpot's conditional options (dropdowns): null for none. */
  conditional: ConditionalOptions | null;
}

/** DMG8 (C2): the design's option styles (data-model.js:927). */
type OptionStyle = 'default' | 'dot' | 'badge';
const OPTION_STYLES: Array<[OptionStyle, string]> = [
  ['default', 'Default'],
  ['dot', 'With dot'],
  ['badge', 'Badge'],
];
/**
 * DMG8 (C6): the design's Number format (data-model.js:924, 1197) on this CRM's number kinds.
 * "Unformatted number" and "Duration" have no display in the CRM yet (for the lead).
 */
const NUMBER_FORMATS: Array<[string, string]> = [
  ['number', 'Formatted number'],
  ['currency', 'Currency'],
  ['percent', 'Percentage'],
];

/**
 * The full-page property editor (HUB-606, the design's property-management screen): a top bar
 * with Cancel and Save, a sidebar of sections (Details, Field type, Documentation, Manage access,
 * Preview, Data Agent, Usage) and the chosen section. The name, type and object of a saved field
 * never change; options can be added, relabelled or archived. CRM-provided fields open read-only.
 */
export function PropertyEditor({
  mode,
  object,
  property,
  seed,
  model,
  startSection,
  onSection,
  viewOnly = false,
  viewOnlyText = ADMIN_ONLY,
  settingsLinks = !viewOnly,
  onClose,
  onSaved,
  onObjectChange,
}: {
  mode: PropertyEditorMode;
  object: DmObject;
  /** The field being edited or cloned. */
  property: CustomPropertyDefinition | null;
  /** Create: what was typed in the quick Create property panel. */
  seed?: PropertySeed;
  model: DataModel;
  /** The section it opens on (the row menu's "Manage access" opens Manage access). */
  startSection?: Section;
  /** Called with the section shown, for pages that keep it in the URL. */
  onSection?: (section: Section) => void;
  /** Someone without Manage settings: the field opens read-only (the user's call, 18 Nov 2026). */
  viewOnly?: boolean;
  /** Batch P1: why it is read-only (the Data Model's reason by default). */
  viewOnlyText?: string;
  /** Batch P1: the links to Settings › Properties show (the page would open for the user). */
  settingsLinks?: boolean;
  onClose: () => void;
  onSaved: (saved: CustomPropertyDefinition) => void;
  /**
   * DMG7 (C7): creating, the object can be changed, as the design's searchable select
   * (data-model.js:1082, 1278); the page then passes the new object. Without it the object is
   * fixed (Settings › Properties, editing, cloning).
   */
  onObjectChange?: (key: string) => void;
}) {
  const toast = useToast();
  const editing = mode === 'edit' && property !== null;
  /**
   * The editor is read-only: a CRM-owned field (built-in, activity default, HubSpot). Not the
   * field's own `readOnly`, which says only imports and calculations set its value.
   */
  /** Nothing can be changed: CRM-owned, or the user can only view the data model. */
  const lock = propertyEditorLock({
    editing,
    crmOwned: editing && isCrmOwned(property),
    viewOnly,
  });
  const readOnly = lock.readOnly;
  /** The CRM works the value out: required and unique don't apply. */
  const calculated = Boolean(property?.calculated);
  /**
   * Users (#261): fields without records. No record is created, nothing links to a member and
   * the Data Agent, record forms and monitoring don't read them, so those sections are hidden.
   */
  const fieldOnly = Boolean(object.fieldOnly);
  const start =
    startSection && !(fieldOnly && NOT_FOR_FIELD_ONLY.has(startSection)) ? startSection : 'details';
  const formula = property ? FORMULAS[`${object.key}.${property.name}`] : undefined;
  const [loading, setLoading] = useState<string | null>(null);
  const groups = liveGroups(model, object.key);

  const initial = useMemo<Draft>(() => {
    const src = property;
    if (!src && seed) {
      const kind = FIELD_KINDS.find((k) => k.value === seed.kind)!;
      return {
        label: seed.label,
        name: seed.name ?? '',
        kind: seed.kind,
        group: defaultGroupName(groups, object) ?? NONE,
        desc: seed.desc,
        instructions: '',
        required: false,
        unique: seed.unique,
        showInForms: true,
        options: isOptionType(kind.type)
          ? [
              { label: 'Option 1', value: 'option_1' },
              { label: 'Option 2', value: 'option_2' },
            ]
          : [],
        access: 'everyone_edit',
        assignees: NO_ASSIGNEES,
        rules: EMPTY_RULES,
        formula: '',
        resultType: 'number',
        rollup: emptyRollup(kind.worked === 'sync'),
        defaultValue: '',
        optionStyle: 'default',
        multipleUsers: false,
        userTeamIds: [],
        conditional: null,
      };
    }
    return {
      label: src ? (mode === 'clone' ? `${src.label} (Cloned)` : src.label) : '',
      name: src && mode === 'edit' ? src.name : src ? toInternalName(`${src.label} cloned`) : '',
      kind: src ? kindOf(src) : 'text',
      // A built-in field's group is a label ("Contact information"), not a stored group: its
      // clone goes in the group of that name, or the default one.
      group: src?.standard
        ? (groups.find((g) => g.label === src.groupName)?.name ??
          defaultGroupName(groups, object) ??
          NONE)
        : (src?.groupName ?? defaultGroupName(groups, object) ?? NONE),
      desc: src?.description ?? '',
      instructions: src?.instructions ?? '',
      required: src?.required ?? false,
      unique: src?.unique ?? false,
      showInForms: src ? shownInForms(src) : true,
      options: src?.options?.map((o) => ({ ...o })) ?? [],
      // A clone starts with the source's access.
      access: src?.access ?? 'everyone_edit',
      assignees: assigneesOf(src),
      rules: rulesDraftOf(src?.validation),
      formula: src?.formula?.expression ?? '',
      resultType: src?.fieldType === 'calculation' ? src.type : 'number',
      rollup: src?.rollup ? { ...src.rollup } : emptyRollup(false),
      defaultValue: src?.defaultValue ?? '',
      optionStyle: src?.optionStyle ?? 'default',
      multipleUsers: Boolean(src?.multipleUsers),
      userTeamIds: [...(src?.userTeamIds ?? [])],
      conditional:
        src?.conditionalOptions && mode === 'edit'
          ? {
              controllingProperty: src.conditionalOptions.controllingProperty,
              byValue: { ...src.conditionalOptions.byValue },
            }
          : null,
    };
    // Only when another field opens: a reload must not reset what the user typed.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [property?.id, mode, object.key]);
  const [d, setD] = useState<Draft>(initial);
  // #737: when the field was last changed as this editor opened it; a reload keeps it.
  const openedAt = useMemo(
    () => property?.updatedAt,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [property?.id, mode, object.key],
  );
  const [nameEdited, setNameEdited] = useState(false);
  const [editName, setEditName] = useState(false);
  const [section, setSection] = useState<Section>(start);
  useEffect(() => {
    onSection?.(section);
    // Only when the section changes: a new callback each render must not call it again.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [section]);
  const [busy, setBusy] = useState(false);
  /** Why the API refused the formula on the last save; cleared as it is edited. */
  const [formulaError, setFormulaError] = useState<string | null>(null);
  const [confirmDiscard, setConfirmDiscard] = useState(false);
  const [usage, setUsage] = useState<PropertyUsage | null | undefined>(undefined);
  // The options list, as in HubSpot: active or archived ones, and a search.
  const [optionTab, setOptionTab] = useState<'active' | 'archived'>('active');
  const [optionSearch, setOptionSearch] = useState('');
  /** C3 (DMG7): the design's Sort orders only the list shown (data-model.js:1154-1155). */
  const [optionSort, setOptionSort] = useState<'custom' | 'az' | 'za'>('custom');
  /** C3: ticked options, by their place in the list (cleared whenever places change). */
  const [optPicked, setOptPicked] = useState<Set<number>>(new Set());
  const [clearing, setClearing] = useState(false);
  const fixedValues = useMemo(
    () => new Set(mode === 'edit' ? (property?.options ?? []).map((o) => o.value) : []),
    [mode, property],
  );

  useEffect(() => {
    setD(initial);
    setNameEdited(Boolean(seed?.name));
    setSection(start);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initial]);

  // Fill rate for the Usage section (custom fields of objects with records; built-in fields
  // aren't stored definitions, so there's none to ask for).
  useEffect(() => {
    if (!editing || object.activity || object.catalog || property?.standard) return;
    let alive = true;
    getPropertyFillRate(property.id).then(
      (r) => alive && setFill(r),
      () => alive && setFill(null),
    );
    return () => {
      alive = false;
    };
  }, [editing, object.activity, object.catalog, property?.id, property?.standard]);

  // Whether the field is on the object's Create form, said when "Show property in forms" goes
  // off: that form keeps it.
  const [onCreateForm, setOnCreateForm] = useState<{ required: boolean } | null>(null);
  useEffect(() => {
    if (!editing || object.activity || object.catalog || property?.standard) return;
    let alive = true;
    getCreateForm(object.key).then(
      (form) => {
        const f = form.fields.find((x) => x.field === `custom.${property.name}`);
        if (alive) setOnCreateForm(f ? { required: f.required } : null);
      },
      () => alive && setOnCreateForm(null),
    );
    return () => {
      alive = false;
    };
  }, [editing, object.activity, object.catalog, object.key, property?.name, property?.standard]);

  useEffect(() => {
    if (!editing) return;
    let alive = true;
    listPropertyUsage(object.key).then(
      (rows) => alive && setUsage(rows.find((r) => r.name === property.name) ?? null),
      () => alive && setUsage(null),
    );
    return () => {
      alive = false;
    };
  }, [editing, object.key, property?.name]);

  // The page behind doesn't scroll while the editor is open; Escape cancels.
  useEffect(() => {
    document.body.classList.add('dm-no-scroll');
    return () => document.body.classList.remove('dm-no-scroll');
  }, []);

  const set = (patch: Partial<Draft>) => setD((cur) => ({ ...cur, ...patch }));
  const k = FIELD_KINDS.find((x) => x.value === d.kind)!;
  const worked = k.worked;
  const isRollup = worked === 'rollup' || worked === 'sync';
  /** Rules › "Show property in forms": shown, disabled (CRM-owned or required) and why. */
  const formsBox = showInFormsBox(editing ? property : null, {
    crmOwned: readOnly,
    required: d.required,
  });
  const withOptions = !worked && isOptionType(k.type);
  /** DMG9: a CRM user field (data-model.js:1177). */
  const crmUser = !worked && k.fieldType === 'owner';
  /** DMG8 (C1): option fields and single checkboxes (data-model.js:1140). */
  const canDefault = !worked && (withOptions || k.type === 'boolean');
  const defaultChoices =
    k.type === 'boolean'
      ? [
          { value: 'true', label: 'Yes' },
          { value: 'false', label: 'No' },
        ]
      : d.options
          .filter((o) => !o.archived && o.label.trim())
          .map((o) => ({ value: o.value, label: o.label }));
  /** DMG8 (C4): the Documentation tab shown. */
  const [docTab, setDocTab] = useState<'text' | 'options'>('text');
  /**
   * HubSpot lets a saved custom property change type; the CRM's own, calculated (calculations,
   * rollups and syncs among them) and CRM user fields keep theirs.
   */
  const typeEditable = !editing || (!readOnly && !calculated && !worked && !fixedType(property));
  const kinds = editing ? editKinds(property.type) : FIELD_KINDS;
  const kindChanged = editing && d.kind !== initial.kind;
  const typeChanged = editing && !worked && k.type !== property.type;
  // Unique values are checked across records, which Users don't have.
  const canBeUnique = kindCanBeUnique(k) && !fieldOnly;
  /** Nobody types a worked-out or File value (#247), so it is never required. */
  const canBeRequired = !worked && !isFileKind(k);
  const ruleKind = worked ? null : rulesKind(k.type, k.fieldType);
  const rollupFields = useRollupFields(object.key, d.rollup.linkedObject, isRollup);
  // #723: a custom object's rollups read the objects it can be associated with (the filter API
  // lists linked objects of contacts, companies and deals only).
  const rollupData = object.definition
    ? {
        ...rollupFields,
        linked: associationsOf(model, object.key)
          .map((a) => model.objects.find((x) => x.key === a.other))
          .filter((x): x is DmObject => Boolean(x && !x.activity && !x.catalog))
          .map((x) => x.key),
      }
    : rollupFields;
  const linkedDefs = model.properties[d.rollup.linkedObject] ?? [];
  const rollupOut = isRollup ? rollupResult(d.rollup, rollupData.fields, linkedDefs) : null;
  // A saved rollup keeps how it is worked out (shown read-only).
  const rollupIssue =
    isRollup && !editing
      ? rollupProblem(object.key, d.rollup, rollupData.fields, linkedDefs)
      : null;
  const rules = rulesOf(d.rules, ruleKind);
  const initialRules = rulesOf(initial.rules, ruleKind).rules;
  const shownName = editing || nameEdited ? d.name : toInternalName(d.label);
  const liveOptions = d.options.filter((o) => !o.archived);
  const archivedCount = d.options.length - liveOptions.length;
  const optionQuery = optionSearch.trim().toLowerCase();
  // Kept with their place in the list, which edits address.
  const shownOptions = d.options
    .map((o, i) => ({ o, i }))
    .filter(
      ({ o }) =>
        Boolean(o.archived) === (optionTab === 'archived') &&
        (!optionQuery ||
          o.label.toLowerCase().includes(optionQuery) ||
          o.value.toLowerCase().includes(optionQuery)),
    )
    .sort((a, b) =>
      optionSort === 'az'
        ? byText(a.o.label, b.o.label)
        : optionSort === 'za'
          ? byText(b.o.label, a.o.label)
          : 0,
    );
  /** "Copy option labels and internal names": one "label;internal name" line per option. */
  const copyOptions = async () => {
    const text = liveOptions.map((o) => `${o.label};${o.value}`).join('\n');
    try {
      await navigator.clipboard.writeText(text);
      toast('Option labels and internal names copied', 'success');
    } catch {
      toast("Couldn't copy to the clipboard", 'danger');
    }
  };
  const dirty = JSON.stringify(d) !== JSON.stringify(initial);
  // Create and clone: a label or internal name the API would refuse (#248, HubSpot's check: the
  // user's call). Edit saves stay as they were.
  const duplicate = editing
    ? null
    : duplicateNotice(model, object.key, { label: d.label, name: shownName });
  const valid =
    d.label.trim() &&
    !duplicate &&
    /^[a-z][a-z0-9_]{0,63}$/.test(shownName) &&
    (!withOptions ||
      (liveOptions.length > 0 && d.options.every((o) => o.label.trim() && o.value.trim()))) &&
    (worked !== 'calculation' || d.formula.trim()) &&
    !rollupIssue &&
    !rules.error;
  const canSave = !readOnly && !busy && Boolean(valid) && (!editing || dirty);
  const [fill, setFill] = useState<{ filled: number; total: number } | null>(null);
  const assetCount = propertyAssetCount(usage);

  const cancel = () => {
    if (dirty && !readOnly) setConfirmDiscard(true);
    else onClose();
  };

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !confirmDiscard && !document.querySelector('.dm-pop')) cancel();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  });

  const save = async () => {
    if (!canSave) return;
    if (d.access === 'assigned' && !hasAssignees(d.assignees)) {
      setSection('access');
      toast('Choose at least one user or team', 'danger');
      return;
    }
    // #557: repeated internal names (the design) or labels (HubSpot), back to Field type.
    const optionProblem = withOptions
      ? optionSaveProblem(d.options, editing ? (property?.options ?? null) : null)
      : null;
    if (optionProblem) {
      setSection('type');
      toast(optionProblem, 'danger');
      return;
    }
    setBusy(true);
    try {
      const groupName = d.group === NONE ? undefined : d.group;
      const cleanOptions = withOptions
        ? d.options.map((o) => ({
            label: o.label.trim(),
            value: o.value.trim(),
            ...(o.archived ? { archived: true } : {}),
            // DMG8 (C4).
            ...(o.description?.trim() ? { description: o.description.trim() } : {}),
          }))
        : undefined;
      // DMG8 (C1): a default must be a live option (one archived or removed since drops it).
      const defaultOut =
        canDefault && defaultChoices.some((c) => c.value === d.defaultValue) ? d.defaultValue : '';
      let saved: CustomPropertyDefinition;
      if (editing) {
        // A new type first: the API converts the values records hold, or says why it can't.
        if (typeChanged) {
          await changeCustomPropertyType(property.id, {
            type: k.type,
            fieldType: k.fieldType ?? null,
            ...(cleanOptions ? { options: cleanOptions } : {}),
          });
        }
        saved = await updateCustomProperty(property.id, {
          // #737: refused when another person saved this field after it was opened here. A type
          // change has just saved the field, so it isn't checked then.
          ...(openedAt && !typeChanged ? { ifUnmodifiedSince: openedAt } : {}),
          ...(kindChanged && !typeChanged ? { fieldType: k.fieldType ?? null } : {}),
          label: d.label.trim(),
          groupName: groupName ?? null,
          description: d.desc.trim() || null,
          instructions: d.instructions.trim() || null,
          required: d.required,
          ...(canBeUnique ? { unique: d.unique } : {}),
          ...(cleanOptions ? { options: cleanOptions } : {}),
          ...showInFormsUpdate(initial.showInForms, d),
          ...(d.access !== initial.access || !sameAssignees(d.assignees, initial.assignees)
            ? accessBody(d.access, d.assignees)
            : {}),
          ...(JSON.stringify(rules.rules) !== JSON.stringify(initialRules)
            ? { validation: rules.rules }
            : {}),
          ...(worked === 'calculation' ? formulaPatch(initial.formula, d.formula) : {}),
          ...(defaultOut !== initial.defaultValue ? { defaultValue: defaultOut || null } : {}),
          ...(withOptions && d.optionStyle !== initial.optionStyle
            ? { optionStyle: d.optionStyle }
            : {}),
          ...(crmUser ? crmUserSettingsPatch(initial, d) : {}),
          ...(withOptions && JSON.stringify(d.conditional) !== JSON.stringify(initial.conditional)
            ? {
                conditionalOptions:
                  d.conditional && Object.keys(d.conditional.byValue).length ? d.conditional : null,
              }
            : {}),
        });
        toast(`Property "${saved.label}" saved`, 'success');
      } else {
        const how = createTypeBody(k, d, rollupOut, cleanOptions);
        // canSave waits for the rollup to be complete, so this is a guard only.
        if (!how) return;
        saved = await createCustomProperty({
          objectType: object.key,
          name: shownName,
          label: d.label.trim(),
          ...how,
          required: canBeRequired && d.required,
          ...(canBeUnique && d.unique ? { unique: true } : {}),
          ...(groupName ? { groupName } : {}),
          ...(d.desc.trim() ? { description: d.desc.trim() } : {}),
          ...(d.instructions.trim() ? { instructions: d.instructions.trim() } : {}),
          ...showInFormsCreate(d),
          ...(d.access !== 'everyone_edit' ? accessBody(d.access, d.assignees) : {}),
          ...(rules.rules ? { validation: rules.rules } : {}),
          ...(defaultOut ? { defaultValue: defaultOut } : {}),
          ...(withOptions && d.optionStyle !== 'default' ? { optionStyle: d.optionStyle } : {}),
          ...(crmUser && d.multipleUsers ? { multipleUsers: true } : {}),
          ...(crmUser && d.userTeamIds.length ? { userTeamIds: d.userTeamIds } : {}),
        });
        toast(`Property "${saved.label}" created`, 'success');
      }
      onSaved(saved);
      onClose();
    } catch (err) {
      // A create or clone refused for a taken label or internal name: the design's words, and
      // back to Details, where both are (#248; assetsUI/data-model-assets-27-10-2026/…/data-model.js
      // :1144). Edit saves stay as they were.
      const conflict = editing
        ? null
        : createConflictNotice(err, { label: d.label.trim(), name: shownName });
      if (conflict) setSection(conflict.section);
      toast(conflict?.message ?? errorText(err), 'danger');
      setFormulaError(worked === 'calculation' ? formulaErrorOf(err) : null);
    } finally {
      setBusy(false);
    }
  };

  const setKind = (next: string) => {
    const nk = FIELD_KINDS.find((x) => x.value === next)!;
    set({
      kind: next,
      ...(isOptionType(nk.type) && !d.options.length
        ? {
            options: [
              { label: 'Option 1', value: 'option_1' },
              { label: 'Option 2', value: 'option_2' },
            ],
          }
        : {}),
      ...(nk.type === 'text' || nk.type === 'number' ? {} : { unique: false }),
      ...(nk.worked || isFileKind(nk) ? { required: false, unique: false } : {}),
      ...(nk.worked === 'rollup' || nk.worked === 'sync'
        ? { rollup: switchRollup(d.rollup, nk.worked === 'sync') }
        : {}),
    });
  };
  const setOption = (i: number, patch: Partial<PropertyOption>) =>
    set({ options: d.options.map((o, j) => (j === i ? { ...o, ...patch } : o)) });
  /** Options show on records in this order: the design's Order box (data-model.js:1318-1320). */
  const moveOptionTo = (i: number, place: number) => {
    const to = Math.max(1, Math.min(d.options.length, Math.round(place) || 1)) - 1;
    if (to === i) return;
    const next = [...d.options];
    const [o] = next.splice(i, 1);
    next.splice(to, 0, o!);
    set({ options: next });
    setOptPicked(new Set());
    setOptionSort('custom');
  };
  /** C3: "Delete N selected" removes new options; saved ones can only be archived (as Clear all). */
  const deletePicked = () => {
    set({
      options: d.options
        .map((o, i) =>
          optPicked.has(i) && fixedValues.has(o.value) ? { ...o, archived: true } : o,
        )
        .filter((o, i) => !(optPicked.has(i) && !fixedValues.has(o.value))),
    });
    setOptPicked(new Set());
  };
  /** "Load options": one label per line, added after the others; repeats are skipped. */
  const loadOptions = (text: string) => {
    const have = new Set(d.options.map((o) => o.label.trim().toLowerCase()));
    const values = new Set(d.options.map((o) => o.value));
    const added: PropertyOption[] = [];
    for (const line of text.split(/\r?\n/)) {
      const label = line.trim();
      if (!label || have.has(label.toLowerCase())) continue;
      have.add(label.toLowerCase());
      let value = toInternalName(label) || `option_${values.size + 1}`;
      for (let n = 2; values.has(value); n++) value = `${toInternalName(label) || 'option'}_${n}`;
      values.add(value);
      added.push({ label, value });
    }
    set({ options: [...d.options, ...added] });
    return added.length;
  };

  const nav: Array<[string] | [Section, string, boolean?]> = [
    [editing ? 'Manage' : 'Create property'],
    ['details', 'Details'],
    ['type', 'Field type'],
    ['docs', 'Documentation'],
    ['rules', 'Rules'],
    // Dropdown, radio and checkbox fields only, as the design.
    ...(withOptions && !fieldOnly
      ? ([['conditional', 'Conditional options']] as Array<[Section, string]>)
      : []),
    ['access', 'Manage access'],
    ['preview', 'Preview'],
    ...(fieldOnly
      ? []
      : ([['Data Agent'], ['smart', 'Smart property prompt'], ['autofill', 'Auto-fill']] as Array<
          [string] | [Section, string]
        >)),
    ...(editing && !fieldOnly
      ? ([
          ['Monitor'],
          ['usage', `Usage (${usage === undefined ? '…' : assetCount})`],
          ['quality', 'Data quality (0)'],
          ['sources', 'Data sources'],
        ] as Array<[string] | [Section, string]>)
      : []),
  ];

  const banner =
    lock.banner === 'crm' ? (
      <div className="dm-pe__banner">
        This property is provided by CRM and can&apos;t be edited.
      </div>
    ) : lock.banner === 'view-only' ? (
      <div className="dm-pe__banner">{viewOnlyText}.</div>
    ) : editing && calculated ? (
      <div className="dm-pe__banner">
        The CRM works out this property&apos;s value, so nobody types it in. Its label, group,
        documentation and access can still be changed.
      </div>
    ) : null;
  const head = (title: string, text?: React.ReactNode) => (
    <div className="dm-pe__head">
      <h2>{title}</h2>
      {text && <p>{text}</p>}
    </div>
  );

  let body: React.ReactNode;
  if (section === 'details') {
    body = (
      <>
        {head(
          'Add property details',
          <>
            In CRM, data is stored in properties. After you create new properties, you can edit them
            in {/* Plain text for someone Settings › Properties would not open for. */}
            {!settingsLinks ? (
              'Property Settings'
            ) : (
              <Link href={`/settings/properties?object=${encodeURIComponent(object.key)}`}>
                Property Settings <DmIcon name="external" size={13} />
              </Link>
            )}
          </>,
        )}
        <label className="dm-field">
          <span className="dm-field__label">Property label *</span>
          <input
            className={cn('dm-input', duplicate && 'is-invalid')}
            type="text"
            value={d.label}
            maxLength={191}
            autoComplete="off"
            disabled={readOnly}
            aria-invalid={Boolean(duplicate)}
            onChange={(e) => set({ label: e.target.value })}
          />
          {duplicate && <span className="dm-field__error">{duplicate}</span>}
        </label>
        <div className="dm-pe__internal">
          <span className="dm-pe__internal-l">Internal name:</span>
          {!editing && editName ? (
            <input
              className={cn(
                'dm-input dm-input--sm',
                shownName && !/^[a-z][a-z0-9_]{0,63}$/.test(shownName) && 'is-invalid',
              )}
              type="text"
              value={shownName}
              aria-label="Internal name"
              onChange={(e) => {
                setNameEdited(true);
                set({ name: e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '_') });
              }}
            />
          ) : (
            <>
              <code>{shownName || '—'}</code>
              {!editing && (
                <button
                  type="button"
                  className="dm-icon-btn dm-icon-btn--xs"
                  aria-label="Edit internal name"
                  title="Used by integrations and the API. It can't be changed after the property is created."
                  onClick={() => setEditName(true)}
                >
                  <DmIcon name="pencil" size={13} />
                </button>
              )}
            </>
          )}
        </div>
        <div className="dm-field">
          <span className="dm-field__label">Object type *</span>
          {onObjectChange && mode === 'create' && !readOnly ? (
            <SelectMenu
              value={object.key}
              options={model.objects
                .filter((x) => x.active && !(x.catalog && !x.fieldOnly))
                .sort((a, b) => byText(a.singular, b.singular))
                .map((x) => ({ value: x.key, label: x.singular }))}
              onChange={(key) => {
                const next = model.objects.find((x) => x.key === key);
                if (!next || key === object.key) return;
                // The design moves the group to the new object's own (data-model.js:1278).
                set({ group: defaultGroupName(liveGroups(model, key), next) ?? NONE });
                onObjectChange(key);
              }}
              ariaLabel="Object type"
              search
            />
          ) : (
            <span className="dm-select">
              <span className="dm-select__btn is-ro" aria-label="Object type (fixed)">
                <span>{object.singular}</span>
              </span>
            </span>
          )}
        </div>
        <div className="dm-field">
          <span className="dm-field__label">Group *</span>
          <SelectMenu
            value={d.group}
            options={[
              { value: NONE, label: 'No group' },
              ...groups.map((g) => ({ value: g.name, label: g.label })),
            ]}
            onChange={(group) => set({ group })}
            search={groups.length > 8}
            ariaLabel="Group"
            disabled={readOnly}
          />
        </div>
        <div className="dm-pe__note">
          <p>Description has moved to the Documentation settings.</p>
          <button type="button" className="dm-link-strong" onClick={() => setSection('docs')}>
            View and edit documentation
          </button>
        </div>
      </>
    );
  } else if (section === 'type') {
    body = (
      <>
        {head('Choose a field type')}
        <div className="dm-field">
          <span className="dm-field__label">Field type *</span>
          {/* Not offered to someone Settings › Properties would not open for. */}
          {settingsLinks && (
            <Link
              className="dm-pe__learn"
              href={`/settings/properties?object=${encodeURIComponent(object.key)}`}
            >
              Learn more about field types <DmIcon name="external" size={12} />
            </Link>
          )}
          {editing && !typeEditable ? (
            <span className="dm-select">
              <span className="dm-select__btn is-ro" aria-label="Field type (fixed)">
                <span>
                  <TypeIcon label={fieldTypeLabel(property)} />
                  {fieldTypeLabel(property)}
                </span>
              </span>
            </span>
          ) : (
            <SelectMenu
              value={d.kind}
              options={kinds.map((x) => ({ value: x.value, label: x.label }))}
              onChange={setKind}
              search
              ariaLabel="Field type"
              icon={(v) => <TypeIcon label={FIELD_KINDS.find((x) => x.value === v)!.label} />}
            />
          )}
          {editing && !typeEditable && (
            <span className="dm-field__hint">
              The type of {calculated ? 'a calculated' : 'this'} property can&apos;t change.
            </span>
          )}
          {editing && typeChanged && (
            <div className="dm-pe__note">
              <p>
                Saving converts the values records hold to the new type. It is refused if any value
                would be lost, or while lists, workflows, forms, reports or conditional logic use
                this property.
              </p>
            </div>
          )}
          {formula && (
            <div className="dm-pe__note">
              <p>
                <b>Calculation:</b> {formula}
              </p>
            </div>
          )}
        </div>
        {worked === 'calculation' && (
          <CalculationFields
            expression={d.formula}
            resultType={d.resultType}
            typeFixed={editing}
            disabled={readOnly}
            error={formulaError}
            onChange={(patch) => {
              if (patch.formula !== undefined) setFormulaError(null);
              set(patch);
            }}
          />
        )}
        {isRollup && (
          <RollupFields
            object={object}
            model={model}
            sync={worked === 'sync'}
            value={d.rollup}
            {...rollupData}
            problem={rollupIssue}
            disabled={readOnly || editing}
            onChange={(rollup) => set({ rollup })}
          />
        )}
        {isRollup && editing && (
          <span className="dm-field__hint">
            How a saved {worked === 'sync' ? 'property sync' : 'rollup'} is worked out can&apos;t
            change here.
          </span>
        )}
        {/* DMG9: the design's CRM user settings (data-model.js:1176-1195). */}
        {crmUser && (
          <CrmUserFields
            propertyId={editing ? property.id : null}
            objectKey={object.key}
            multipleUsers={d.multipleUsers}
            userTeamIds={d.userTeamIds}
            readOnly={readOnly}
            settingsLinks={settingsLinks}
            onChange={set}
          />
        )}
        {/* DMG8 (C6): the design's Number format (data-model.js:1196-1197). */}
        {!worked && NUMBER_FORMATS.some(([kind]) => kind === d.kind) && (
          <div className="dm-field">
            <span className="dm-field__label">Number format *</span>
            <SelectMenu
              value={d.kind}
              options={NUMBER_FORMATS.map(([value, label]) => ({ value, label }))}
              onChange={setKind}
              ariaLabel="Number format"
              disabled={readOnly}
            />
          </div>
        )}
        {/* DMG8 (C1): the design's Default value (data-model.js:1140-1145). */}
        {canDefault && (
          <div className="dm-field">
            <span className="dm-field__label">Default value</span>
            <span className="dm-field__hint">
              This value will be automatically filled in whenever a new record is created
            </span>
            <SelectMenu
              value={defaultChoices.some((c) => c.value === d.defaultValue) ? d.defaultValue : ''}
              options={[{ value: '', label: 'No default value' }, ...defaultChoices]}
              onChange={(v) => set({ defaultValue: v })}
              placeholder="Select default value"
              ariaLabel="Default value"
              disabled={readOnly}
            />
          </div>
        )}
        {/* DMG8 (C2): the design's Option style (data-model.js:1146-1152). */}
        {withOptions && (
          <div className="dm-field">
            <span className="dm-field__label">Option style *</span>
            <div className="dm-pe__styles" role="radiogroup" aria-label="Option style">
              {OPTION_STYLES.map(([value, label]) => (
                <button
                  key={value}
                  type="button"
                  role="radio"
                  aria-checked={d.optionStyle === value}
                  className={cn('dm-pe__style', d.optionStyle === value && 'is-active')}
                  disabled={readOnly}
                  onClick={() => set({ optionStyle: value })}
                >
                  {value === 'dot' ? (
                    <>
                      <i className="dm-pe__dot" />
                      {label}
                    </>
                  ) : value === 'badge' ? (
                    <span className="dm-pe__badge">{label}</span>
                  ) : (
                    label
                  )}
                </button>
              ))}
            </div>
          </div>
        )}
        {withOptions && (
          <div className="dm-field">
            <div className="dm-pe__optshead">
              <b>
                {k.type === 'select' ? 'Dropdown options' : 'Options'} ({liveOptions.length})
              </b>
              {optPicked.size > 0 && !readOnly && (
                <button
                  type="button"
                  className="dm-link-strong dm-pe__danger"
                  onClick={deletePicked}
                >
                  {[...optPicked].every((i) => fixedValues.has(d.options[i]?.value ?? ''))
                    ? `Archive ${optPicked.size} selected`
                    : `Delete ${optPicked.size} selected`}
                </button>
              )}
              {!readOnly && (
                <span style={{ display: 'inline-flex', gap: 12, marginLeft: 'auto' }}>
                  <button type="button" className="dm-link-strong" onClick={() => setLoading('')}>
                    Load options
                  </button>
                  <button
                    type="button"
                    className="dm-link-strong"
                    disabled={!liveOptions.length}
                    onClick={() => setClearing(true)}
                  >
                    Clear all options
                  </button>
                </span>
              )}
            </div>
            <div className="dm-pe__opttools">
              <div className="dm-pe__opttabs" role="tablist" aria-label="Options">
                {(
                  [
                    ['active', `Active (${liveOptions.length})`],
                    ['archived', `Archived (${archivedCount})`],
                  ] as const
                ).map(([key, text]) => (
                  <button
                    key={key}
                    type="button"
                    role="tab"
                    aria-selected={optionTab === key}
                    className={cn('dm-pe__opttab', optionTab === key && 'is-active')}
                    onClick={() => setOptionTab(key)}
                  >
                    {text}
                  </button>
                ))}
              </div>
              <input
                className="dm-input dm-input--sm dm-pe__optsearch"
                type="search"
                placeholder="Search options"
                aria-label="Search options"
                value={optionSearch}
                onChange={(e) => setOptionSearch(e.target.value)}
              />
              <SelectMenu
                value={optionSort}
                options={[
                  { value: 'custom', label: 'Custom' },
                  { value: 'az', label: 'Alphabetical (A-Z)' },
                  { value: 'za', label: 'Alphabetical (Z-A)' },
                ]}
                onChange={setOptionSort}
                ariaLabel="Sort options"
              />
              <button
                type="button"
                className="dm-link-strong"
                disabled={!liveOptions.length}
                onClick={() => void copyOptions()}
              >
                Copy option labels and internal names
              </button>
            </div>
            {editing && (
              <span className="dm-field__hint">
                Saved options keep their internal name; archive one to stop it being chosen.
              </span>
            )}
            <div className="dm-table-wrap">
              <table className="dm-table dm-pe__opts">
                <thead>
                  <tr>
                    <th className="dm-pe__opts-c">
                      <input
                        type="checkbox"
                        aria-label="Select all options"
                        checked={
                          shownOptions.length > 0 && shownOptions.every(({ i }) => optPicked.has(i))
                        }
                        disabled={readOnly || !shownOptions.length}
                        onChange={(e) =>
                          setOptPicked(
                            e.target.checked ? new Set(shownOptions.map(({ i }) => i)) : new Set(),
                          )
                        }
                      />
                    </th>
                    <th className="dm-pe__opts-o">Order</th>
                    <th>Label</th>
                    <th>Internal name</th>
                    <th aria-label="Actions" />
                  </tr>
                </thead>
                <tbody>
                  {!shownOptions.length && (
                    <tr>
                      <td colSpan={5} className="dm-muted">
                        {optionQuery
                          ? 'No options match your search.'
                          : optionTab === 'archived'
                            ? 'No archived options.'
                            : 'No options yet. Add an option to get started.'}
                      </td>
                    </tr>
                  )}
                  {shownOptions.map(({ o, i }) => {
                    const fixed = fixedValues.has(o.value);
                    return (
                      <tr key={i} className={o.archived ? 'is-inactive' : undefined}>
                        <td className="dm-pe__opts-c">
                          <span className="dm-pe__grip" aria-hidden>
                            <DmIcon name="grip" size={14} />
                          </span>
                          <input
                            type="checkbox"
                            aria-label={`Select ${o.label || 'option'}`}
                            checked={optPicked.has(i)}
                            disabled={readOnly}
                            onChange={(e) =>
                              setOptPicked((cur) => {
                                const next = new Set(cur);
                                if (e.target.checked) next.add(i);
                                else next.delete(i);
                                return next;
                              })
                            }
                          />
                        </td>
                        <td className="dm-pe__opts-o">
                          <input
                            key={`${o.value}-${i}`}
                            className="dm-input dm-input--sm"
                            type="number"
                            min={1}
                            max={d.options.length}
                            defaultValue={i + 1}
                            aria-label={`Order of ${o.label || 'option'}`}
                            disabled={readOnly || o.archived}
                            onBlur={(e) => moveOptionTo(i, Number(e.target.value))}
                            onKeyDown={(e) => {
                              if (e.key === 'Enter') e.currentTarget.blur();
                            }}
                          />
                        </td>
                        <td>
                          <input
                            className={cn('dm-input dm-input--sm', !o.label.trim() && 'is-invalid')}
                            type="text"
                            value={o.label}
                            aria-label="Option label"
                            disabled={o.archived || readOnly}
                            onChange={(e) =>
                              setOption(i, {
                                label: e.target.value,
                                ...(fixed
                                  ? {}
                                  : { value: toInternalName(e.target.value) || o.value }),
                              })
                            }
                          />
                        </td>
                        <td>
                          <input
                            className={cn('dm-input dm-input--sm', !o.value.trim() && 'is-invalid')}
                            type="text"
                            value={o.value}
                            aria-label="Option internal name"
                            disabled={fixed || readOnly}
                            onChange={(e) => setOption(i, { value: e.target.value })}
                          />
                        </td>
                        <td>
                          {readOnly ? null : fixed ? (
                            <button
                              type="button"
                              className="dm-link-strong"
                              onClick={() => setOption(i, { archived: !o.archived })}
                            >
                              {o.archived ? 'Restore' : 'Archive'}
                            </button>
                          ) : (
                            <button
                              type="button"
                              className="dm-icon-btn"
                              aria-label={`Remove ${o.label || 'option'}`}
                              onClick={() => set({ options: d.options.filter((_, j) => j !== i) })}
                            >
                              <DmIcon name="trash" />
                            </button>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
            {!readOnly && (
              <button
                type="button"
                className="dm-link-strong dm-co__add"
                onClick={() => {
                  const n = d.options.length + 1;
                  set({ options: [...d.options, { label: `Option ${n}`, value: `option_${n}` }] });
                  // The new option shows in the active list.
                  setOptionTab('active');
                  setOptionSearch('');
                }}
              >
                <DmIcon name="plus" size={14} />
                Add option
              </button>
            )}
          </div>
        )}
        {/* Nobody types a worked-out or File value, so it is never required. */}
        {canBeRequired && !fieldOnly && (
          <label className="dm-check dm-check--plain">
            <input
              type="checkbox"
              checked={d.required}
              disabled={readOnly || calculated}
              onChange={(e) => set({ required: e.target.checked })}
            />
            <span>Required when a record is created</span>
          </label>
        )}
      </>
    );
  } else if (section === 'rules') {
    // The design's "Property rules": visibility in forms, unique values and the validation
    // rules (HUB-354). Read-only, calculated and built-in fields have no visibility box.
    body = (
      <>
        {head('Property rules')}
        {formsBox.shown && (
          <fieldset className="dm-field dm-pe__fs">
            <legend className="dm-field__label">Visibility options</legend>
            <label className="dm-check dm-check--plain">
              <input
                type="checkbox"
                checked={showInFormsValue(d)}
                disabled={formsBox.disabled}
                onChange={(e) => set({ showInForms: e.target.checked })}
              />
              <span>Show property in forms</span>
            </label>
            <span className="dm-field__hint">
              Offers the property when building forms. Forms it is already on keep it.
            </span>
            {formsBox.reason && <span className="dm-field__hint">{formsBox.reason}</span>}
            {onCreateForm && !showInFormsValue(d) && (
              <span className="dm-field__hint">
                It is on the Create {object.singular.toLowerCase()} form
                {onCreateForm.required ? ', as a required field' : ''}, and stays there until it is
                removed in the form editor.
              </span>
            )}
          </fieldset>
        )}
        {worked ? (
          <p className="dm-pe__msg">
            The CRM works out this property&apos;s value, so it has no rules.
          </p>
        ) : (
          !canBeUnique &&
          (property?.calculated || !ruleKind) && (
            <p className="dm-pe__msg">
              Validation rules are available for text and number properties.
            </p>
          )
        )}
        {canBeUnique && (
          <label className="dm-check dm-check--plain">
            <input
              type="checkbox"
              checked={d.unique}
              disabled={readOnly || calculated}
              onChange={(e) => set({ unique: e.target.checked })}
            />
            <span>Require unique values for this property</span>
          </label>
        )}
        <ValidationRulesFields
          kind={property?.calculated ? null : ruleKind}
          value={d.rules}
          error={rules.error}
          disabled={readOnly}
          onChange={(patch) => set({ rules: { ...d.rules, ...patch } })}
        />
      </>
    );
  } else if (section === 'conditional') {
    body = (
      <>
        {head(
          'Conditional options',
          'Show different options for this property based on the value of another property.',
        )}
        {mode !== 'edit' ? (
          <p className="dm-pe__msg">Save the property first, then set its conditional options.</p>
        ) : (
          <ConditionalOptionsFields
            controls={customProperties(model, object.key).filter(
              (p) =>
                p.name !== d.name &&
                !p.archived &&
                (p.type === 'select' || p.type === 'multiselect' || p.type === 'boolean'),
            )}
            options={d.options.filter((o) => !o.archived)}
            value={d.conditional}
            disabled={readOnly}
            onChange={(conditional) => set({ conditional })}
          />
        )}
      </>
    );
  } else if (section === 'quality' || section === 'sources') {
    body = (
      <>
        {head(
          section === 'quality' ? 'Data quality' : 'Data sources',
          section === 'quality'
            ? 'Issues found in the values of this property.'
            : 'Where the values of this property come from.',
        )}
        <p className="dm-pe__msg">
          {section === 'quality'
            ? 'No data quality issues found for this property.'
            : "Data sources aren't available in this CRM yet."}
        </p>
      </>
    );
  } else if (section === 'docs') {
    body = (
      <>
        {head(
          'Property documentation',
          'Documentation improves the quality of results from agents. Property descriptions are also visible in the CRM.',
        )}
        {withOptions && (
          <div className="dm-pe__opttabs" role="tablist" aria-label="Documentation">
            {(
              [
                ['text', 'Description and Instructions'],
                ['options', `Option descriptions (${liveOptions.length})`],
              ] as const
            ).map(([key, text]) => (
              <button
                key={key}
                type="button"
                role="tab"
                aria-selected={docTab === key}
                className={cn('dm-pe__opttab', docTab === key && 'is-active')}
                onClick={() => setDocTab(key)}
              >
                {text}
              </button>
            ))}
          </div>
        )}
        {withOptions && docTab === 'options' ? (
          liveOptions.length ? (
            d.options.map((o, i) =>
              o.archived ? null : (
                <label key={i} className="dm-field">
                  <span className="dm-field__label">{o.label || 'Untitled option'}</span>
                  <textarea
                    className="dm-textarea"
                    rows={2}
                    maxLength={1000}
                    value={o.description ?? ''}
                    disabled={readOnly}
                    onChange={(e) => setOption(i, { description: e.target.value })}
                  />
                </label>
              ),
            )
          ) : (
            <p className="dm-muted">Add options in Field type to describe them here.</p>
          )
        ) : (
          <>
            <label className="dm-field">
              <span className="dm-field__label">Property description</span>
              <span className="dm-field__hint">
                Explains what this property represents and how its data is used.
              </span>
              <textarea
                className="dm-textarea"
                rows={4}
                maxLength={2000}
                value={d.desc}
                disabled={readOnly}
                onChange={(e) => set({ desc: e.target.value })}
              />
            </label>
            <label className="dm-field">
              <span className="dm-field__label">Data entry instructions</span>
              <span className="dm-field__hint">
                Explains how this property should be completed by users and agents.
              </span>
              <textarea
                className="dm-textarea"
                rows={4}
                maxLength={5000}
                value={d.instructions}
                disabled={readOnly}
                onChange={(e) => set({ instructions: e.target.value })}
              />
            </label>
          </>
        )}
      </>
    );
  } else if (section === 'access') {
    // HUB-226. CRM fields open read-only (the banner says so): their access never changes.
    body = (
      <>
        {head(
          'Manage property access',
          'Customize the level of access users and teams have to this property. Super admins always see and edit it.',
        )}
        <div role="radiogroup" aria-label="Property access">
          {accessChoices(publicEnv().NEXT_PUBLIC_ASSIGNED_ACCESS, initial.access).map((choice) => (
            <label key={choice.value} className="dm-check dm-check--plain">
              <input
                type="radio"
                name="dm-pe-access"
                value={choice.value}
                checked={d.access === choice.value}
                disabled={readOnly}
                onChange={() => set({ access: choice.value })}
              />
              <span>{choice.label}</span>
            </label>
          ))}
        </div>
        {d.access === 'assigned' && (
          <AccessAssigneesField
            value={d.assignees}
            disabled={readOnly}
            onChange={(assignees) => set({ assignees })}
          />
        )}
      </>
    );
  } else if (section === 'preview') {
    body = (
      <>
        {head('Preview your property')}
        <div className="dm-pe__preview">
          <span className="dm-field__label">{d.label || 'New property'}</span>
          <PreviewControl
            kind={d.kind}
            options={liveOptions}
            optionStyle={d.optionStyle}
            defaultValue={d.defaultValue}
          />
        </div>
      </>
    );
  } else if (section === 'smart' || section === 'autofill') {
    body = (
      <>
        {head(
          section === 'smart' ? 'Data Agent smart property' : 'Auto-fill',
          section === 'smart'
            ? 'Automatically fill in property values by generating and extracting data from a variety of sources.'
            : 'Re-run smart property when selected events occur.',
        )}
        <p className="dm-pe__msg">Data Agent isn&apos;t available in this CRM yet.</p>
      </>
    );
  } else if (section === 'usage') {
    body = (
      <>
        <div className="dm-pe__head">
          <h2>
            {d.label} is used in {assetCount} place{assetCount === 1 ? '' : 's'}
          </h2>
        </div>
        {fill && (
          <div className="dm-pe__fill">
            <h3>{object.singular} fill rate for this property</h3>
            <p>
              <b>
                {fill.total ? `${Math.round((fill.filled / fill.total) * 10000) / 100}%` : '0%'}
              </b>{' '}
              {fill.filled.toLocaleString('en-US')} out of {fill.total.toLocaleString('en-US')}
            </p>
            {object.page && (
              <Link className="dm-btn dm-btn--outline dm-btn--sm" href={object.page}>
                Review {object.name} <DmIcon name="external" size={13} />
              </Link>
            )}
          </div>
        )}
        {usage === undefined ? (
          <p className="dm-muted">Loading…</p>
        ) : assetCount === 0 ? (
          <p className="dm-muted">
            This property isn&apos;t used in any dashboards, reports, workflows, lists or forms yet.
          </p>
        ) : (
          PROPERTY_ASSET_KINDS.map(([kind, title]) => {
            const assets: Array<{ id: string; name: string; dashboardId?: string }> =
              usage?.[kind] ?? [];
            return assets.length ? (
              <section key={kind}>
                <h3 className="dm-pe__h3">
                  {title} ({assets.length})
                </h3>
                <ul className="dm-assets__list">
                  {assets.map((a) => {
                    const to = propertyAssetHref(kind, a);
                    return <li key={a.id}>{to ? <Link href={to}>{a.name}</Link> : a.name}</li>;
                  })}
                </ul>
              </section>
            ) : null;
          })
        )}
      </>
    );
  }

  return createPortal(
    <div
      className="dm-pe"
      role="dialog"
      aria-modal="true"
      aria-label={`${editing ? 'Edit property' : 'Create property'}: ${d.label || 'New property'}`}
    >
      <header className="dm-pe__bar">
        <span className="dm-pe__bar-side" aria-hidden />
        <div className="dm-pe__title">
          <h2>{d.label || 'New property'}</h2>
          <span>{object.singular}</span>
        </div>
        <div className="dm-pe__acts">
          <button type="button" className="dm-pe__btn" onClick={cancel}>
            Cancel
          </button>
          <button
            type="button"
            className={cn('dm-pe__btn dm-pe__btn--solid', busy && 'is-loading')}
            disabled={!canSave}
            onClick={() => void save()}
          >
            {editing ? 'Save' : 'Create'}
          </button>
        </div>
      </header>
      <div className="dm-pe__main">
        <nav className="dm-pe__nav" aria-label="Property settings">
          {nav.map((it, i) =>
            it.length === 1 ? (
              <div key={it[0]}>
                {i > 0 && <span className="dm-pe__navdiv" role="separator" />}
                <h3>{it[0]}</h3>
              </div>
            ) : (
              <button
                key={it[0]}
                type="button"
                className={cn('dm-pe__navlink', section === it[0] && 'is-active')}
                aria-current={section === it[0] ? 'true' : undefined}
                disabled={it[2]}
                aria-disabled={it[2] || undefined}
                onClick={() => setSection(it[0])}
              >
                {it[1]}
              </button>
            ),
          )}
        </nav>
        <div className="dm-pe__body">
          <div className={cn('dm-pe__inner', section === 'type' && 'dm-pe__inner--wide')}>
            {banner}
            {body}
          </div>
        </div>
      </div>
      {/* C3 (DMG7): the design asks first (data-model.js:1290-1293). Saved options are archived,
          as the API keeps them; new ones go. */}
      {clearing && (
        <Modal
          title="Clear all options?"
          okLabel="Clear all options"
          danger
          onClose={() => setClearing(false)}
          onOk={() => {
            set({
              options: d.options
                .filter((o) => fixedValues.has(o.value))
                .map((o) => ({ ...o, archived: true })),
            });
            setOptPicked(new Set());
          }}
        >
          <p className="dm-muted">
            All {liveOptions.length} options will be removed from this property.
          </p>
        </Modal>
      )}
      {loading !== null && (
        <Modal
          title="Load options"
          okLabel="Add options"
          okDisabled={!loading.trim()}
          onClose={() => setLoading(null)}
          onOk={() => {
            const n = loadOptions(loading);
            toast(
              n ? `${n} option${n === 1 ? '' : 's'} added` : 'No new options to add',
              'success',
            );
          }}
        >
          <label className="dm-field">
            <span className="dm-field__label">One option per line</span>
            <textarea
              className="dm-textarea"
              rows={8}
              autoFocus
              value={loading}
              onChange={(e) => setLoading(e.target.value)}
            />
          </label>
        </Modal>
      )}
      {confirmDiscard && (
        <Modal
          title="Discard changes?"
          okLabel="Discard changes"
          cancelLabel="Keep editing"
          danger
          onClose={() => setConfirmDiscard(false)}
          onOk={() => {
            onClose();
          }}
        >
          <p className="dm-muted">
            You have unsaved changes. If you cancel now, all your changes will be lost.{' '}
            <b>This action can&apos;t be undone.</b>
          </p>
        </Modal>
      )}
    </div>,
    document.body,
  );
}

/** How the field looks on a record (Preview). */
export function PreviewControl({
  kind,
  options,
  optionStyle = 'default',
  defaultValue = '',
}: {
  kind: string;
  options: PropertyOption[];
  /** DMG8 (C2): the dropdown's chosen option in this style (data-model.js:1208-1210). */
  optionStyle?: OptionStyle;
  defaultValue?: string;
}) {
  const k = FIELD_KINDS.find((x) => x.value === kind)!;
  if (k.worked) {
    return <input className="dm-input" disabled placeholder="Worked out by the CRM" />;
  }
  // #247: the design's File preview (data-model.js:1127), a button that does nothing.
  if (isFileKind(k)) {
    return (
      <button type="button" className="dm-btn dm-btn--outline dm-btn--sm">
        Upload file
      </button>
    );
  }
  if (k.fieldType === 'owner') {
    return (
      <select className="dm-input" defaultValue="">
        <option value="">Select a user</option>
      </select>
    );
  }
  if (k.type === 'boolean') {
    return (
      <label className="dm-check dm-check--plain">
        <input type="checkbox" />
        <span>Yes</span>
      </label>
    );
  }
  if (k.type === 'select' || k.type === 'multiselect') {
    if (k.fieldType === 'radio' || k.type === 'multiselect') {
      return (
        <div className="dm-pe__pvopts">
          {options.map((o) => (
            <label key={o.value} className="dm-check dm-check--plain">
              <input type={k.type === 'multiselect' ? 'checkbox' : 'radio'} name="dm-pe-preview" />
              <span>{o.label}</span>
            </label>
          ))}
        </div>
      );
    }
    const shown = options.find((o) => o.value === defaultValue) ?? options[0];
    if (shown && optionStyle !== 'default') {
      return (
        <span className="dm-select">
          <span className="dm-select__btn">
            <span>
              {optionStyle === 'dot' ? (
                <>
                  <i className="dm-pe__dot" />
                  {shown.label}
                </>
              ) : (
                <span className="dm-pe__badge">{shown.label}</span>
              )}
            </span>
          </span>
        </span>
      );
    }
    return (
      <select className="dm-input" defaultValue={shown && defaultValue ? shown.value : ''}>
        <option value="">Select an option</option>
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    );
  }
  if (k.type === 'textarea') return <textarea className="dm-textarea" rows={3} />;
  const inputType =
    k.type === 'number'
      ? 'number'
      : k.type === 'date'
        ? 'date'
        : k.type === 'datetime'
          ? 'datetime-local'
          : k.fieldType === 'email'
            ? 'email'
            : k.fieldType === 'url'
              ? 'url'
              : k.fieldType === 'phonenumber'
                ? 'tel'
                : 'text';
  return <input className="dm-input" type={inputType} />;
}

/**
 * The design's Conditional options (settings-properties.js:728-737), as HubSpot: a controlling
 * field, then for each of its values the options of this field to show. A value with nothing
 * ticked shows every option.
 */
function ConditionalOptionsFields({
  controls,
  options,
  value,
  disabled,
  onChange,
}: {
  controls: CustomPropertyDefinition[];
  options: PropertyOption[];
  value: ConditionalOptions | null;
  disabled: boolean;
  onChange: (next: ConditionalOptions | null) => void;
}) {
  const control = controls.find((c) => c.name === value?.controllingProperty);
  const controlValues: Array<{ value: string; label: string }> = control
    ? control.type === 'boolean'
      ? [
          { value: 'true', label: 'Yes' },
          { value: 'false', label: 'No' },
        ]
      : (control.options ?? []).filter((o) => !o.archived)
    : [];
  const toggle = (when: string, option: string, on: boolean) => {
    if (!value) return;
    const current = value.byValue[when] ?? [];
    const next = on ? [...current, option] : current.filter((o) => o !== option);
    const byValue = { ...value.byValue };
    if (next.length) byValue[when] = options.map((o) => o.value).filter((o) => next.includes(o));
    else delete byValue[when];
    onChange({ ...value, byValue });
  };
  return (
    <>
      <div className="dm-field">
        <span className="dm-field__label">Controlling property</span>
        <SelectMenu
          value={value?.controllingProperty ?? ''}
          options={[
            { value: '', label: 'Choose a property' },
            ...[...controls]
              .sort((a, b) => byText(a.label, b.label))
              .map((c) => ({ value: c.name, label: c.label })),
          ]}
          onChange={(name) => onChange(name ? { controllingProperty: name, byValue: {} } : null)}
          ariaLabel="Controlling property"
          disabled={disabled}
          search
        />
      </div>
      {control &&
        (controlValues.length ? (
          <div className="dm-condmap">
            {controlValues.map((cv) => (
              <fieldset key={cv.value} className="dm-condrow">
                <legend>
                  When <strong>{control.label}</strong> is <strong>{cv.label}</strong>, show:
                </legend>
                {options.length ? (
                  options.map((o) => (
                    <label key={o.value} className="dm-check dm-check--plain">
                      <input
                        type="checkbox"
                        checked={(value?.byValue[cv.value] ?? []).includes(o.value)}
                        disabled={disabled}
                        onChange={(e) => toggle(cv.value, o.value, e.target.checked)}
                      />
                      <span>{o.label}</span>
                    </label>
                  ))
                ) : (
                  <p className="dm-pe__msg">Add options to this property first.</p>
                )}
              </fieldset>
            ))}
          </div>
        ) : (
          <p className="dm-pe__msg">The controlling property has no options yet.</p>
        ))}
    </>
  );
}
