'use client';

import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Fragment, useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { publicEnv } from '@/config/env';
import {
  archiveAssociationLabel,
  createAssociationLabel,
  renameAssociationLabel,
} from '@/features/associations/api.client';
import { labelRows, limitBucket, matchesLabel, type LabelRow } from '../labelRows';
import type { AssociationLabel } from '@/features/associations/types';
import { CreateLabelDrawer, LabelHistoryModal, LabelLimitDrawer } from './LabelDialogs';
import { accessChoices } from '@/features/custom-properties/access-assignees';
import { allowObjectAssociation } from '@/features/objects/api.client';
import {
  archiveCustomProperty,
  deleteCustomProperty,
  isLockedField,
  listPropertyFillRates,
  PROPERTY_ACCESS_CHOICES,
  restoreCustomProperty,
  updateCustomProperty,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { listOwners } from '@/features/owners/api.client';
import { creatorOf, loadMemberNames, type MemberName } from '@/features/settings/createdBy';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { sortKey } from '@/lib/utils/sort-label';
import {
  createPropertyGroup,
  listPropertyUsage,
  setPropertyGroupArchived,
  setStandardPropertyGroup,
  updatePropertyGroup,
  type PropertyGroup,
  type PropertyUsage,
} from '../api.client';
import {
  associationsOf,
  byText,
  canLink,
  canRename,
  downloadFile,
  fieldTypeFilterLabels,
  fieldTypeLabel,
  groupLabel,
  isCrmProvided,
  labelText,
  labelsSeenBy,
  liveGroups,
  liveProperties,
  toCsv,
  type Cardinality,
  type DmObject,
  propertyAssetCount,
} from '../model';
import { ApiDetailsModal, EditLimitsModal } from './AssociationLabelModals';
import { useDm } from './DataModelView';
import { LogicSection } from './LogicSection';
import { DmIcon } from './icons';
import { exportDataModelImage } from './export-image';
import { ExportHistoryModal } from './ExportHistoryModal';
import { isCrmOwned } from './PropertyEditor';
import { FIXED_NAME_HINT } from './ManageTab';
import {
  ActionMenu,
  Canvas,
  CheckFilter,
  countLabel,
  DataTable,
  Dropdown,
  Modal,
  SearchBox,
  SelectMenu,
  ViewToggle,
  type Column,
  type MenuItem,
} from './primitives';
import {
  ApiRowsModal,
  ExportDefinitionModal,
  PropertyApiModal,
  PropertyHistoryDrawer,
} from './PropertyDialogs';
import { ArchivePropertyDrawer, CantArchiveDrawer } from './ArchiveDialogs';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { createdDayText, lastRunText } from '../zoneText';
import { ColumnChooser } from '@/features/list-page/ui/ColumnChooser';
import {
  ARCHIVED_SET,
  MAX_FROZEN,
  LABEL_SET,
  PROPERTY_SET,
  orderColumns,
  readColumnPrefs,
  saveColumnPrefs,
  type ColumnPrefs,
} from '../manageColumns';
import { nameInText } from '@/features/objects/paths';
import { lockItem, lockProps } from './viewOnly';

/** Objects the object switcher lists, in the design's order. */
const SWITCHER_OBJECTS = ['company', 'contact', 'deal', 'event', 'meeting', 'email', 'task'];

/**
 * DMG10 (B1/D1, the user's call, 20 Nov 2026): the design's sections and names
 * (data-model.js:2982-2989), in place of #725's tabs.
 */
const SUBS = [
  ['properties', 'All properties'],
  ['groups', 'Property groups'],
  ['archived', 'Archived properties'],
  ['associations', 'Associated objects'],
  ['association-labels', 'Association labels'],
  // HUB-355
  ['logic', 'Conditional logic'],
] as const;
type Sub = (typeof SUBS)[number][0];
/** The design's other names for these sections (data-model.php:57; data-model.js:2944-2948). */
const SUB_ALIASES: Record<string, Sub> = {
  'all-properties': 'properties',
  'archived-properties': 'archived',
  'associated-objects': 'associations',
  labels: 'association-labels',
};
/** The nav's two folding groups (data-model.js:3005-3021). */
const NAV_GROUPS = [
  { id: 'props', label: 'Properties', icon: 'text', subs: ['properties', 'groups', 'archived'] },
  {
    id: 'assoc',
    label: 'Associations',
    icon: 'assoc-fork',
    subs: ['associations', 'association-labels'],
  },
] as const;
const SUB_ICON: Record<Sub, string> = {
  properties: 'text',
  groups: 'folder',
  archived: 'archive',
  associations: 'assoc-fork',
  'association-labels': 'tag',
  logic: 'logic',
};

/** One object (renderObject): breadcrumb + switcher, "Manage object", and its sections. */
export function ObjectDetail({ object: o }: { object: DmObject }) {
  const { model, params, href, openProperty, openUsage, renameObject, setArchived, canEdit } =
    useDm();
  const toast = useToast();
  /** A write, or a link to an admin-only Settings page: off for a view-only user. */
  const lock = (item: MenuItem) => lockItem(item, canEdit);
  const rawSub = params.get('sub');
  const sub: Sub = SUBS.some(([k]) => k === rawSub)
    ? (rawSub as Sub)
    : ((rawSub ? SUB_ALIASES[rawSub] : undefined) ?? 'properties');
  const view = params.get('view') ?? undefined;
  const [q, setQ] = useState('');

  const exportProps = () => {
    const out: Array<Array<string>> = [
      ['Property label', 'Internal name', 'Field type', 'Group', 'Required', 'Description'],
    ];
    for (const p of liveProperties(model, o.key)) {
      out.push([
        p.label,
        p.name,
        fieldTypeLabel(p),
        groupLabel(model, o.key, p.groupName),
        p.required ? 'Yes' : 'No',
        p.description ?? '',
      ]);
    }
    downloadFile(`${o.name.toLowerCase().replace(/\s+/g, '-')}-properties.csv`, toCsv(out));
    toast('Properties exported', 'success');
  };

  // "Manage object" (HUB-604), in the design's order. Only custom objects can be renamed or
  // switched off for now; the built-in names aren't stored per business yet.
  const deactivatable = Boolean(o.definition) || Boolean(o.deactivatable);
  const settingsKey = o.activity ? 'activities' : o.key;
  const manageItems: MenuItem[] = [
    o.catalog
      ? {
          label: 'Create property',
          icon: 'plus',
          disabled: true,
          title: `${o.name} has no properties in this CRM yet`,
        }
      : lock({
          label: 'Create property',
          icon: 'plus',
          onClick: () => openProperty(o.key, null, 'create'),
        }),
    { label: 'Export properties', icon: 'cloud', onClick: exportProps },
    canRename(o)
      ? lock({ label: 'Edit object name', icon: 'pencil', onClick: () => renameObject(o.key) })
      : { label: 'Edit object name', icon: 'pencil', disabled: true, title: FIXED_NAME_HINT },
    { label: 'View object usage', icon: 'usage', onClick: () => openUsage(o.key) },
    { divider: true },
    deactivatable
      ? lock({
          label: 'Deactivate object',
          icon: 'circle',
          onClick: () => setArchived(o.key, true),
        })
      : {
          label: 'Deactivate object',
          icon: 'circle',
          disabled: true,
          title: `${o.name} can't be deactivated`,
        },
    { divider: true },
    lock({
      label: `Customize the 'create ${nameInText(o.singular)}' form`,
      icon: 'external',
      href: `/settings/objects?object=${encodeURIComponent(o.key)}&tab=setup#create-form`,
      disabled: o.catalog,
    }),
    lock({
      label: 'Customize the record view',
      icon: 'external',
      href: `/settings/objects?object=${encodeURIComponent(settingsKey)}&tab=record`,
      disabled: o.catalog || o.activity,
    }),
  ];

  // The design's switcher lists these objects, in this order (the ones this business has).
  const switchable = SWITCHER_OBJECTS.map((k) => model.objects.find((x) => x.key === k)).filter(
    (x): x is DmObject => Boolean(x?.active),
  );
  const shownSwitch = q
    ? switchable.filter((x) => x.name.toLowerCase().includes(q.toLowerCase()))
    : switchable;

  return (
    <>
      <div className="dm-objhead">
        <div>
          <div className="dm-crumb">
            <Link href={href({ tab: 'manage', view })}>All objects</Link>
            <span aria-hidden>/</span>
            <Dropdown
              btnClass="dm-crumb__switch"
              menuClass="dm-menu dm-menu--switch"
              role="listbox"
              label={
                <>
                  <DmIcon name={o.icon} />
                  {o.name}
                  <DmIcon name="caret" />
                </>
              }
            >
              {(close) => (
                <>
                  <label className="dm-pop__search">
                    <input
                      type="search"
                      placeholder="Search"
                      aria-label="Search objects"
                      value={q}
                      onChange={(e) => setQ(e.target.value)}
                    />
                    <DmIcon name="search" />
                  </label>
                  {shownSwitch.map((x) => (
                    <Link
                      key={x.key}
                      className={cn('dm-menu__item', x.key === o.key && 'is-selected')}
                      href={href({ tab: 'manage', object: x.key, sub, view })}
                      onClick={close}
                    >
                      <DmIcon name={x.icon} size={15} />
                      <span>{x.name}</span>
                    </Link>
                  ))}
                  {!shownSwitch.length && <p className="dm-pop__empty">No results</p>}
                </>
              )}
            </Dropdown>
          </div>
          {o.desc && <p className="dm-objhead__desc">{o.desc}</p>}
        </div>
        <ActionMenu
          label={
            <>
              Manage object
              <DmIcon name="chevron-down" size={14} />
            </>
          }
          btnClass="dm-btn dm-btn--outline dm-btn--sm"
          right
          items={manageItems}
        />
      </div>
      <div className="dm-objlayout">
        <ObjectNav object={o} sub={sub} view={view} />
        <div className="dm-lmain dm-subcontent">
          {sub === 'properties' ? (
            <PropertiesSection
              key={o.key}
              object={o}
              onCreate={() => openProperty(o.key, null, 'create')}
            />
          ) : sub === 'groups' ? (
            <GroupsSection key={o.key} object={o} />
          ) : sub === 'logic' ? (
            <LogicSection key={o.key} object={o} model={model} canEdit={canEdit} />
          ) : sub === 'archived' ? (
            <ArchivedSection key={o.key} object={o} />
          ) : sub === 'association-labels' ? (
            <AssociationLabelsSection key={o.key} object={o} />
          ) : (
            <AssociationsSection key={o.key} object={o} />
          )}
        </div>
      </div>
    </>
  );
}

/**
 * The design's left nav (data-model.js:2973-3060): "Properties" and "Associations" fold open
 * (the current one's group always open), then Conditional logic. Narrow screens get the
 * "Section: X" toggle.
 */
function ObjectNav({ object: o, sub, view }: { object: DmObject; sub: Sub; view?: string }) {
  const { href } = useDm();
  const [open, setOpen] = useState<Record<string, boolean>>({ props: true, assoc: true });
  const [mobileOpen, setMobileOpen] = useState(false);
  // The current section's group opens when the section changes; it can be folded after.
  useEffect(() => {
    const g = NAV_GROUPS.find((x) => (x.subs as readonly Sub[]).includes(sub));
    if (g) setOpen((cur) => (cur[g.id] ? cur : { ...cur, [g.id]: true }));
  }, [sub]);
  const label = (k: Sub) => SUBS.find(([x]) => x === k)![1];
  const link = (k: Sub, child: boolean) => (
    <Link
      key={k}
      className={cn('dm-lnav__link', child && 'dm-lnav__link--child', k === sub && 'is-active')}
      href={href({ tab: 'manage', object: o.key, sub: k, view })}
      aria-current={k === sub ? 'page' : undefined}
      onClick={() => setMobileOpen(false)}
    >
      <span className="dm-lnav__title">
        <span className="dm-lnav__icon">
          <DmIcon name={SUB_ICON[k]} size={15} />
        </span>
        <span>{label(k)}</span>
      </span>
    </Link>
  );
  return (
    <aside
      className={cn('dm-lnav dm-subtabs-lnav', mobileOpen && 'is-mobile-open')}
      aria-label={`${o.name} sections`}
    >
      <button
        type="button"
        className="dm-subtabs-mobile-toggle"
        aria-expanded={mobileOpen}
        onClick={() => setMobileOpen((v) => !v)}
      >
        <span className="dm-subtabs-mobile-toggle__left">
          <span className="dm-subtabs-mobile-toggle__icon">
            <DmIcon name="menu" size={16} />
          </span>
          <span>
            Section: <strong>{label(sub)}</strong>
          </span>
        </span>
        <span className="dm-subtabs-mobile-toggle__chevron">
          <DmIcon name="chevron-down" size={16} />
        </span>
      </button>
      <div className="dm-subtabs-lnav__body">
        {NAV_GROUPS.map((g) => {
          const isOpen = Boolean(open[g.id]);
          // A Fragment: the toggles stay siblings, so the design's `:first-child` margin rule
          // only touches the first one.
          return (
            <Fragment key={g.id}>
              <button
                type="button"
                className={cn('dm-lnav__link dm-lnav__toggle', isOpen && 'is-open')}
                aria-expanded={isOpen}
                onClick={() => setOpen((cur) => ({ ...cur, [g.id]: !isOpen }))}
              >
                <span className="dm-lnav__title">
                  <span className="dm-lnav__icon">
                    <DmIcon name={g.icon} size={16} />
                  </span>
                  <span>{g.label}</span>
                </span>
                <span className="dm-lnav__chevron">
                  <DmIcon name="chevron-down" size={16} />
                </span>
              </button>
              <div className="dm-lnav__children" hidden={!isOpen}>
                {g.subs.map((k) => link(k, true))}
              </div>
            </Fragment>
          );
        })}
        {link('logic', false)}
      </div>
    </aside>
  );
}

/* ================================================================== archived */

/**
 * DMG5 (C13-C15): the design's Archived properties tab (data-model.js:3628-3857). Search (also by
 * field type), Field type and Created by filters, Edit columns, Restore and Delete beside the name,
 * the internal name with Copy, and the time archived in the user's zone (#551). Delete uses the
 * API's `DELETE /custom-properties/:id`, as Settings › Properties does; the API refuses a CRM field
 * or one something still reads, and the reason shows in a toast.
 */
function ArchivedSection({ object: o }: { object: DmObject }) {
  const { model, reload, canEdit } = useDm();
  const toast = useToast();
  const { timeZone } = useUserPrefs();
  const [search, setSearch] = useState('');
  const [types, setTypes] = useState<string[]>([]);
  const [createdBy, setCreatedBy] = useState<string[]>([]);
  const [columns, setColumns] = useState<ColumnPrefs>({ ids: ARCHIVED_SET.defaults, frozen: 0 });
  const [editingColumns, setEditingColumns] = useState(false);
  useEffect(() => setColumns(readColumnPrefs(ARCHIVED_SET)), []);
  const [busy, setBusy] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<CustomPropertyDefinition | null>(null);
  const [copied, setCopied] = useState<string | null>(null);
  /** Fields just restored or deleted: hidden at once, before the model reloads. */
  const [gone, setGone] = useState<Set<string>>(new Set());
  // Created by names, as the Properties tab (#725).
  const [members, setMembers] = useState<Map<string, MemberName>>(new Map());
  const [membersComplete, setMembersComplete] = useState(false);
  useEffect(() => {
    let alive = true;
    void loadMemberNames(
      (cursor) => listOwners({ limit: 200, cursor, includeDeactivated: true }),
      (names) => alive && setMembers(names),
    ).then(({ complete }) => alive && setMembersComplete(complete));
    return () => {
      alive = false;
    };
  }, []);
  const creator = (p: CustomPropertyDefinition) =>
    creatorOf(p, members, { crmProvided: isCrmProvided(p), membersComplete }).label;
  /** Archived before archivedAt was kept: the last change stands in for it. */
  const archivedOn = (p: CustomPropertyDefinition) => p.archivedAt ?? p.updatedAt;
  const all = (model.properties[o.key] ?? []).filter((p) => p.archived && !gone.has(p.id));
  const q = search.trim().toLowerCase();
  const rows = all.filter(
    (p) =>
      (!q ||
        p.label.toLowerCase().includes(q) ||
        p.name.toLowerCase().includes(q) ||
        fieldTypeLabel(p).toLowerCase().includes(q)) &&
      (!types.length || types.includes(fieldTypeLabel(p))) &&
      (!createdBy.length || createdBy.includes(creator(p))),
  );
  const optionsOf = (values: string[]) =>
    [...new Set(values)].sort(byText).map((v) => ({ value: v, label: v }));

  const restore = async (p: CustomPropertyDefinition) => {
    setBusy(p.id);
    try {
      await restoreCustomProperty(p.id);
      toast(`"${p.label}" restored`, 'success');
      setGone((cur) => new Set(cur).add(p.id));
      void reload();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(null);
    }
  };
  const copy = (name: string) => {
    void navigator.clipboard?.writeText(name);
    setCopied(name);
    setTimeout(() => setCopied((c) => (c === name ? null : c)), 1800);
  };

  return (
    <>
      <div className="dm-toolbar dm-toolbar--rows">
        <div className="dm-toolbar__top">
          <SearchBox
            value={search}
            onChange={setSearch}
            placeholder="Search archived properties"
            wide
          />
          <span className="dm-grow" />
          <button
            type="button"
            className="dm-btn dm-btn--outline dm-btn--sm"
            onClick={() => setEditingColumns(true)}
          >
            <DmIcon name="columns" size={14} />
            Edit columns
          </button>
        </div>
        <div className="dm-toolbar__filters">
          <CheckFilter
            label={countLabel('Field type', types)}
            options={optionsOf(fieldTypeFilterLabels(all))}
            selected={types}
            onChange={setTypes}
            search
          />
          <CheckFilter
            label={countLabel('Created by', createdBy)}
            options={optionsOf(all.map(creator))}
            selected={createdBy}
            onChange={setCreatedBy}
            search
          />
        </div>
      </div>
      <DataTable
        rows={rows}
        rowKey={(p) => p.id}
        sortKey="archivedAt"
        sortDir={-1}
        frozen={columns.frozen}
        empty={
          all.length
            ? 'No archived properties match your filters.'
            : `${o.name} has no archived properties.`
        }
        cols={orderColumns<Column<CustomPropertyDefinition>>(
          [
            {
              key: 'label',
              label: 'Name',
              sort: true,
              // #73: by the name after a leading emoji or mark, as Settings › Properties.
              val: (p) => sortKey(p.label),
              width: '38%',
              render: (p) => (
                <div className="dm-arch-name-cell">
                  <div className="dm-arch-name-main">
                    <span className="dm-arch-name-title">{p.label}</span>
                    <div className="dm-arch-name-type">{fieldTypeLabel(p)}</div>
                  </div>
                  <div className="dm-arch-actions">
                    <button
                      type="button"
                      className="dm-arch-pill-btn dm-arch-pill-btn--restore"
                      onClick={() => void restore(p)}
                      disabled={busy !== null}
                      aria-label={`Restore ${p.label}`}
                      {...lockProps(canEdit)}
                    >
                      Restore
                    </button>
                    <button
                      type="button"
                      className="dm-arch-pill-btn dm-arch-pill-btn--delete"
                      onClick={() => setDeleting(p)}
                      disabled={busy !== null || isCrmProvided(p)}
                      title={
                        isCrmProvided(p)
                          ? "A field provided by the CRM can't be deleted"
                          : undefined
                      }
                      aria-label={`Delete ${p.label}`}
                      {...lockProps(canEdit)}
                    >
                      Delete
                    </button>
                  </div>
                </div>
              ),
            },
            {
              key: 'name',
              label: 'Internal Name',
              sort: true,
              val: (p) => p.name,
              cls: 'dm-td--internal',
              render: (p) => (
                <div className="dm-arch-internal-cell">
                  <span className="dm-arch-internal-text">{p.name}</span>
                  <div className="dm-arch-copy-wrap">
                    <button
                      type="button"
                      className={cn(
                        'dm-arch-pill-btn dm-arch-copy-btn',
                        copied === p.name && 'is-copied',
                      )}
                      aria-label="Copy internal name"
                      onClick={() => copy(p.name)}
                    >
                      Copy
                      <span className="dm-arch-tooltip" role="tooltip">
                        {copied === p.name ? 'Copied!' : 'Copy internal name'}
                      </span>
                    </button>
                  </div>
                </div>
              ),
            },
            {
              key: 'archivedAt',
              label: 'Time Archived',
              sort: true,
              val: archivedOn,
              render: (p) => (
                <span className="dm-arch-time">
                  {lastRunText(new Date(archivedOn(p)), timeZone)}
                </span>
              ),
            },
            {
              key: 'group',
              label: 'Group',
              sort: true,
              val: (p) => groupLabel(model, o.key, p.groupName),
              render: (p) => groupLabel(model, o.key, p.groupName),
            },
            { key: 'createdBy', label: 'Created by', sort: true, val: creator, render: creator },
            {
              key: 'desc',
              label: 'Description',
              sort: true,
              val: (p) => p.description ?? '',
              render: (p) => p.description || '—',
            },
          ],
          columns.ids,
        )}
      />
      <ColumnChooser
        open={editingColumns}
        columns={ARCHIVED_SET.columns}
        selected={columns.ids}
        lockedId={ARCHIVED_SET.locked}
        frozen={columns.frozen}
        maxFrozen={MAX_FROZEN}
        createHref={null}
        okLabel="Save"
        onClose={() => setEditingColumns(false)}
        onApply={(ids, frozen) => {
          const next = { ids, frozen };
          setColumns(next);
          saveColumnPrefs(ARCHIVED_SET, next);
          toast('Columns updated', 'success');
        }}
      />
      {deleting && (
        <Modal
          title="Delete property permanently?"
          okLabel="Delete permanently"
          danger
          onClose={() => setDeleting(null)}
          onOk={async () => {
            try {
              await deleteCustomProperty(deleting.id);
              toast(`"${deleting.label}" was permanently deleted.`, 'success');
              setGone((cur) => new Set(cur).add(deleting.id));
              void reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="dm-muted">
            Are you sure you want to permanently delete <b>{deleting.label}</b>? All historical data
            for this property will be permanently removed. This action cannot be undone.
          </p>
        </Modal>
      )}
    </>
  );
}

/* ================================================================ properties */

function PropertiesSection({ object: o, onCreate }: { object: DmObject; onCreate: () => void }) {
  const { model, openProperty, reload, canEdit } = useDm();
  const lock = (item: MenuItem) => lockItem(item, canEdit);
  const toast = useToast();
  const [search, setSearch] = useState('');
  const [types, setTypes] = useState<string[]>([]);
  const [groups, setGroups] = useState<string[]>([]);
  const [access, setAccess] = useState<string[]>([]);
  /** B7: the design's Created by filter (data-model.js:3317-3325). */
  const [createdBy, setCreatedBy] = useState<string[]>([]);
  // B6 (DMG4): the columns this viewer chose, in order; read after mount (none on the server).
  const [columns, setColumns] = useState<ColumnPrefs>({ ids: PROPERTY_SET.defaults, frozen: 0 });
  const [editingColumns, setEditingColumns] = useState(false);
  useEffect(() => setColumns(readColumnPrefs(PROPERTY_SET)), []);
  /** B9: the ids on the page shown, which the header checkbox ticks (data-model.js:3428-3444). */
  const [pageIds, setPageIds] = useState<string[]>([]);
  /** B9: "Select all N properties" was clicked; cleared by any change to the selection. */
  const [allChosen, setAllChosen] = useState(false);
  /** B10: the fields whose definition the export dialog is for. */
  // `bulk`: opened from the bulk bar, so the selection clears after (data-model.js:3510-3512).
  const [exporting, setExporting] = useState<{
    list: CustomPropertyDefinition[];
    bulk: boolean;
  } | null>(null);
  /** B12: the field whose API details or history are open. */
  const [apiOf, setApiOf] = useState<CustomPropertyDefinition | null>(null);
  const [historyFor, setHistoryFor] = useState<CustomPropertyDefinition | null>(null);
  const [moving, setMoving] = useState<CustomPropertyDefinition[] | null>(null);
  const [archiving, setArchiving] = useState<CustomPropertyDefinition[] | null>(null);
  /** #453: the fields ticked for a bulk action, by id. */
  const [picked, setPicked] = useState<Set<string>>(new Set());
  /** #736: the field whose history the export dialog is for. */
  const [historyOf, setHistoryOf] = useState<CustomPropertyDefinition | null>(null);
  /** A CRM-provided field whose Archive was clicked: it can't be archived. */
  const [locked, setLocked] = useState<CustomPropertyDefinition | null>(null);
  /** Fields just archived: hidden at once, before the model reloads (about 5 s). */
  const [gone, setGone] = useState<Set<string>>(new Set());
  // Where each field is used (Used In); null while loading or when it failed.
  const [usage, setUsage] = useState<Map<string, PropertyUsage> | null>(null);
  // #725: Created by names (every member may read the owners list) and Fill Rate per field id.
  const [members, setMembers] = useState<Map<string, MemberName>>(new Map());
  const [membersComplete, setMembersComplete] = useState(false);
  const [fills, setFills] = useState<Map<string, number> | null>(null);

  useEffect(() => {
    let alive = true;
    void loadMemberNames(
      (cursor) => listOwners({ limit: 200, cursor, includeDeactivated: true }),
      (names) => alive && setMembers(names),
    ).then(({ complete }) => alive && setMembersComplete(complete));
    return () => {
      alive = false;
    };
  }, []);

  useEffect(() => {
    // No records to count: activities and the standard objects (as Settings › Properties).
    if (!o.active || o.catalog || o.activity) return;
    let alive = true;
    listPropertyFillRates(o.key).then(
      (rows) =>
        alive &&
        setFills(new Map(rows.map((r) => [r.id, r.total ? (r.filled / r.total) * 100 : 0]))),
      () => alive && setFills(null),
    );
    return () => {
      alive = false;
    };
  }, [o.active, o.catalog, o.activity, o.key, model]);
  const creator = (p: CustomPropertyDefinition) =>
    creatorOf(p, members, { crmProvided: isCrmProvided(p), membersComplete }).label;
  const fillOf = (p: CustomPropertyDefinition) => fills?.get(p.id) ?? null;

  useEffect(() => {
    if (!o.active || o.catalog) return;
    let alive = true;
    listPropertyUsage(o.key).then(
      (rows) => alive && setUsage(new Map(rows.map((r) => [r.name, r]))),
      () => alive && setUsage(null),
    );
    return () => {
      alive = false;
    };
  }, [o.active, o.catalog, o.key, model]);
  const assetCount = (p: CustomPropertyDefinition) => propertyAssetCount(usage?.get(p.name));

  const props = liveProperties(model, o.key).filter((p) => !gone.has(p.id));
  // Every access level, used or not, so "Limited to super admins" can be looked for. "Assigned"
  // shows once it can be chosen, or while a field has it.
  const accessOptions = accessChoices(
    publicEnv().NEXT_PUBLIC_ASSIGNED_ACCESS,
    props.some((p) => p.access === 'assigned') ? 'assigned' : null,
  ).map((c) => ({ value: c.short, label: c.short }));
  // CQS2: the design's field types, not only the ones in use (data-model.js:3343).
  const typeOptions = fieldTypeFilterLabels(props).map((t) => ({ value: t, label: t }));
  const groupNames = [...new Set(props.map((p) => p.groupName ?? ''))];
  const groupOptions = groupNames
    .map((g) => ({ value: g, label: groupLabel(model, o.key, g || null) }))
    .sort((a, b) => byText(a.label, b.label));

  const rows = props.filter((p) => {
    const q = search.trim().toLowerCase();
    return (
      (!q || p.label.toLowerCase().includes(q) || p.name.includes(q)) &&
      (!types.length || types.includes(fieldTypeLabel(p))) &&
      (!groups.length || groups.includes(p.groupName ?? '')) &&
      (!access.length || access.includes(propertyAccess(p))) &&
      (!createdBy.length || createdBy.includes(creator(p)))
    );
  });
  const creatorOptions = [...new Set(props.map(creator))]
    .sort(byText)
    .map((c) => ({ value: c, label: c }));

  /** B10: one field as the export lists it (data-model.js:1879-1882). */
  const definitionRow = (p: CustomPropertyDefinition) => ({
    name: p.name,
    label: p.label,
    type: fieldTypeLabel(p),
    group: groupLabel(model, o.key, p.groupName),
    assets: usage ? assetCount(p) : ('' as const),
    access: propertyAccess(p),
  });

  // #453: the ticked fields still listed (filters and archiving can drop some).
  const pickedRows = rows.filter((p) => picked.has(p.id));
  const pick = (ids: string[], on: boolean) => {
    setAllChosen(false);
    setPicked((cur) => {
      const next = new Set(cur);
      ids.forEach((id) => (on ? next.add(id) : next.delete(id)));
      return next;
    });
  };
  const clearPicked = () => {
    setAllChosen(false);
    setPicked(new Set());
  };
  /** Built-in and CRM default fields can't be archived (the API refuses them too). */
  const archivable = (p: CustomPropertyDefinition) => !p.system && !p.standard;

  return (
    <>
      {/* DMG4 (B6, B7): the design's two rows (data-model.js:3334-3349). */}
      <div className="dm-toolbar dm-toolbar--rows">
        <div className="dm-toolbar__top">
          <SearchBox
            value={search}
            onChange={(v) => {
              setSearch(v);
              setAllChosen(false);
            }}
            placeholder="Search for a property"
            wide
          />
          <span className="dm-grow" />
          <button
            type="button"
            className="dm-btn dm-btn--primary dm-btn--sm"
            onClick={onCreate}
            disabled={o.catalog}
            {...lockProps(canEdit)}
          >
            <DmIcon name="plus" size={14} />
            Create property
          </button>
          <button
            type="button"
            className="dm-btn dm-btn--outline dm-btn--sm"
            onClick={() => setEditingColumns(true)}
          >
            <DmIcon name="columns" size={14} />
            Edit columns
          </button>
        </div>
        <div className="dm-toolbar__filters">
          <CheckFilter
            label={countLabel('Field type', types)}
            options={typeOptions}
            selected={types}
            onChange={(v) => {
              setTypes(v);
              setAllChosen(false);
            }}
            search
          />
          <CheckFilter
            label={countLabel('Group', groups)}
            options={groupOptions}
            selected={groups}
            onChange={(v) => {
              setGroups(v);
              setAllChosen(false);
            }}
            search
            wide
          />
          <CheckFilter
            label={countLabel('Created by', createdBy)}
            options={creatorOptions}
            selected={createdBy}
            onChange={(v) => {
              setCreatedBy(v);
              setAllChosen(false);
            }}
            search
          />
          <CheckFilter
            label={countLabel('Access level', access)}
            options={accessOptions}
            selected={access}
            onChange={(v) => {
              setAccess(v);
              setAllChosen(false);
            }}
          />
        </div>
      </div>
      {/* B9: the design's bulk bar and selection banner (data-model.js:3351-3369). */}
      {pickedRows.length > 0 && (
        <>
          <div className="dm-pbulk-bar" role="region" aria-label="Bulk actions">
            <label className="dm-pbulk-check" title="Toggle selection">
              <input
                type="checkbox"
                checked
                aria-label="Clear selection"
                onChange={(e) => !e.target.checked && clearPicked()}
              />
            </label>
            <span className="dm-pbulk-count">{pickedRows.length} selected</span>
            <button
              type="button"
              className="dm-pbulk-action"
              onClick={() => setMoving(pickedRows)}
              {...lockProps(canEdit)}
            >
              <DmIcon name="move" size={15} />
              Choose new property group
            </button>
            <button
              type="button"
              className="dm-pbulk-action"
              onClick={() => setArchiving(pickedRows.filter(archivable))}
              disabled={!pickedRows.some(archivable)}
              title={
                pickedRows.some(archivable)
                  ? undefined
                  : "Properties provided by CRM can't be archived"
              }
              {...lockProps(canEdit)}
            >
              <DmIcon name="archive" size={15} />
              Archive
            </button>
            <button
              type="button"
              className="dm-pbulk-action"
              onClick={() => setExporting({ list: pickedRows, bulk: true })}
            >
              <DmIcon name="cloud" size={15} />
              Export property definition
            </button>
          </div>
          <div className="dm-selection-banner">
            {allChosen && pickedRows.length === rows.length ? (
              <>
                <span>All {rows.length} properties are selected.</span>
                <button type="button" className="dm-selection-banner__link" onClick={clearPicked}>
                  Clear selection
                </button>
              </>
            ) : (
              <>
                <span>
                  {pickedRows.length} {pickedRows.length === 1 ? 'property' : 'properties'}{' '}
                  selected.
                </span>
                <button
                  type="button"
                  className="dm-selection-banner__link"
                  onClick={() => {
                    setPicked(new Set(rows.map((p) => p.id)));
                    setAllChosen(true);
                  }}
                >
                  Select all {rows.length} properties.
                </button>
              </>
            )}
          </div>
        </>
      )}
      <DataTable
        rows={rows}
        rowKey={(p) => p.id}
        sortKey="label"
        empty={
          props.length
            ? 'No properties match your filters.'
            : `${o.name} has no custom properties yet.`
        }
        // B9: the header box ticks the page shown; unticked, it clears (data-model.js:3428-3444).
        onPageKeys={setPageIds}
        // B6 / DMG3: the frozen count is of the chosen columns; the checkbox column comes first.
        frozen={columns.frozen ? columns.frozen + 1 : 0}
        rowCls={(p) => (picked.has(p.id) ? 'is-selected' : undefined)}
        cols={[
          {
            // #453: HubSpot's row checkboxes.
            key: 'pick',
            label: (
              <input
                type="checkbox"
                aria-label="Select this page's properties"
                checked={pickedRows.length > 0}
                onChange={(e) => (e.target.checked ? pick(pageIds, true) : clearPicked())}
              />
            ),
            width: '36px',
            render: (p) => (
              <input
                type="checkbox"
                aria-label={`Select ${p.label}`}
                checked={picked.has(p.id)}
                onChange={(e) => pick([p.id], e.target.checked)}
              />
            ),
          },
          ...orderColumns<Column<CustomPropertyDefinition>>(
            [
              {
                key: 'label',
                label: 'Property name',
                sort: true,
                // #73: by the name after a leading emoji or mark, as Settings › Properties.
                val: (p) => sortKey(p.label),
                width: '36%',
                render: (p) => (
                  <div className="dm-prop-cell">
                    <button
                      type="button"
                      className="dm-prop"
                      onClick={() => openProperty(o.key, p, 'edit')}
                    >
                      <span className="dm-prop__name">{p.label}</span>
                      <span className="dm-prop__type">{fieldTypeLabel(p)}</span>
                    </button>
                    <span className="dm-rowtools">
                      <button
                        type="button"
                        className="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
                        aria-label={`Edit ${p.label}`}
                        title="Edit"
                        onClick={() => openProperty(o.key, p, 'edit')}
                        {...lockProps(canEdit)}
                      >
                        <DmIcon name="pencil" size={13} />
                      </button>
                      <ActionMenu
                        label={
                          <>
                            <DmIcon name="more-h" size={14} />
                            <span className="crm-visually-hidden">Actions for {p.label}</span>
                          </>
                        }
                        btnClass="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
                        items={[
                          // The design's menu for every field, built-in ones too (HUB-226 D6).
                          lock({
                            label: 'Clone',
                            icon: 'copy',
                            onClick: () => openProperty(o.key, p, 'clone'),
                          }),
                          lock({
                            label: 'Choose new property group',
                            icon: 'move',
                            onClick: () => setMoving([p]),
                          }),
                          // B12: the design's View API details, View history and Assets
                          // (data-model.js:1755-1757). History reads the audit log (Super Admins);
                          // a built-in field has no definition row to look it up by.
                          {
                            label: 'View API details',
                            icon: 'info',
                            onClick: () => setApiOf(p),
                          },
                          p.standard
                            ? {
                                label: 'View history',
                                icon: 'clock',
                                disabled: true,
                                title: 'History is kept for custom properties',
                              }
                            : lock({
                                label: 'View history',
                                icon: 'clock',
                                onClick: () => setHistoryFor(p),
                              }),
                          {
                            label: 'Assets',
                            icon: 'usage',
                            onClick: () => openProperty(o.key, p, 'edit', 'usage'),
                          },
                          { divider: true },
                          // Every record's values, so the API keeps it for admins (custom-properties
                          // service `history`: manage settings).
                          lock({
                            label: 'Export property history',
                            icon: 'clock',
                            onClick: () => setHistoryOf(p),
                          }),
                          {
                            label: 'Export property definition',
                            icon: 'cloud',
                            onClick: () => setExporting({ list: [p], bulk: false }),
                          },
                          // HUB-226: who may see and change the values. CRM properties never change it.
                          isCrmOwned(p)
                            ? {
                                label: 'Manage access',
                                icon: 'lock',
                                disabled: true,
                                title: "CRM properties' access can't be changed",
                              }
                            : lock({
                                label: 'Manage access',
                                icon: 'lock',
                                onClick: () => openProperty(o.key, p, 'edit', 'access'),
                              }),
                          // Fields the CRM provides (built-in ones, an activity's defaults, HUB-609)
                          // can't be archived; as in the design, Archive says so.
                          lock({
                            label: 'Archive',
                            icon: 'archive',
                            onClick: () => (archivable(p) ? setArchiving([p]) : setLocked(p)),
                          }),
                        ]}
                      />
                    </span>
                  </div>
                ),
              },
              {
                key: 'group',
                label: 'Group',
                sort: true,
                val: (p) => groupLabel(model, o.key, p.groupName),
                render: (p) => groupLabel(model, o.key, p.groupName),
              },
              // #725: HubSpot's Created by.
              { key: 'by', label: 'Created by', sort: true, val: creator, render: creator },
              {
                // Workflows, lists and forms using the field. B8 (user's call): the design's name,
                // "Assets" (data-model.js:3296); B13: the count opens the editor's Usage (:3519).
                key: 'assets',
                label: 'Assets',
                sort: true,
                val: assetCount,
                render: (p) => {
                  if (!usage) return <span className="dm-muted">--</span>;
                  const n = assetCount(p);
                  return n ? (
                    <button
                      type="button"
                      className="dm-num-link"
                      onClick={() => openProperty(o.key, p, 'edit', 'usage')}
                    >
                      {n}
                      <DmIcon name="external" size={13} />
                    </button>
                  ) : (
                    '0'
                  );
                },
              },
              // B6: the design's other columns (data-model.js:3305-3315).
              {
                key: 'type',
                label: 'Field type',
                sort: true,
                val: fieldTypeLabel,
                render: fieldTypeLabel,
              },
              {
                key: 'desc',
                label: 'Description',
                render: (p) =>
                  p.description ? p.description : <span className="dm-muted">--</span>,
              },
              {
                key: 'name',
                label: 'Internal name',
                sort: true,
                val: (p) => p.name,
                render: (p) => <code className="dm-prop-subname">{p.name}</code>,
              },
              {
                // #725: HubSpot's Fill Rate, the share of live records holding a value.
                key: 'fill',
                label: 'Fill Rate',
                sort: true,
                val: (p) => fillOf(p) ?? -1,
                render: (p) => {
                  const n = fillOf(p);
                  return n === null ? (
                    <span className="dm-muted">--</span>
                  ) : (
                    `${Math.round(n * 100) / 100}%`
                  );
                },
              },
              {
                key: 'access',
                label: 'Property access',
                sort: true,
                val: propertyAccess,
                render: propertyAccess,
              },
            ],
            columns.ids,
          ),
        ]}
      />
      {/* B6: the design's Edit columns (data-model.js:3530-3537), as Manage's (DMG3). */}
      <ColumnChooser
        open={editingColumns}
        columns={PROPERTY_SET.columns}
        selected={columns.ids}
        lockedId={PROPERTY_SET.locked}
        frozen={columns.frozen}
        maxFrozen={MAX_FROZEN}
        createHref={null}
        okLabel="Save"
        onClose={() => setEditingColumns(false)}
        onApply={(ids, frozen) => {
          const next = { ids, frozen };
          setColumns(next);
          saveColumnPrefs(PROPERTY_SET, next);
          toast('Columns updated', 'success');
        }}
      />
      {exporting && exporting.list.length > 0 && (
        <ExportDefinitionModal
          objectKey={o.key}
          objectName={o.name}
          rows={exporting.list.map(definitionRow)}
          onClose={() => setExporting(null)}
          onDone={() => {
            if (exporting.bulk) clearPicked();
          }}
        />
      )}
      {apiOf && (
        <PropertyApiModal
          property={{
            id: apiOf.id,
            name: apiOf.name,
            type: fieldTypeLabel(apiOf),
            crmDefined: isCrmProvided(apiOf),
          }}
          onClose={() => setApiOf(null)}
        />
      )}
      <PropertyHistoryDrawer property={historyFor} onClose={() => setHistoryFor(null)} />

      {historyOf && (
        <ExportHistoryModal
          objectKey={o.key}
          property={historyOf}
          members={members}
          onClose={() => setHistoryOf(null)}
        />
      )}
      {moving && (
        <MoveGroupModal
          properties={moving}
          groups={liveGroups(model, o.key)}
          onClose={() => setMoving(null)}
          onSave={async (name, list) => {
            const failed: string[] = [];
            for (const m of list) {
              if (m.groupName === name) continue;
              try {
                if (m.standard) await setStandardPropertyGroup(o.key, m.name, name);
                else await updateCustomProperty(m.id, { groupName: name });
              } catch (err) {
                failed.push(`${m.label} (${errorText(err)})`);
              }
            }
            const to = groupLabel(model, o.key, name);
            if (failed.length) toast(`Not moved to ${to}: ${failed.join(', ')}`, 'danger');
            else {
              toast(
                list.length === 1
                  ? `"${list[0]!.label}" moved to ${to}`
                  : `${list.length} properties moved to ${to}`,
                'success',
              );
            }
            clearPicked();
            await reload();
            if (failed.length) return false;
          }}
        />
      )}
      {locked && <CantArchiveDrawer property={locked} onClose={() => setLocked(null)} />}
      {archiving && archiving.length > 0 && (
        <ArchivePropertyDrawer
          props={archiving}
          details={(p) => ({
            group: groupLabel(model, o.key, p.groupName),
            type: fieldTypeLabel(p),
          })}
          usage={usage}
          onClose={() => setArchiving(null)}
          onArchive={async () => {
            const done: string[] = [];
            const failed: string[] = [];
            for (const a of archiving) {
              try {
                await archiveCustomProperty(a.id);
                done.push(a.id);
              } catch (err) {
                failed.push(`${a.label} (${errorText(err)})`);
              }
            }
            setGone((cur) => new Set([...cur, ...done]));
            pick(done, false);
            void reload();
            if (failed.length) {
              toast(`Not archived: ${failed.join(', ')}`, 'danger');
              // The drawer stays open on the ones that failed.
              setArchiving(archiving.filter((a) => !done.includes(a.id)));
              return false;
            }
            toast(
              archiving.length === 1
                ? `"${archiving[0]!.label}" archived`
                : `${archiving.length} properties archived`,
              'success',
            );
          }}
        />
      )}
    </>
  );
}

/** Who may see and edit a field: CRM-calculated and import-only fields can't be edited. */
/** Its access (HUB-226), as the design words it; a field nobody edits by hand reads as view-only. */
function propertyAccess(p: CustomPropertyDefinition): string {
  const access = p.access === 'everyone_edit' && isLockedField(p) ? 'everyone_view' : p.access;
  return (
    PROPERTY_ACCESS_CHOICES.find((c) => c.value === access)?.short ??
    (isLockedField(p) ? 'Everyone can view' : 'Everyone can view and edit')
  );
}

function MoveGroupModal({
  properties,
  groups,
  onClose,
  onSave,
}: {
  /** #453: one field, or the ticked ones. */
  properties: CustomPropertyDefinition[];
  groups: PropertyGroup[];
  onClose: () => void;
  /** Saves the properties still listed (a chip's × drops one, B11). */
  onSave: (name: string, list: CustomPropertyDefinition[]) => Promise<boolean | void>;
}) {
  const [chosen, setChosen] = useState('');
  // B11: the design's chips with × and "No properties selected" (data-model.js:1770-1858).
  const [list, setList] = useState(properties);
  return (
    <Modal
      title="Choose new property group"
      okLabel="Save"
      okDisabled={!chosen || !list.length || list.every((p) => p.groupName === chosen)}
      onClose={onClose}
      onOk={() => onSave(chosen, list)}
    >
      <div className="dm-move-group-sec">
        <h4 className="dm-move-group-h">Properties</h4>
        <div className="dm-move-props-chips">
          {list.length ? (
            list.map((p) => (
              <span key={p.id} className="dm-move-prop-chip">
                <span className="dm-move-prop-chip__label">{p.label}</span>
                <button
                  type="button"
                  className="dm-move-prop-chip__rm"
                  aria-label={`Remove ${p.label}`}
                  onClick={() => setList((cur) => cur.filter((x) => x.id !== p.id))}
                >
                  &times;
                </button>
              </span>
            ))
          ) : (
            <span className="dm-muted">No properties selected</span>
          )}
        </div>
      </div>
      <div className="dm-field">
        <span className="dm-field__label">Groups</span>
        {groups.length ? (
          <SelectMenu
            value={chosen}
            options={[...groups]
              .sort((a, b) => byText(a.label, b.label))
              .map((g) => ({ value: g.name, label: g.label }))}
            onChange={setChosen}
            placeholder="Select a group"
            ariaLabel="Groups"
            search
          />
        ) : (
          <p className="dm-muted">
            This object has no property groups yet. Create one under Groups.
          </p>
        )}
      </div>
    </Modal>
  );
}

/* ================================================================ groups */

/**
 * Property groups: name (Edit on hover) and number of properties, as in the design. QA 18 Nov
 * (#738): HubSpot's Create group, Delete (an empty group; it is archived, as the API keeps
 * groups) and Reorder, which sets the order records and forms show the groups in.
 */
function GroupsSection({ object: o }: { object: DmObject }) {
  const { model, reload, canEdit } = useDm();
  const toast = useToast();
  const lock = (item: MenuItem) => lockItem(item, canEdit);
  const [search, setSearch] = useState('');
  const [editing, setEditing] = useState<PropertyGroup | null>(null);
  const [name, setName] = useState('');
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState('');
  const [deleting, setDeleting] = useState<PropertyGroup | null>(null);
  const [reordering, setReordering] = useState(false);
  const props = liveProperties(model, o.key);
  const live = [...liveGroups(model, o.key)].sort(
    (a, b) => a.displayOrder - b.displayOrder || byText(a.label, b.label),
  );
  const countOf = (g: PropertyGroup) => props.filter((p) => p.groupName === g.name).length;
  const rows = live
    .filter((g) => !search || g.label.toLowerCase().includes(search.toLowerCase()))
    .map((g, i) => ({ ...g, order: i + 1, count: countOf(g) }));
  const taken = (label: string) =>
    live.some((g) => g.label.trim().toLowerCase() === label.trim().toLowerCase());

  const open = (g: PropertyGroup) => {
    setEditing(g);
    setName(g.label);
  };

  return (
    <>
      <div className="dm-toolbar">
        <SearchBox value={search} onChange={setSearch} placeholder="Search for a group" wide />
        <span className="dm-grow" />
        <button
          type="button"
          className="dm-btn dm-btn--outline dm-btn--sm"
          onClick={() => setReordering(true)}
          disabled={live.length < 2}
          {...lockProps(canEdit)}
        >
          <DmIcon name="move" size={14} />
          Reorder groups
        </button>
        <button
          type="button"
          className="dm-btn dm-btn--primary dm-btn--sm"
          onClick={() => {
            setNewName('');
            setCreating(true);
          }}
          disabled={o.catalog && !o.fieldOnly}
          {...lockProps(canEdit)}
        >
          <DmIcon name="plus" size={14} />
          Create group
        </button>
      </div>
      <DataTable
        rows={rows}
        rowKey={(g) => g.id}
        sortKey="order"
        empty={
          live.length ? 'No groups match your search.' : `${o.name} has no property groups yet.`
        }
        cols={[
          { key: 'order', label: 'Order', sort: true, width: '90px' },
          {
            key: 'label',
            label: 'Group name',
            sort: true,
            width: '58%',
            render: (g) => (
              <span className="dm-row-hover">
                {g.label}
                <button
                  type="button"
                  className="dm-btn dm-btn--outline dm-btn--xxs dm-row-hover__btn"
                  onClick={() => open(g)}
                  {...lockProps(canEdit)}
                >
                  Edit
                </button>
                <ActionMenu
                  label={
                    <>
                      <DmIcon name="more-h" size={14} />
                      <span className="crm-visually-hidden">Actions for {g.label}</span>
                    </>
                  }
                  btnClass="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring dm-row-hover__btn"
                  items={[
                    g.count > 0
                      ? {
                          label: 'Delete',
                          icon: 'trash',
                          disabled: true,
                          title: 'Move its properties to another group first',
                        }
                      : lock({ label: 'Delete', icon: 'trash', onClick: () => setDeleting(g) }),
                  ]}
                />
              </span>
            ),
          },
          { key: 'count', label: 'Number of properties', sort: true },
        ]}
      />
      {creating && (
        <Modal
          title="Create property group"
          okLabel="Create"
          okDisabled={!newName.trim() || taken(newName)}
          onClose={() => setCreating(false)}
          onOk={async () => {
            try {
              await createPropertyGroup({
                objectType: o.key,
                label: newName.trim(),
                displayOrder: live.length ? Math.max(...live.map((g) => g.displayOrder)) + 1 : 0,
              });
              toast(`Group "${newName.trim()}" created`, 'success');
              await reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <label className="dm-field">
            <span className="dm-field__label">Group name</span>
            <input
              className={cn('dm-input', taken(newName) && 'is-invalid')}
              type="text"
              value={newName}
              maxLength={100}
              autoFocus
              onChange={(e) => setNewName(e.target.value)}
            />
            {taken(newName) && (
              <span className="dm-field__error">A group with this name already exists.</span>
            )}
          </label>
        </Modal>
      )}
      {deleting && (
        <Modal
          title="Delete property group?"
          okLabel="Delete"
          danger
          onClose={() => setDeleting(null)}
          onOk={async () => {
            try {
              await setPropertyGroupArchived(deleting.id, true);
              toast(`Group "${deleting.label}" deleted`, 'success');
              await reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="dm-muted">
            <b>{deleting.label}</b> has no properties. It will no longer be listed or offered for
            new properties.
          </p>
        </Modal>
      )}
      {reordering && (
        <ReorderGroupsModal
          groups={live}
          onClose={() => setReordering(false)}
          onSave={async (order) => {
            const failed: string[] = [];
            for (const [i, g] of order.entries()) {
              if (g.displayOrder === i) continue;
              try {
                await updatePropertyGroup(g.id, { displayOrder: i });
              } catch (err) {
                failed.push(`${g.label} (${errorText(err)})`);
              }
            }
            if (failed.length) toast(`Order not saved for: ${failed.join(', ')}`, 'danger');
            else toast('Group order saved', 'success');
            await reload();
            if (failed.length) return false;
          }}
        />
      )}
      {editing && (
        <Modal
          title="Edit property group"
          okLabel="Save"
          okDisabled={!name.trim()}
          onClose={() => setEditing(null)}
          onOk={async () => {
            try {
              await updatePropertyGroup(editing.id, { label: name.trim() });
              toast('Group renamed', 'success');
              await reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <label className="dm-field">
            <span className="dm-field__label">Group name</span>
            <input
              className="dm-input"
              type="text"
              value={name}
              maxLength={100}
              autoFocus
              onChange={(e) => setName(e.target.value)}
            />
            <span className="dm-field__hint">The internal name stays {editing.name}.</span>
          </label>
        </Modal>
      )}
    </>
  );
}

/** #738: drag a group (or use its arrows) to a new place; Save writes the new order. */
function ReorderGroupsModal({
  groups,
  onClose,
  onSave,
}: {
  groups: PropertyGroup[];
  onClose: () => void;
  onSave: (order: PropertyGroup[]) => Promise<boolean | void>;
}) {
  const [order, setOrder] = useState(groups);
  const [dragged, setDragged] = useState<number | null>(null);
  const move = (from: number, to: number) => {
    if (to < 0 || to >= order.length || from === to) return;
    setOrder((cur) => {
      const next = [...cur];
      const [g] = next.splice(from, 1);
      next.splice(to, 0, g!);
      return next;
    });
  };
  return (
    <Modal
      title="Reorder property groups"
      okLabel="Save"
      okDisabled={order.every((g, i) => g.id === groups[i]?.id)}
      onClose={onClose}
      onOk={() => onSave(order)}
    >
      <p className="dm-muted">Drag the groups into the order records and forms show them.</p>
      <ol className="dm-reorder">
        {order.map((g, i) => (
          <li
            key={g.id}
            className={cn('dm-reorder__item', dragged === i && 'is-dragging')}
            draggable
            onDragStart={() => setDragged(i)}
            onDragOver={(e) => {
              e.preventDefault();
              if (dragged !== null && dragged !== i) {
                move(dragged, i);
                setDragged(i);
              }
            }}
            onDragEnd={() => setDragged(null)}
          >
            <DmIcon name="move" size={14} />
            <span className="dm-reorder__label">{g.label}</span>
            <button
              type="button"
              className="dm-icon-btn dm-icon-btn--xs"
              aria-label={`Move ${g.label} up`}
              disabled={i === 0}
              onClick={() => move(i, i - 1)}
            >
              <DmIcon name="chevron-up" size={14} />
            </button>
            <button
              type="button"
              className="dm-icon-btn dm-icon-btn--xs"
              aria-label={`Move ${g.label} down`}
              disabled={i === order.length - 1}
              onClick={() => move(i, i + 1)}
            >
              <DmIcon name="chevron-down" size={14} />
            </button>
          </li>
        ))}
      </ol>
    </Modal>
  );
}

/* ================================================================ associations */

function AssociationsSection({ object: o }: { object: DmObject }) {
  const { model, params, href, reload, canEdit } = useDm();
  const lock = (item: MenuItem) => lockItem(item, canEdit);
  const router = useRouter();
  const pathname = usePathname();
  const toast = useToast();
  const [view, setView] = useState<'graph' | 'table'>(
    params.get('view') === 'graph' ? 'graph' : 'table',
  );
  const [search, setSearch] = useState('');
  const [limits, setLimits] = useState<string[]>([]);
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const [creating, setCreating] = useState<string | null>(null);
  // Row Actions on one pair (by the other object's key), as in HubSpot.
  const [pairAction, setPairAction] = useState<{
    kind: 'limit' | 'api';
    other: string;
  } | null>(null);
  const highlight = params.get('to');
  // DMG12 (D3): the design's pair view, open for ?to=<object> (data-model.js:5017 `pair: D.to`)
  // and from the chips, "+N more", "Labels: N" and the row menu; "All associations" goes back.
  const [pairView, setPairView] = useState<string | null>(highlight);
  useEffect(() => {
    if (highlight) setPairView(highlight);
  }, [highlight]);
  const openPair = (other: string) => {
    setPairView(other);
    const q = new URLSearchParams(params.toString());
    q.set('to', other);
    router.replace(`${pathname}?${q.toString()}`, { scroll: false });
  };
  const closePair = () => {
    setPairView(null);
    const q = new URLSearchParams(params.toString());
    q.delete('to');
    router.replace(`${pathname}?${q.toString()}`, { scroll: false });
  };

  const all = useMemo(() => associationsOf(model, o.key), [model, o.key]);
  // Links with an activity have no labels (HUB-609), as in HubSpot.
  const labelable = (other: string) =>
    !o.activity && !model.objects.find((x) => x.key === other)?.activity;
  // ?createLabel=1&to=<object> opens Create label for that pair once (data-model.php:122;
  // data-model.js:5195-5200). The param then goes, so coming back doesn't open it again.
  const askLabel = params.get('createLabel');
  // The page rewrites the design's other params first (normalizeDmUrl): wait, or its rewrite
  // would put ?createLabel back.
  const rewriting = ['create', 'fromObjectTypeId', 'toObjectTypeId'].some((k) => params.has(k));
  useEffect(() => {
    if (!askLabel || !highlight || rewriting) return;
    if (canEdit && all.some((a) => a.other === highlight) && labelable(highlight))
      setCreating(highlight);
    const q = new URLSearchParams(params.toString());
    q.delete('createLabel');
    router.replace(`${pathname}?${q.toString()}`, { scroll: false });
    // Once per link: the other values only decide whether it opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [askLabel, highlight, rewriting]);
  // Records link without a limit; a label can allow one link per record (1-to-1).
  const list = all
    .map((a) => ({
      ...a,
      name: model.objects.find((x) => x.key === a.other)!.name,
      card: '1-to-many' as Cardinality,
      seen: labelsSeenBy(a.labels, o.key),
    }))
    .filter((a) => {
      if (search && !a.name.toLowerCase().includes(search.toLowerCase())) return false;
      if (!limits.length) return true;
      return limits.some((c) =>
        c === 'Custom' ? a.labels.length > 0 : a.card === c || a.seen.some((l) => l.card === c),
      );
    });
  // Objects this one can't be linked to yet; a pair with a custom object can be added.
  const notYet = o.activity
    ? []
    : model.objects.filter(
        (x) =>
          x.active &&
          !x.activity &&
          !x.catalog &&
          !canLink(o, x) &&
          (Boolean(o.definition) || Boolean(x.definition)),
      );
  /**
   * QA 18 Nov (#758): as in HubSpot, Create association works on every object. An object already
   * linked gets a new association (a labelled one: the next step is Create association label);
   * links with an activity have no labels (HUB-609), and objects with no records here can't link.
   */
  const linkedAlready = model.objects.filter(
    (x) => x.active && !x.catalog && !notYet.includes(x) && canLink(o, x),
  );
  const noRecords = model.objects.filter((x) => x.active && x.catalog && !notYet.includes(x));
  const addOptions = [
    ...notYet.map((x) => ({ value: x.key, label: x.name })),
    ...linkedAlready.map((x) =>
      o.activity || x.activity
        ? {
            value: x.key,
            label: `${x.name} (already associated)`,
            disabled: true,
            title: 'Activities are already associated with this object and have no labels',
          }
        : { value: x.key, label: `${x.name} (add an association label)` },
    ),
    ...noRecords.map((x) => ({
      value: x.key,
      label: `${x.name} (no records in this CRM yet)`,
      disabled: true,
      title: "This CRM doesn't keep records of this object yet",
    })),
  ].sort((a, b) => byText(a.label, b.label));
  const [adding, setAdding] = useState(false);
  const [addTo, setAddTo] = useState('');
  // Activities' auto-association settings (HUB-226 D4), on this object or this activity type.
  const autoDefaults = o.activity
    ? `/settings/objects?object=activities&tab=associations&type=${encodeURIComponent(o.key)}`
    : `/settings/objects?object=activities&tab=associations&subject=${encodeURIComponent(o.key)}`;

  const initialPage = useMemo(() => {
    if (!highlight) return 1;
    const at = [...list]
      .sort((a, b) => byText(a.name, b.name))
      .findIndex((a) => a.other === highlight);
    return at > -1 ? Math.floor(at / 10) + 1 : 1;
    // only when the page opens with ?to=
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [highlight]);

  /** The Actions of one pair: labels, limits and ids, then the auto-association defaults. */
  const pairItems = (other: string): MenuItem[] => [
    ...(labelable(other)
      ? [
          lock({
            label: 'Create association label',
            icon: 'plus',
            onClick: () => setCreating(other),
          }),
          lock({
            label: 'Manage all association labels',
            icon: 'tag',
            onClick: () => openPair(other),
          }),
          lock({
            label: 'Edit association limit',
            icon: 'pencil',
            onClick: () => setPairAction({ kind: 'limit', other }),
          }),
        ]
      : []),
    {
      label: 'View API details',
      icon: 'info',
      onClick: () => setPairAction({ kind: 'api', other }),
    },
    lock({ label: 'Configure auto-association defaults', icon: 'external', href: autoDefaults }),
  ];

  const chips = (a: (typeof list)[number], max: number) => {
    if (!a.seen.length) return <span className="dm-muted">--</span>;
    const showAll = expanded.has(a.other);
    const shown = showAll ? a.seen : a.seen.slice(0, max);
    return (
      <span className="dm-chips">
        {shown.map((l) =>
          // The chip opens Manage labels, which writes: plain text for a view-only user.
          labelable(a.other) ? (
            <button
              key={l.key}
              type="button"
              className="dm-chip dm-chip--link"
              title="Manage association labels"
              onClick={() => openPair(a.other)}
            >
              {l.text} ({l.limit})
            </button>
          ) : (
            <span key={l.key} className="dm-chip">
              {l.text} ({l.limit})
            </span>
          ),
        )}
        {!showAll && a.seen.length > max && (
          <button
            type="button"
            className="dm-chips__more"
            onClick={() => setExpanded((cur) => new Set(cur).add(a.other))}
          >
            +{a.seen.length - max} more
          </button>
        )}
      </span>
    );
  };

  const switchView = (v: 'graph' | 'table') => {
    setView(v);
    router.replace(href({ tab: 'manage', object: o.key, sub: 'associations', view: v }));
  };

  const exportImage = async () => {
    try {
      const shown = list.map((a) => model.objects.find((x) => x.key === a.other)!);
      await exportDataModelImage(model, [o, ...shown]);
      toast('Data model image exported', 'success');
    } catch {
      toast("The image couldn't be created", 'danger');
    }
  };

  // DMG1's ?createLabel=1&to= opens this drawer; the pair view (?to=) shows it as well.
  const createDrawer = creating && (
    <CreateLabelDrawer
      from={o}
      to={model.objects.find((x) => x.key === creating)!}
      targets={[]}
      onClose={() => setCreating(null)}
      onCreate={async (body) => {
        try {
          await createAssociationLabel(body);
          toast(`Association label "${body.name}" created`, 'success');
          await reload();
        } catch (err) {
          toast(errorText(err), 'danger');
          return false;
        }
      }}
    />
  );
  const pairObject = pairView ? model.objects.find((x) => x.key === pairView) : undefined;
  if (pairView && pairObject && labelable(pairView)) {
    const pairLabels = all.find((a) => a.other === pairView)?.labels ?? [];
    return (
      <>
        {/* The design's breadcrumb (data-model.js:4830-4834). */}
        <div className="dm-assoc-breadcrumb">
          <button type="button" className="dm-link" onClick={closePair}>
            All associations
          </button>
          <span className="sep">&gt;</span>
          <span className="current">
            {o.name}-to-{pairObject.name}
          </span>
        </div>
        <LabelsPanel
          key={pairView}
          object={o}
          pair={{ other: pairView, object: pairObject, labels: pairLabels }}
        />
        {createDrawer}
      </>
    );
  }

  return (
    <>
      <div className="dm-toolbar">
        <ViewToggle view={view} onChange={switchView} />
        <SearchBox
          value={search}
          onChange={setSearch}
          placeholder="Search for an associated object"
          wide
        />
        <CheckFilter
          label={countLabel('Limits', limits)}
          options={[
            { value: '1-to-1', label: '1-to-1' },
            { value: '1-to-many', label: '1-to-many' },
            { value: 'Custom', label: 'Custom' },
          ]}
          selected={limits}
          onChange={setLimits}
        />
        <span className="dm-grow" />
        <span>
          <button
            type="button"
            className="dm-btn dm-btn--soft dm-btn--sm"
            onClick={() => {
              setAddTo('');
              setAdding(true);
            }}
            {...lockProps(canEdit)}
          >
            <DmIcon name="plus" size={14} />
            Create association
          </button>
        </span>
        {canEdit ? (
          <Link className="dm-btn dm-btn--outline dm-btn--sm" href={autoDefaults}>
            <DmIcon name="external" size={14} />
            Configure auto-association defaults
          </Link>
        ) : (
          // An admin-only Settings page.
          <button type="button" className="dm-btn dm-btn--outline dm-btn--sm" {...lockProps(false)}>
            <DmIcon name="external" size={14} />
            Configure auto-association defaults
          </button>
        )}
        <ActionMenu
          label={
            <>
              More
              <DmIcon name="chevron-down" size={14} />
            </>
          }
          btnClass="dm-btn dm-btn--outline dm-btn--sm"
          right
          items={[
            {
              label: 'Export data model as an image',
              icon: 'image',
              onClick: () => void exportImage(),
              disabled: view === 'table',
            },
          ]}
        />
      </div>
      {view === 'table' ? (
        <DataTable
          rows={list}
          rowKey={(a) => a.other}
          sortKey="name"
          initialPage={initialPage}
          rowCls={(a) => (a.other === highlight ? 'is-highlight' : undefined)}
          empty="No associated objects match your filters."
          cols={[
            {
              key: 'name',
              label: 'Associated object',
              sort: true,
              width: '26%',
              render: (a) => (
                <div className="dm-prop-cell">
                  <Link
                    className="dm-plain-link"
                    href={href({
                      tab: 'manage',
                      object: a.other,
                      sub: 'associations',
                      view: 'table',
                    })}
                  >
                    {a.name}
                  </Link>
                  <span className="dm-rowtools">
                    <ActionMenu
                      label={
                        <>
                          Actions
                          <DmIcon name="chevron-down" size={13} />
                        </>
                      }
                      btnClass="dm-btn dm-btn--outline dm-btn--xxs"
                      items={pairItems(a.other)}
                    />
                  </span>
                </div>
              ),
            },
            { key: 'card', label: 'Cardinality', sort: true, width: '18%' },
            { key: 'labels', label: 'Association labels', render: (a) => chips(a, 4) },
          ]}
        />
      ) : (
        <Canvas
          className="dm-canvas--assoc"
          legend="Lines join this object to every object its records can be associated with. Purple cards have association labels."
        >
          <div className="dm-agraph">
            <div className="dm-agraph__src">
              <article className="dm-acard dm-acard--src">
                <h4>
                  <DmIcon name={o.icon} size={14} />
                  {o.name}
                </h4>
                <p>{o.desc || `${list.length} associated objects`}</p>
              </article>
              <span className="dm-agraph__plus">
                <DmIcon name="plus" size={12} />
              </span>
            </div>
            <div className="dm-agraph__targets">
              {!list.length && (
                <p className="dm-muted dm-agraph__none">
                  No associated objects match your filters.
                </p>
              )}
              {[...list]
                .sort((a, b) => byText(a.name, b.name))
                .map((a) => {
                  const other = model.objects.find((x) => x.key === a.other)!;
                  return (
                    <div key={a.other} className="dm-agraph__row">
                      <span className="dm-agraph__pill">{a.card}</span>
                      <article className={cn('dm-acard', a.labels.length > 0 && 'has-labels')}>
                        <div className="dm-acard__head">
                          <h4>
                            <DmIcon name={other.icon} size={14} />
                            {other.name}
                          </h4>
                          <span className="dm-grow" />
                          {/* D16: the design's "View labels in table" (data-model.js:5104,
                              5138-5140): the table, searched for this object. */}
                          {a.labels.length > 0 && (
                            <button
                              type="button"
                              className="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
                              title="View in table"
                              aria-label="View labels in table"
                              onClick={() => {
                                setSearch(other.name);
                                switchView('table');
                              }}
                            >
                              <DmIcon name="assoc" size={12} />
                            </button>
                          )}
                          <ActionMenu
                            label={<DmIcon name="more-vertical" size={13} />}
                            ariaLabel={`Actions for ${other.name}`}
                            btnClass="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
                            right
                            items={[
                              {
                                label: 'View all properties',
                                icon: 'list',
                                href: href({ tab: 'manage', object: a.other, sub: 'properties' }),
                              },
                              {
                                label: 'View all associated objects',
                                icon: 'assoc',
                                href: href({
                                  tab: 'manage',
                                  object: a.other,
                                  sub: 'associations',
                                  view: 'graph',
                                }),
                              },
                              ...(labelable(a.other)
                                ? [
                                    lock({
                                      label: 'Create association label',
                                      icon: 'plus',
                                      onClick: () => setCreating(a.other),
                                    }),
                                    lock({
                                      label: 'Manage all association labels',
                                      icon: 'tag',
                                      onClick: () => openPair(a.other),
                                    }),
                                  ]
                                : []),
                            ]}
                          />
                        </div>
                        <p>{other.desc || other.name}</p>
                        {a.labels.length > 0 && (
                          <div className="dm-acard__labels">
                            <span className="dm-chip dm-chip--sm">{labelText(a.labels[0]!)}</span>
                            {a.labels[1] && (
                              <span className="dm-chip dm-chip--sm dm-chip--faint">
                                {labelText(a.labels[1])}
                              </span>
                            )}
                            <button
                              type="button"
                              className="dm-acard__count"
                              onClick={() => openPair(a.other)}
                            >
                              Labels: {a.labels.length}
                            </button>
                          </div>
                        )}
                      </article>
                    </div>
                  );
                })}
            </div>
          </div>
        </Canvas>
      )}
      {adding && (
        <Modal
          title={`Create new association to ${o.name}`}
          okLabel="Create"
          okDisabled={!addTo}
          onClose={() => setAdding(false)}
          onOk={async () => {
            // #758: an object already linked: the association to create is a labelled one.
            if (!notYet.some((x) => x.key === addTo)) {
              setCreating(addTo);
              return;
            }
            try {
              await allowObjectAssociation(o.key, addTo);
              toast('Association created', 'success');
              // Saved: the dialog closes now and the list refreshes when the model is in.
              void reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="dm-muted">
            Records of {o.name} and of the object you pick can then be linked. For an object already
            associated, you name the new association label next.
          </p>
          <div className="dm-field">
            <span className="dm-field__label">Object</span>
            <SelectMenu
              value={addTo}
              options={addOptions}
              onChange={setAddTo}
              placeholder="Choose an object"
              search={addOptions.length > 8}
              ariaLabel="Object to associate"
            />
          </div>
        </Modal>
      )}
      {pairAction?.kind === 'limit' && (
        <EditLimitsModal
          model={model}
          from={o}
          to={model.objects.find((x) => x.key === pairAction.other)!}
          onClose={() => setPairAction(null)}
          onChanged={reload}
        />
      )}
      {pairAction?.kind === 'api' && (
        <ApiDetailsModal
          model={model}
          from={o}
          to={model.objects.find((x) => x.key === pairAction.other)!}
          onClose={() => setPairAction(null)}
        />
      )}
      {createDrawer}
    </>
  );
}

/* ===================================================== association labels */

/**
 * DMG10 (D2): the design's Association labels section (data-model.js:5337-5811). Pick the other
 * object, then search, filter (Limits, Created by), choose columns, and act on each label.
 * Description, Used In, Internal name, Date created, history and the one-label limit drawer
 * need API data and come with DMG11; delete waits for the lead (D13), so labels archive as today.
 */
function AssociationLabelsSection({ object: o }: { object: DmObject }) {
  const { model, params } = useDm();
  // Links with an activity have no labels (HUB-609).
  const targets = associationsOf(model, o.key)
    .map((a) => ({ ...a, object: model.objects.find((x) => x.key === a.other)! }))
    .filter((a) => !o.activity && !a.object.activity)
    .sort((a, b) => byText(a.object.name, b.object.name));
  const asked = params.get('to');
  const [target, setTarget] = useState<string>(asked ?? '');
  // A `to` set after mount (the page turns ?toObjectTypeId into it) picks that object too.
  useEffect(() => {
    if (asked) setTarget(asked);
  }, [asked]);
  // The chosen object, else the first one (none chosen yet, or it went away on a reload).
  const pair = targets.find((t) => t.other === target) ?? targets[0];
  return (
    <>
      {/* The design's top card (data-model.js:5509-5537). */}
      <div className="dm-assoc-top-card">
        <div className="dm-assoc-selector">
          <span className="dm-assoc-selector__label">
            Select a {o.name} association: {o.name} to
          </span>
          {targets.length ? (
            <SelectMenu
              value={pair?.other ?? ''}
              options={targets.map((t) => ({ value: t.other, label: t.object.name }))}
              onChange={setTarget}
              ariaLabel={`Object associated with ${o.name}`}
              search
            />
          ) : (
            <span className="dm-muted">No objects can have labels with {o.name}.</span>
          )}
        </div>
      </div>
      <LabelsPanel key={pair?.other ?? ''} object={o} pair={pair} />
    </>
  );
}

/** One object pair's labels, as `labelRows` reads them (the other object, its labels). */
interface LabelPair {
  other: string;
  object: DmObject;
  labels: AssociationLabel[];
}

/**
 * DMG10 / DMG12: one pair's labels table: search, Limits and Created by filters, Edit columns,
 * create, and each label's pencil and menu. The Association labels section and the design's
 * "Manage all association labels" pair view (data-model.js:4722-4973) both show it.
 */
function LabelsPanel({ object: o, pair }: { object: DmObject; pair: LabelPair | undefined }) {
  const { reload, canEdit } = useDm();
  const toast = useToast();
  const { timeZone } = useUserPrefs();
  const lock = (item: MenuItem) => lockItem(item, canEdit);
  const [search, setSearch] = useState('');
  const [limits, setLimits] = useState<string[]>([]);
  const [createdBy, setCreatedBy] = useState<string[]>([]);
  const [columns, setColumns] = useState<ColumnPrefs>({ ids: LABEL_SET.defaults, frozen: 0 });
  const [editingColumns, setEditingColumns] = useState(false);
  useEffect(() => setColumns(readColumnPrefs(LABEL_SET)), []);
  const [creating, setCreating] = useState(false);
  // DMG11: the row's dialog (D9 limit, D10 API details, D11 history).
  const [dialog, setDialog] = useState<{
    kind: 'limits' | 'api' | 'history';
    row: LabelRow;
  } | null>(null);
  const [archiving, setArchiving] = useState<LabelRow | null>(null);

  const all = pair ? labelRows(pair.labels, o.key) : [];
  const rows = all.filter(
    (r) =>
      matchesLabel(r, search) &&
      (!limits.length || limits.includes(limitBucket(r.limit))) &&
      (!createdBy.length || createdBy.includes(r.crm ? 'CRM' : 'User')),
  );
  const create = (
    <button
      type="button"
      className="dm-btn dm-btn--primary dm-btn--sm"
      onClick={() => setCreating(true)}
      disabled={!pair}
      {...lockProps(canEdit)}
    >
      <DmIcon name="plus" size={14} />
      Create association label
    </button>
  );

  return (
    <>
      <div className="dm-toolbar dm-toolbar--rows dm-assoc-labels-toolbar">
        <div className="dm-toolbar__top">
          <SearchBox value={search} onChange={setSearch} placeholder="Search for a label" />
          <span className="dm-grow" />
          {create}
          <button
            type="button"
            className="dm-btn dm-btn--outline dm-btn--sm"
            onClick={() => setEditingColumns(true)}
          >
            <DmIcon name="columns" size={14} />
            Edit columns
          </button>
        </div>
        <div className="dm-toolbar__filters">
          <CheckFilter
            label={countLabel('Limits', limits)}
            options={['1-to-1', '1-to-many', 'Custom'].map((v) => ({ value: v, label: v }))}
            selected={limits}
            onChange={setLimits}
          />
          <CheckFilter
            label={countLabel('Created by', createdBy)}
            options={['CRM', 'User'].map((v) => ({ value: v, label: v }))}
            selected={createdBy}
            onChange={setCreatedBy}
          />
        </div>
      </div>
      {all.length === 0 ? (
        // The design's empty card (data-model.js:5555-5602). Its "Learn more" points at a
        // knowledge base this CRM doesn't have, so it is left out.
        <div className="dm-assoc-empty-card">
          <div className="dm-assoc-empty-card__content">
            <h3 className="dm-assoc-empty-card__title">You have no labels</h3>
            <p className="dm-assoc-empty-card__desc">
              Create association labels to add more meaning to your object and record relationships.
            </p>
            <div className="dm-assoc-empty-card__actions">{create}</div>
          </div>
        </div>
      ) : (
        <DataTable
          rows={rows}
          rowKey={(r) => r.id}
          sortKey="label"
          frozen={columns.frozen}
          empty="No association labels match your filters."
          cols={orderColumns<Column<LabelRow>>(
            [
              {
                key: 'label',
                label: 'Label',
                sort: true,
                val: (r) => r.label,
                width: '30%',
                render: (r) => (
                  <div className="dm-label-cell">
                    <div className="dm-label-cell__row">
                      <span className="dm-assoc-badge">{r.label}</span>
                      <span className="dm-rowtools">
                        <button
                          type="button"
                          className="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
                          aria-label={`Edit label limit of ${r.label}`}
                          title="Edit label limit"
                          onClick={() => setDialog({ kind: 'limits', row: r })}
                          {...lockProps(canEdit)}
                        >
                          <DmIcon name="pencil" size={12} />
                        </button>
                        <ActionMenu
                          label={
                            <>
                              <DmIcon name="more-vertical" size={14} />
                              <span className="crm-visually-hidden">Actions for {r.label}</span>
                            </>
                          }
                          btnClass="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
                          items={[
                            lock({
                              label: 'Edit label limit',
                              icon: 'pencil',
                              onClick: () => setDialog({ kind: 'limits', row: r }),
                            }),
                            {
                              label: 'View API details',
                              icon: 'info',
                              onClick: () => setDialog({ kind: 'api', row: r }),
                            },
                            {
                              label: 'View history',
                              icon: 'clock',
                              onClick: () => setDialog({ kind: 'history', row: r }),
                            },
                            { divider: true },
                            r.crm
                              ? {
                                  label: 'Archive label',
                                  icon: 'archive',
                                  disabled: true,
                                  title: "CRM labels can't be archived",
                                }
                              : lock({
                                  label: 'Archive label',
                                  icon: 'archive',
                                  onClick: () => setArchiving(r),
                                }),
                          ]}
                        />
                      </span>
                    </div>
                    {r.pairedWith && (
                      <span className="dm-label-cell__paired">
                        Paired with &quot;{r.pairedWith}&quot;
                      </span>
                    )}
                  </div>
                ),
              },
              {
                key: 'card',
                label: 'Limits',
                sort: true,
                val: (r) => r.limit,
                render: (r) => r.limit,
              },
              {
                key: 'desc',
                label: 'Description',
                sort: true,
                val: (r) => r.description ?? '',
                render: (r) => r.description || <span className="dm-muted">--</span>,
              },
              {
                key: 'created_by',
                label: 'Created By CRM',
                sort: true,
                val: (r) => (r.crm ? 'Yes' : 'No'),
                render: (r) => (r.crm ? 'Yes' : 'No'),
              },
              {
                key: 'internal',
                label: 'Internal name',
                sort: true,
                val: (r) => r.internalName,
                render: (r) => <code className="dm-prop-subname">{r.internalName}</code>,
              },
              {
                key: 'created_date',
                label: 'Date created',
                sort: true,
                val: (r) => r.createdAt ?? '',
                // The design's "Wednesday, November 18, 2026" (data-model.js:5449), in the user's zone.
                render: (r) => (r.createdAt ? createdDayText(r.createdAt, timeZone) : '—'),
              },
            ],
            columns.ids,
          )}
        />
      )}
      <ColumnChooser
        open={editingColumns}
        columns={LABEL_SET.columns}
        selected={columns.ids}
        lockedId={LABEL_SET.locked}
        frozen={columns.frozen}
        maxFrozen={MAX_FROZEN}
        createHref={null}
        okLabel="Save"
        onClose={() => setEditingColumns(false)}
        onApply={(ids, frozen) => {
          const next = { ids, frozen };
          setColumns(next);
          saveColumnPrefs(LABEL_SET, next);
          toast('Columns updated', 'success');
        }}
      />
      {creating && pair && (
        <CreateLabelDrawer
          from={o}
          to={pair.object}
          targets={[]}
          onClose={() => setCreating(false)}
          onCreate={async (body) => {
            try {
              await createAssociationLabel(body);
              toast(`Association label "${body.name}" created`, 'success');
              await reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        />
      )}
      {dialog?.kind === 'limits' && pair && (
        <LabelLimitDrawer
          from={o}
          to={pair.object}
          label={dialog.row.label}
          pairedWith={dialog.row.pairedWith}
          fromLimit={
            dialog.row.onA
              ? (dialog.row.source.maxPerRecord ?? null)
              : (dialog.row.source.inverseMaxPerRecord ?? null)
          }
          toLimit={
            dialog.row.onA
              ? (dialog.row.source.inverseMaxPerRecord ?? null)
              : (dialog.row.source.maxPerRecord ?? null)
          }
          onClose={() => setDialog(null)}
          onSave={async (fromLimit, toLimit) => {
            // Stored order: this side is the a-side, or the b-side.
            const onA = dialog.row.onA;
            try {
              await renameAssociationLabel(dialog.row.id, {
                maxPerRecord: onA ? fromLimit : toLimit,
                inverseMaxPerRecord: onA ? toLimit : fromLimit,
              });
              toast('Label limit saved', 'success');
              await reload();
              return null;
            } catch (err) {
              return errorText(err);
            }
          }}
        />
      )}
      {dialog?.kind === 'api' && pair && (
        <ApiRowsModal
          rows={[
            { label: 'CRM internal name', value: dialog.row.internalName },
            { label: 'Label limits', value: dialog.row.limit },
            {
              label: 'CRM / User defined',
              value: dialog.row.crm ? 'CRM_DEFINED' : 'USER_DEFINED',
            },
            {
              label: 'Association ID',
              value:
                (dialog.row.onA
                  ? dialog.row.source.hubspotTypeId
                  : dialog.row.source.hubspotInverseTypeId) ?? dialog.row.id,
            },
          ]}
          onClose={() => setDialog(null)}
        />
      )}
      {dialog?.kind === 'history' && pair && (
        <LabelHistoryModal
          label={dialog.row.source}
          shownName={dialog.row.label}
          from={o}
          to={pair.object}
          onClose={() => setDialog(null)}
        />
      )}
      {archiving && (
        <Modal
          title="Archive label?"
          okLabel="Archive"
          danger
          onClose={() => setArchiving(null)}
          onOk={async () => {
            try {
              await archiveAssociationLabel(archiving.id);
              toast(`Label "${archiving.label}" archived`, 'success');
              await reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="dm-muted">
            <b>{archiving.label}</b> can no longer be added to links. Links that have it keep it.
          </p>
        </Modal>
      )}
    </>
  );
}
