'use client';

import { MergeDesignDialog } from '@/features/duplicates/design/MergeDesignDialog';
import { MERGE_DENIED_TITLE, recordRights, scopeCovers } from '@/features/auth/record-access';
import {
  ADDITIONAL_LABEL,
  additionalText,
  keepMergedIds,
  MERGED_IDS_LABEL,
  mergedIdsText,
} from '@/features/duplicates/mergedIds';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Fragment, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Alert } from '@/components/crm/Alert';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { useToast } from '@/components/crm/ToastProvider';
import { useTimelineEditing } from '@/features/activities/ui/TimelineActivityEditing';
import { useOpenRecordAction } from '@/features/activities/ui/useOpenRecordAction';
import { usePanelParam } from '@/features/record-pages/usePanelParam';
import {
  ALL_TIMELINE_TYPES,
  timelineServerFilters,
  timelineTypesParam,
  type TimelineDateFilter,
} from '@/features/activities/timelineFilters';
import {
  TimelineEmpty,
  TimelineExpandMenu,
  TimelineFilterChips,
} from '@/features/activities/ui/TimelineFilterChips';
import { AssociatedPreview, type PreviewTarget } from '@/features/record-pages/AssociatedPreview';
import { RecordStickyHeader } from '@/features/record-pages/RecordStickyHeader';
import {
  ActivityTabAddButton,
  ActivityTypeIcon,
  activityTabAddAction,
  activityTabLogAction,
  activityTabSearchPlaceholder,
  TimelineLoadMore,
  TimelineTypeTabs,
} from '@/features/activities/ui/TimelineControls';
import type { CommunicationChannel } from '@/features/activities/api.client';
import { ActivitiesMoreMenu, type MoreMenuItem } from '@/features/record-pages/ActivitiesMoreMenu';
import {
  COMMERCE,
  COMMERCE_KINDS,
  CommerceCreateDialog,
  type CommerceKind,
} from '@/features/record-pages/CommerceCreateDialog';
import { MoreMenuIcon } from '@/features/record-pages/MoreMenuIcon';
import { CloneRecordDrawer } from '@/features/record-tools/ui/CloneRecordDrawer';
import { useRecordTimeline, type TimelineFetch } from '@/features/activities/ui/useRecordTimeline';
import { isPinnable, withoutPinned } from '@/features/activities/timelinePins';
import {
  PinnedBadge,
  PinsLoadError,
  TimelinePinToggle,
} from '@/features/activities/ui/TimelinePin';
import { useTimelinePins } from '@/features/activities/ui/useTimelinePins';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { canUsePlaybooks } from '@/features/playbooks/access';
import { useConfirm } from '@/components/crm/useConfirm';
import { ownerLabelFromCache } from '@/features/owners/labels';
import { useOwners } from '@/features/owners/useOwners';
import {
  getContact,
  getContactHistory,
  getContactTimeline,
  contactsWithEmail,
  createContact,
  restoreContact,
  updateContact,
} from '@/features/contacts/api.client';
import {
  formatUserDate,
  formatUserMonthYear,
  MEANINGFUL_FIELDS,
  readable,
  type ReadableContext,
} from '@/features/activities/readable';
import { AssociationHistoryDrawer, useRecordTools } from '@/features/record-tools/ui/RecordTools';
import { ownerLock } from '@/features/record-tools/recordAccessView';
import { completeTask } from '@/features/tasks/api.client';
import { listTeamOptions } from '@/features/members/api.client';
import type { RecordActionButton } from '@/features/settings/types';
import {
  ContactOverviewCard,
  OVERVIEW_CARDS,
  useContactOverviewData,
} from './record/ContactOverview';
import { isSection, sectionName, TabSection, tabGroups } from '@/features/record-layouts/tabItems';
import { condOk, recordTexts } from '@/features/record-layouts/cond';
import {
  companyNameEdit,
  contactCompanyText,
  createdText,
  headerSubtitle,
  RECORD_TEXT_MAX,
} from './record/aboutValues';
import { ContactNameHeading } from './record/ContactNameHeading';
import { RecordNamePopover, type NameField } from '@/features/record-pages/RecordNamePopover';
import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import {
  ComingSoonPanel,
  PlaybooksCard,
  RecordTabBar,
  type PlaybookRunContext,
} from '@/features/record-pages/RecordTabs';
import {
  ABOUT_FIELDS,
  CARD_CATALOG,
  defaultLayout,
  useMyRecordLayout,
} from '@/features/record-layouts/api.client';
import { companyRecord, dealRecord } from '@/features/record-layouts/assocRecords';
import { baseCardId, cardDef, listMode, presetProps } from '@/features/record-layouts/cardSettings';
import type { CardView } from '@/features/record-layouts/ui/AssocLines';
import { canEditCards, withCardGear } from '@/features/record-layouts/ui/CardGear';
import { recordEditorHref, editorViewParam } from '@/features/record-layouts/editorLinks';
import { OtherContactsCard, WebsiteActivityCard } from './record/ContactSidebarCards';
import {
  ActivityDisplayDialog,
  BUTTON_LABELS,
  BUTTON_TITLES,
  ButtonOrderDialog,
  fullOrder,
} from './record/RecordPrefsDialogs';
import type { Contact, TimelineItem, UpdateContactBody } from '@/features/contacts/types';
import { cloneContactBody } from '@/features/contacts/clone';
import { getMyMailbox } from '@/features/inbox/api.client';
import {
  controlSequenceEnrollment,
  listContactSequenceEnrollments,
  listSequences,
} from '@/features/sequences/api.client';
import type { Sequence, SequenceEnrollment } from '@/features/sequences/types';
import { EnrollPreviewDialog } from '@/features/sequences/ui/EnrollPreviewDialog';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { listPicklistOptions, type PicklistOption } from '@/features/picklists/api.client';
import { customHistoryField } from '@/features/property-history/describe';
import { PropertyHistoryButton } from '@/features/property-history/PropertyHistoryButton';
import { PropertyHistoryDrawer } from '@/features/property-history/PropertyHistoryDrawer';
import { contactHistoryDescriber } from '@/features/property-history/records';
import { useFieldAccess, VIEW_ONLY_TITLE } from '@/features/permission-sets/field-access';
import { canOpenPropertySettings } from '@/features/permission-sets/property-settings';
import { RecordTasksCard } from '@/features/tasks/ui/RecordTasksCard';
import { AttachmentsSidebarCard } from '@/features/files/ui/AttachmentsCard';
import { RecordQuotesCard } from '@/features/quotes/ui/RecordQuotesCard';
import { ContactLeadStageCard } from '@/features/objects/ui/lead/LeadStageTracker';
import { ContactSubscriptionsCard } from '@/features/subscriptions/ui/ContactSubscriptionsCard';
import { errorText, isApiError } from '@/lib/api/errors';
import { emailError, inlinePhoneValue } from '@/lib/validation/contact-company';
import { cn } from '@/lib/utils/cn';
import {
  formatPicklistLabel,
  timelineBody,
  timelineTitle,
} from '@/features/activities/timelineSearch';

// The search helper's test still imports it from here.
export { timelineBody };
import { ContactActionsMenu, type ContactAction } from './actions/ContactActionsMenu';
import { CreateTaskDrawer } from '@/features/tasks/ui/CreateTaskDrawer';
import { AdditionalOwnersEdit } from './actions/AdditionalOwners';
import { PropertyGroupCards } from './actions/PropertyGroupCards';
import { CustomFieldsList } from './actions/custom-fields';
import { usePickerGroups } from '@/features/list-page/propertyGroups';
import {
  canEditPropertySettings,
  propertySettingsHref,
} from '@/features/permission-sets/property-settings';
import {
  AllPropertiesDesignDrawer,
  DesignPropertyRow,
  useDesignPropertyRow,
  type PropertyRow,
} from '@/features/record-tools/ui/AllPropertiesDesign';
import type { CustomProperties } from '@/types/api';
import {
  InlineEdit,
  InlineSelectInput,
  InlineTextInput,
  ownerChoices,
  picklistChoices,
} from './actions/InlineEdit';
import { duplicateEmailText, duplicateWarningText, emailInUse } from './actions/editContactErrors';
import { DeleteContactDialog } from './actions/DeleteContactDialog';
import { EditContactDrawer } from './actions/EditContactDrawer';
import { LogCallDrawer } from './actions/LogCallDrawer';
import { LogCommunicationDrawer } from './actions/LogCommunicationDrawer';
import { LogPostalMailDrawer } from './actions/LogPostalMailDrawer';
import { LogEmailDrawer } from './actions/LogEmailDrawer';
import { asCompanyAssoc, asDealAssoc } from './actions/assocTypes';
import { LogNoteDrawer } from './actions/LogNoteDrawer';
import { ScheduleMeetingDrawer } from './actions/ScheduleMeetingDrawer';
import { SendEmailDrawer } from './actions/SendEmailDrawer';
import { contactErrorText, contactFieldLabel, hasFieldDetails } from './actions/fieldErrors';
import { useUserPrefs } from './actions/shared';
import { CardMemory, CollapsibleCard } from './CollapsibleCard';
import { keepSequencePick } from './sequencePick';
import { EnrollSequenceDialog } from './actions/EnrollSequenceDialog';
import { LinkedObjectCards } from '@/features/objects/ui/LinkedObjectCards';
import { RelatedRecordsCard } from '@/features/associations/ui/RelatedRecordsCard';
import { ContactAssociations } from './ContactAssociations';
import { useObjectNames } from '@/features/objects/useObjectNames';

type KnownTab = 'overview' | 'activity' | 'salesnav' | 'docusign';
/** R10b: a page tab: a known one, or `x:<layout id>` for a tab only the layout has. */
type CenterTab = KnownTab | `x:${string}`;
/** Record layout tab ids (HUB-380) and the page's tabs. */
const LAYOUT_TABS: Record<string, KnownTab> = {
  overview: 'overview',
  activities: 'activity',
  salesnav: 'salesnav',
  docusign: 'docusign',
};
/** A page tab's record layout id (LAYOUT_TABS the other way). */
const LAYOUT_TAB_ID: Record<KnownTab, string> = {
  overview: 'overview',
  activity: 'activities',
  salesnav: 'salesnav',
  docusign: 'docusign',
};
/**
 * The contact tabs: the 28 Oct design's (record-layout.js:113-117) without Intelligence. CQS2,
 * the user's call (23 Nov): only these four, all in the row (no More); Emails and History left.
 */
const BUILT_IN_TABS: Array<readonly [CenterTab, string]> = [
  ['activity', 'Activities'],
  ['salesnav', 'Sales Navigator'],
  ['overview', 'Overview'],
  ['docusign', 'DocuSign'],
];
/** R10b: a layout tab id as the page's tab key, and back. */
const tabKeyOf = (id: string): CenterTab => LAYOUT_TABS[id] ?? `x:${id}`;
const layoutIdOf = (tab: CenterTab): string =>
  tab.startsWith('x:') ? tab.slice(2) : LAYOUT_TAB_ID[tab as KnownTab];
/** R10b: the whole-tab cards a tab can hold (the timeline and the panels). */
const PLAIN_CARDS = new Set(['activities', 'salesnav', 'docusign']);
const BUILT_IN_CONTACT_LAYOUT = defaultLayout('contact');

type Drawer =
  | 'edit'
  | 'note'
  | 'call'
  | 'dial'
  | 'task'
  | 'meeting'
  | 'log-meeting'
  | 'email'
  | 'log-email'
  | 'communication'
  | 'postal-mail'
  | 'delete';
const EXTENSION_ACTIONS = ['email', 'note', 'call', 'task', 'meeting'] as const;

/** R4: card memory for the record page's sidebars (CollapsibleCard `CardMemory`). */
const LEFT_CARD_MEMORY = { storageKey: null, defaultCollapsed: [], phoneCollapsed: true };
const CONTACT_RIGHT_MEMORY = {
  storageKey: 'rt.collapsed.contacts',
  // The design's default-collapsed cards master has: Events and Quotes (record-tabs.js:263).
  defaultCollapsed: ['object-event', 'quotes'],
};

/** R3: the built-in fields' group in "View all properties", as the list pickers name it. */
const CONTACT_INFO = 'Contact information';
const CONTACT_GROUPS = [CONTACT_INFO] as const;
type ActivityType = 'all' | 'notes' | 'emails' | 'calls' | 'tasks' | 'meetings';

/**
 * The design's activity sub-tabs (record-ui.php:271-278). CQS2: Communications and Postal mail
 * left; those activities stay under All activities.
 */
const ACTIVITY_TABS: Array<{ key: ActivityType; label: string }> = [
  { key: 'all', label: 'All activities' },
  { key: 'notes', label: 'Notes' },
  { key: 'emails', label: 'Emails' },
  { key: 'calls', label: 'Calls' },
  { key: 'tasks', label: 'Tasks' },
  { key: 'meetings', label: 'Meetings' },
];

/** API `types` query for each activity tab (`all` = every type). */
const ACTIVITY_TYPES: Record<ActivityType, string | undefined> = {
  all: undefined,
  notes: 'note',
  emails: 'email',
  calls: 'call',
  tasks: 'task',
  meetings: 'meeting',
};

/** R5b: the tab a composer moves the timeline to, as the design's `TAB_OF` (ac.js:1053). */
const DRAWER_TAB: Partial<Record<Drawer, ActivityType>> = {
  note: 'notes',
  email: 'emails',
  'log-email': 'emails',
  call: 'calls',
  dial: 'calls',
  task: 'tasks',
  meeting: 'meetings',
  'log-meeting': 'meetings',
};

const NO_ITEMS: TimelineItem[] = [];

/** The same wording as the sequence's Enrollments tab (QA 16 Oct #135). */
function enrollmentStatusLabel(row: SequenceEnrollment): string {
  if (row.status === 'active') {
    if (row.waitingOnTask) return 'Waiting on task';
    return row.currentStep <= 0 ? 'Scheduled' : 'In progress';
  }
  if (row.status === 'paused') return 'Paused';
  if (row.status === 'exited' && row.exitReason === 'unenrolled') return 'Unenrolled';
  if (row.status === 'exited' && row.exitReason === 'sequence_deleted') return 'Sequence deleted';
  if (row.status === 'failed') return 'Error';
  return 'Finished';
}

const isCurrentEnrollment = (row: SequenceEnrollment) =>
  row.status === 'active' || row.status === 'paused';

const ENROLLMENT_ACTION_DONE: Record<'pause' | 'resume' | 'stop', string> = {
  pause: 'Enrollment paused',
  resume: 'Enrollment resumed',
  stop: 'Contact unenrolled',
};

function enrollmentStatusClass(status: SequenceEnrollment['status']): string {
  if (status === 'active') return 'tag tag-marketing';
  if (status === 'paused') return 'tag tag-opportunity';
  if (status === 'failed') return 'tag tag-lead';
  return 'tag';
}

function contactDisplayName(c: Contact): string {
  const name = [c.firstName, c.lastName].filter(Boolean).join(' ').trim();
  return name || c.email || 'Untitled contact';
}

function BackIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M15 18l-6-6 6-6" />
    </svg>
  );
}

function ExternalLinkIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M18 13v6a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
      <path d="M15 3h6v6" />
      <path d="M10 14 21 3" />
    </svg>
  );
}

function CopyIcon() {
  return (
    <svg
      viewBox="0 0 24 24"
      width="14"
      height="14"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <rect x="9" y="9" width="12" height="12" rx="2" />
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
    </svg>
  );
}

function SearchIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
      <circle cx="11" cy="11" r="7" />
      <path d="m20 20-3.5-3.5" />
    </svg>
  );
}

function NoteActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <path d="M14 2v6h6" />
      <path d="M8 13h8M8 17h5" />
    </svg>
  );
}

function EmailActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="m3 7 9 6 9-6" />
    </svg>
  );
}

function TaskActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M9 11l3 3L22 4" />
      <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
    </svg>
  );
}

function MeetingActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <rect x="3" y="5" width="18" height="16" rx="2" />
      <path d="M16 3v4M8 3v4M3 11h18" />
    </svg>
  );
}

function CallActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M7 4c2 0 3 2 3 4 0 1-1 2-2 2l-1 1c1 3 3 5 6 6l1-1c0-1 1-2 2-2 2 0 4 1 4 3v2c0 1-1 2-2 2C10 21 3 14 3 6c0-1 1-2 2-2h2z" />
    </svg>
  );
}

function EditActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M12 20h9" />
      <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z" />
    </svg>
  );
}

function HistoryActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M12 8v4l3 3M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
      <path d="M3 3v5h5" />
    </svg>
  );
}

function MergeActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M6 3v6a6 6 0 0 0 6 6h6M15 12l3 3-3 3M6 21v-6" />
    </svg>
  );
}

function DeleteActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />
      <path d="M10 11v6M14 11v6" />
    </svg>
  );
}

/** Icons of the HUB-571 / HUB-572 menu items. */
function ToolIcon({ name }: { name: string }) {
  const paths: Record<string, React.ReactNode> = {
    follow: (
      <path d="M15 17h5l-1.4-1.4A2 2 0 0 1 18 14.2V11a6 6 0 1 0-12 0v3.2c0 .5-.2 1-.6 1.4L4 17h5m6 0a3 3 0 1 1-6 0" />
    ),
    properties: <path d="M4 6h16M4 12h16M4 18h10" />,
    history: <path d="M12 8v4l3 3M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5" />,
    review: <path d="M9 11l3 3L22 4M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />,
    google: <path d="M21 12a9 9 0 1 1-2.6-6.4M21 12h-9" />,
    optout: <path d="M4 4l16 16M3 7l9 6 3-2M21 7v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7" />,
    restore: <path d="M3 12a9 9 0 1 0 3-6.7L3 8M3 3v5h5" />,
    access: <path d="M12 3l8 4v5c0 5-3.5 8-8 9-4.5-1-8-4-8-9V7z" />,
    clone: <path d="M9 9h11v11H9zM5 15H4V4h11v1" />,
    linkedin: (
      <path d="M4 9h4v11H4zM6 4a2 2 0 1 1 0 4 2 2 0 0 1 0-4M10 9h4v2c.7-1.3 2-2 3.5-2 2.5 0 3.5 1.6 3.5 4.5V20h-4v-6c0-1.4-.5-2-1.6-2-1.2 0-1.9.8-1.9 2.2V20h-3.5z" />
    ),
    whatsapp: (
      <path d="M4 20l1.3-4A8 8 0 1 1 8 18.7zM9 9c0 3 3 6 6 6l1.5-1.5-2-1-1 1c-1-.5-2-1.5-2.5-2.5l1-1-1-2z" />
    ),
  };
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      {paths[name] ?? null}
    </svg>
  );
}

function MoreActionIcon() {
  return (
    <span className="crm-contact-profile__dots" aria-hidden>
      <i />
      <i />
      <i />
    </span>
  );
}

function AboutField({
  label,
  value,
  children,
  onHistory,
}: {
  label: string;
  value?: string;
  /** An in-place editor (HUB-615) shown instead of the plain value. */
  children?: ReactNode;
  /** HUB-356: open this field's property history. */
  onHistory?: () => void;
}) {
  // R3: inside "View all properties", the design's row around the same value or editor.
  const look = useDesignPropertyRow();
  if (look) return <DesignPropertyRow look={look}>{children ?? value}</DesignPropertyRow>;
  return (
    <div className="crm-about-field">
      <div className="crm-about-label">
        {label}
        {onHistory ? <PropertyHistoryButton label={label} onClick={onHistory} /> : null}
      </div>
      <div className="crm-about-value">{children ?? value}</div>
    </div>
  );
}

export function ContactDetailsView({ contactId }: { contactId: string }) {
  // HUB-226 D1: the object as the business names it ("Clients").
  const names = useObjectNames('contact');
  const me = useCurrentUser();
  // HUB-317: built-in fields the permission set hides (not shown) or makes view-only (locked).
  const access = useFieldAccess('contact');
  const lockFor = (key: string) =>
    access.locked(key) ? { canEdit: false, lockedTitle: VIEW_ONLY_TITLE } : null;
  const toast = useToast();
  const router = useRouter();
  const prefs = useUserPrefs();
  // A date and time in the user's format and time zone, as the timeline shows them (not the
  // browser's time zone, which made the About card disagree with the timeline).
  const formatDate = useCallback(
    (iso: string | null | undefined) =>
      formatUserDate(iso, { region: prefs.regionFormat, timeZone: prefs.timeZone, time: true }),
    [prefs.regionFormat, prefs.timeZone],
  );
  // CQ3 #9: Create date is a date only, as the design (record.php:103, record-tabs.js:51-57).
  const datePrefs = { region: prefs.regionFormat, timeZone: prefs.timeZone };
  const { owners } = useOwners(true, true);
  const ownerById = useMemo(() => new Map(owners.map((o) => [o.userId, o])), [owners]);
  const [contact, setContact] = useState<Contact | null>(null);
  /** Shown to admins (GET ?includeDeleted=true) when the contact is soft-deleted. */
  const [deleted, setDeleted] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [tab, setTab] = useState<CenterTab>('activity');
  /** HUB-380 / HUB-381: the record layout of my team (or the default); null: built in. */
  const myLayout = useMyRecordLayout('contact');
  const recordLayout = myLayout.layout;
  const cardDate = useCallback(
    (iso: string | null | undefined) =>
      formatUserDate(iso, { region: prefs.regionFormat, timeZone: prefs.timeZone }),
    [prefs.regionFormat, prefs.timeZone],
  );
  /** A sidebar card's layout settings, and its gear for admins (who may save layouts). */
  const cardView = (id: string): CardView => {
    const saved = recordLayout?.cards[id];
    return {
      ...(saved?.title ? { title: saved.title } : {}),
      ...(saved?.assoc?.props ? { props: saved.assoc.props } : {}),
      // batch 2: saved with filters / quick filters / sort, the card loads its own list
      ...(saved?.assoc && listMode(saved) ? { list: saved.assoc } : {}),
      // Only once the layout loaded: saving over a layout that failed to load would replace it.
      // LD6: the gear opens the record page editor on this card, and Exit comes back here
      // (record-tabs.js:32, record-layout-editor.js:663-668).
      ...(canEditCards(me.role) && myLayout.status === 'ready'
        ? {
            onGear: () =>
              router.push(
                recordEditorHref({
                  object: 'contact',
                  view: editorViewParam(myLayout.view),
                  card: id,
                  from: `/contacts/${contactId}`,
                }),
              ),
          }
        : {}),
    };
  };
  const layoutTabApplied = useRef(false);
  /** R8a: the tab `?tab=` named on load, until the layout shows whether the page has it. */
  const urlTab = useRef<CenterTab | null>(null);
  const urlTabRead = useRef(false);
  useEffect(() => {
    // R8a: `?tab=<layout tab id>` opens that tab, before the layout's default (rt.js:862).
    const q = new URLSearchParams(window.location.search).get('tab');
    const key = q ? tabKeyOf(q) : undefined;
    if (key) {
      layoutTabApplied.current = true;
      urlTab.current = key;
      setTab(key);
    }
    urlTabRead.current = true;
  }, []);
  useEffect(() => {
    if (!recordLayout?.defaultTab || layoutTabApplied.current) return;
    layoutTabApplied.current = true;
    const id = recordLayout.defaultTab;
    if (recordLayout.tabs.some((t) => t.id === id)) setTab(tabKeyOf(id));
  }, [recordLayout]);
  /** The middle tabs: the layout's (names and order), else Overview / Activities / Emails / History. */
  const centerTabs: Array<readonly [CenterTab, string]> = recordLayout?.tabs.length
    ? recordLayout.tabs.map((t) => [tabKeyOf(t.id), t.label] as const)
    : BUILT_IN_TABS;
  const centerTabKeys = centerTabs.map(([key]) => key).join(',');
  // R8a: a `?tab=` the page's tabs don't have falls back to the first tab, as the design.
  useEffect(() => {
    if (!urlTab.current || myLayout.status === 'loading') return;
    const keys = centerTabKeys.split(',') as CenterTab[];
    if (!keys.includes(urlTab.current)) setTab(keys[0] ?? 'activity');
    urlTab.current = null;
  }, [myLayout.status, centerTabKeys]);
  // R8a: the open tab is kept in `?tab=`, and the first tab has none (rt.js:917).
  const firstTab = centerTabs[0]?.[0];
  useEffect(() => {
    if (!urlTabRead.current || urlTab.current) return;
    const url = new URL(window.location.href);
    if (tab === firstTab) url.searchParams.delete('tab');
    else url.searchParams.set('tab', layoutIdOf(tab));
    if (url.href !== window.location.href) {
      window.history.replaceState(window.history.state, '', url);
    }
  }, [tab, firstTab]);
  /**
   * R10b: the open tab's cards and sections: its saved items, else the built-in ones
   * (`defaultLayout`, today's tab bodies). Fetches follow the cards it holds, not its key.
   */
  const openTabId = layoutIdOf(tab);
  const currentItems =
    (
      recordLayout?.tabs.find((t) => t.id === openTabId) ??
      BUILT_IN_CONTACT_LAYOUT.tabs.find((t) => t.id === openTabId)
    )?.items ?? [];
  const hasCard = (id: string) => currentItems.includes(id);
  /** R10b: closed sections, by `<tab id>|<index>` (open by default, not remembered). */
  const [closedSecs, setClosedSecs] = useState<Set<string>>(() => new Set());
  /** Cards in the layout's order; without a layout, in the page's own order. */
  const orderedCards = (order: string[] | undefined, cards: Record<string, ReactNode>) =>
    (order ?? Object.keys(cards)).map((key) =>
      key in cards ? <Fragment key={key}>{cards[key]}</Fragment> : null,
    );
  const [drawer, setOpenDrawer] = useState<Drawer | null>(null);
  /** The page stays usable behind a composer, so anything opening here asks it first. */
  const composer = useRef<ComposerWindowHandle | null>(null);
  const openDrawer = useRef<Drawer | null>(null);
  const setDrawer = useCallback((next: Drawer | null) => {
    if (next && composer.current?.holdOpen(next === openDrawer.current)) return;
    openDrawer.current = next;
    setOpenDrawer(next);
  }, []);
  // R2: the channel the communication drawer opens on (More's Log SMS / LinkedIn / WhatsApp).
  const [commChannel, setCommChannel] = useState<CommunicationChannel>('linkedin_message');
  const [cloneOpen, setCloneOpen] = useState(false);
  // R4: the sticky header watches the quick actions in the left column.
  const leftColumnRef = useRef<HTMLElement>(null);
  const quickRowRef = useRef<HTMLDivElement>(null);
  // R3: "View all properties" as the design's drawer, its groups labelled as the list pickers.
  const [propsOpen, setPropsOpen] = useState(false);
  // R7: the associated record whose preview a sidebar row opened.
  const [previewTarget, setPreviewTarget] = useState<PreviewTarget>(null);
  const contactGroups = usePickerGroups('contact', CONTACT_GROUPS);
  const [restoring, setRestoring] = useState(false);
  /** Bumped after an action, to reload the open tab. */
  const [refreshKey, setRefreshKey] = useState(0);

  const [contactPicklists, setContactPicklists] = useState<PicklistOption[]>([]);
  const [activityPicklists, setActivityPicklists] = useState<PicklistOption[]>([]);
  const [customDefs, setCustomDefs] = useState<CustomPropertyDefinition[]>([]);
  /** HUB-315: the Merge flow (pick the other record, then review). */
  const [mergeOpen, setMergeOpen] = useState(false);
  /** HUB-356: the property history drawer's field (`all` for every field); null when closed. */
  const [historyField, setHistoryField] = useState<string | null>(null);
  const describeHistory = useMemo(
    () =>
      contactHistoryDescriber({
        defs: customDefs,
        owners,
        picklists: contactPicklists,
        formatDateTime: formatDate,
      }),
    [customDefs, owners, contactPicklists, formatDate],
  );

  const [activityType, setActivityType] = useState<ActivityType>('all');
  const [activitySearch, setActivitySearch] = useState('');
  const [activitySort, setActivitySort] = useState<'newest' | 'oldest'>('newest');
  const [activityDate, setActivityDate] = useState<TimelineDateFilter>('all');
  /** R5b: several users and teams, as the design's chips (applied by the API). */
  const [activityUserIds, setActivityUserIds] = useState<string[]>([]);
  const [activityTeamIds, setActivityTeamIds] = useState<string[]>([]);
  const [activityFrom, setActivityFrom] = useState('');
  const [activityTo, setActivityTo] = useState('');
  /** R5b: the Activity chip's types; null follows the Activity display settings. */
  const [activityTypes, setActivityTypes] = useState<string[] | null>(null);
  const [teamOptions, setTeamOptions] = useState<Array<{ value: string; label: string }>>([]);
  /** HUB-572: the user's button order and default timeline types (after saving here). */
  const [buttonOrder, setButtonOrder] = useState<RecordActionButton[] | null>(null);
  const [displayTypes, setDisplayTypes] = useState<string[] | null | undefined>(undefined);
  const [prefsDialog, setPrefsDialog] = useState<'buttons' | 'display' | null>(null);
  /** HUB-617: the association history drawer of one card (or all links). */
  const [assocHistory, setAssocHistory] = useState<{ type?: string; title: string } | null>(null);
  const [collapsedIds, setCollapsedIds] = useState<Set<string>>(() => new Set());

  const [sequenceChoices, setSequenceChoices] = useState<Sequence[]>([]);
  const [selectedSequenceId, setSelectedSequenceId] = useState('');
  const [mailboxId, setMailboxId] = useState<string | null>(null);
  const [mailboxReady, setMailboxReady] = useState(false);
  const [mailboxEmail, setMailboxEmail] = useState<string | null>(null);
  /** The last sequence load failed (the dialog says so rather than "no sequences"). */
  const [sequencesFailed, setSequencesFailed] = useState(false);
  /** SQ1: the design's "Enroll in a sequence" dialog (record-popups-hs.js:822-864). */
  const [enrollDialogOpen, setEnrollDialogOpen] = useState(false);
  /** MM1: which of More's create dialogs is open (contract, payment link, quote, invoice). */
  const [commerceKind, setCommerceKind] = useState<CommerceKind | null>(null);
  const closeCommerce = useCallback(() => setCommerceKind(null), []);
  // Stable, so the open dialog does not move focus back to its search on each page render.
  const closeEnrollDialog = useCallback(() => setEnrollDialogOpen(false), []);
  const [enrollments, setEnrollments] = useState<SequenceEnrollment[]>([]);
  const [enrollmentsLoading, setEnrollmentsLoading] = useState(false);
  const [enrollOpen, setEnrollOpen] = useState(false);
  const [busyEnrollmentId, setBusyEnrollmentId] = useState<string | null>(null);

  const { confirm: confirmEnrollment, dialog: enrollmentConfirmDialog } = useConfirm();
  /** The one "Send emails from": the user's own connected mailbox (HUB-195). */
  const sequenceSender = {
    mailboxId,
    ready: mailboxReady,
    label: mailboxEmail ? `${me.user.name} (${mailboxEmail})` : me.user.name,
  };

  const isAdmin = me.role === 'admin';
  const canUseSequences = me.permissionSet.rules.app.use_sequences;

  /** `quiet`: refresh in place (after an action) without the full-page loading state. */
  const load = useCallback(
    async (quiet = false) => {
      if (!quiet) setLoading(true);
      setError(null);
      try {
        setContact(await getContact(contactId));
        setDeleted(false);
      } catch (err) {
        if (isApiError(err) && err.isNotFound) {
          // an admin may still see it when it was deleted (and restore it)
          const gone = isAdmin ? await getContact(contactId, true).catch(() => null) : null;
          if (gone) {
            setContact(gone);
            setDeleted(true);
          } else {
            setError('This contact was not found or has been deleted.');
            setContact(null);
          }
        } else {
          setError(isApiError(err) ? err.message : 'Could not load this contact.');
          setContact(null);
        }
      } finally {
        if (!quiet) setLoading(false);
      }
    },
    [contactId, isAdmin],
  );

  useEffect(() => {
    void load();
  }, [load]);

  // dropdown labels and custom field definitions, for the About section and the drawers
  useEffect(() => {
    listPicklistOptions({ objectType: 'contact', includeArchived: true }).then(
      setContactPicklists,
      () => {},
    );
    listPicklistOptions({ objectType: 'activity' }).then(setActivityPicklists, () => {});
    listCustomProperties({ objectType: 'contact' }).then(
      (defs) =>
        setCustomDefs(
          defs.filter((d) => !d.archived).sort((a, b) => a.displayOrder - b.displayOrder),
        ),
      () => {},
    );
  }, []);

  useEffect(() => {
    listTeamOptions().then(
      (res) => setTeamOptions(res.data.map((t) => ({ value: t.id, label: t.name }))),
      () => setTeamOptions([]),
    );
  }, []);

  const loadSequenceData = useCallback(async () => {
    if (!canUseSequences || deleted) return;
    setEnrollmentsLoading(true);
    try {
      const [sequencesPage, mailbox, enrollmentPage] = await Promise.all([
        listSequences({ status: 'active', limit: 100 }),
        getMyMailbox(),
        listContactSequenceEnrollments(contactId, { limit: 20 }),
      ]);

      setSequenceChoices(sequencesPage.data);
      setSelectedSequenceId((current) => keepSequencePick(current, sequencesPage.data));
      setMailboxId(mailbox.id ?? null);
      setMailboxReady(Boolean(mailbox.connected && mailbox.status === 'connected' && mailbox.id));
      setMailboxEmail(mailbox.emailAddress ?? null);
      setEnrollments(enrollmentPage.data);
      setSequencesFailed(false);
    } catch {
      setSequencesFailed(true);
      setSequenceChoices([]);
      setEnrollments([]);
      setMailboxId(null);
      setMailboxReady(false);
      setMailboxEmail(null);
    } finally {
      setEnrollmentsLoading(false);
    }
  }, [canUseSequences, contactId, deleted]);

  useEffect(() => {
    if (!contact || deleted || !canUseSequences) {
      setSequenceChoices([]);
      setEnrollments([]);
      setMailboxId(null);
      setMailboxReady(false);
      return;
    }
    void loadSequenceData();
  }, [canUseSequences, contact, deleted, loadSequenceData]);

  /** HUB-426: the user, team and date filters, applied by the API (paging stays right). */
  const serverFilters = useMemo(
    () =>
      timelineServerFilters({
        date: activityDate,
        from: activityFrom,
        to: activityTo,
        userIds: activityUserIds,
        teamIds: activityTeamIds,
      }),
    [activityDate, activityFrom, activityTo, activityUserIds, activityTeamIds],
  );
  const fetchTimeline = useCallback<TimelineFetch>(
    (params) => getContactTimeline(contactId, { ...params, ...serverFilters }),
    [contactId, serverFilters],
  );
  /** HUB-572: All activities shows the user's default types (Activity Display Settings). */
  const defaultTypes = displayTypes === undefined ? prefs.timelineTypes : displayTypes;
  // R5b: the Activity chip starts from those defaults and applies on every tab (raf.js:69-71);
  // a sub-tab whose type is off shows nothing.
  const chosenTypes = useMemo(
    () =>
      activityTypes ??
      (defaultTypes?.length
        ? ALL_TIMELINE_TYPES.filter((t) => defaultTypes.includes(t))
        : [...ALL_TIMELINE_TYPES]),
    [activityTypes, defaultTypes],
  );
  const typesParam = timelineTypesParam(ACTIVITY_TYPES[activityType], chosenTypes);
  const noTypes = typesParam === null;
  const timelineTypes = typesParam ?? undefined;
  const timelineEnabled = Boolean(contact) && !deleted && hasCard('activities') && !noTypes;
  const timelineReloadKey = `${refreshKey}|${contact?.updatedAt ?? ''}|${JSON.stringify(serverFilters)}`;
  const timelineState = useRecordTimeline({
    fetchPage: fetchTimeline,
    types: timelineTypes,
    enabled: timelineEnabled,
    reloadKey: timelineReloadKey,
  });
  const timeline = noTypes ? NO_ITEMS : timelineState.items;
  /** G8: pinned items, with the same types and filters as the timeline. */
  const pinParams = useMemo(
    () => ({ ...(timelineTypes ? { types: timelineTypes } : {}), ...serverFilters }),
    [timelineTypes, serverFilters],
  );
  const timelinePins = useTimelinePins({
    record: 'contacts',
    recordId: contactId,
    params: pinParams,
    enabled: timelineEnabled,
    reloadKey: timelineReloadKey,
  });
  const callOutcomes = useMemo(
    () => activityPicklists.filter((o) => o.field === 'callOutcome' && !o.archived),
    [activityPicklists],
  );
  const timelineEditing = useTimelineEditing({
    outcomes: callOutcomes,
    timeZone: prefs.timeZone,
    disabled: deleted,
    onUpdated: (item, patch) => {
      timelineState.updateItem(item.id, patch);
      timelinePins.patchItem(item.id, patch);
    },
    onDeleted: (item) => {
      timelineState.removeItem(item.id);
      timelinePins.dropItem(item.id);
    },
  });

  /** R10b: the Overview cards' data, for the ones the open tab holds. */
  const overviewData = useContactOverviewData(
    contactId,
    `${refreshKey}|${contact?.updatedAt ?? ''}`,
    {
      recent: !deleted && hasCard('recent'),
      upcoming: !deleted && hasCard('upcoming'),
      totals: !deleted && hasCard('totals'),
    },
  );

  /** HUB-618: how timeline items read (labels and values in plain words). */
  const readableCtx: ReadableContext = useMemo(
    () => ({
      recordName: contact ? contactDisplayName(contact) : '',
      describe: describeHistory,
      region: prefs.regionFormat,
      timeZone: prefs.timeZone,
      objectLabel: names.singular,
    }),
    [contact, describeHistory, prefs.regionFormat, prefs.timeZone, names.singular],
  );

  /** Whether an item stays in view under the tab and the search (pinned items too, G8). */
  const activityMatches = useCallback(
    (item: TimelineItem) => {
      const q = activitySearch.trim().toLowerCase();
      // HUB-618: only meaningful property changes in All activities (the rest are in History).
      if (
        activityType === 'all' &&
        item.type === 'field_change' &&
        !MEANINGFUL_FIELDS.has(String(item.field ?? ''))
      ) {
        return false;
      }
      if (!q) return true;
      const r = readable(item, readableCtx);
      const text = [r.title, r.body ?? '', ...r.meta, timelineBody(item, formatDate) ?? '']
        .join(' ')
        .toLowerCase();
      return (
        text.includes(q) ||
        String(item.type).includes(q) ||
        timelineTitle(item).toLowerCase().includes(q)
      );
    },
    [activitySearch, activityType, readableCtx, formatDate],
  );

  const filteredTimeline = useMemo(() => {
    // G8: a pinned item shows once, at the top.
    const filtered = withoutPinned(timeline, timelinePins.pins).filter(activityMatches);
    const sorted = [...filtered].sort((a, b) => {
      const diff = new Date(a.occurredAt).getTime() - new Date(b.occurredAt).getTime();
      return activitySort === 'newest' ? -diff : diff;
    });
    return sorted;
  }, [timeline, timelinePins.pins, activitySort, activityMatches]);

  /** G8: pinned items in view, newest pin first, above the dated list. */
  const shownPins = useMemo(
    () => (noTypes ? [] : timelinePins.pins.filter((p) => activityMatches(p.item))),
    [noTypes, timelinePins.pins, activityMatches],
  );

  /** R5b: the empty state says "No matching" under a search or any filter (at.js:470). */
  const activityFiltered =
    Boolean(activitySearch.trim()) ||
    chosenTypes.length !== ALL_TIMELINE_TYPES.length ||
    activityDate !== 'all' ||
    activityUserIds.length > 0 ||
    activityTeamIds.length > 0;

  /** R5b: the design's Clear all: every type on, the filters and the search emptied (raf.js:223). */
  const clearActivityFilters = () => {
    setActivityTypes([...ALL_TIMELINE_TYPES]);
    setActivitySort('newest');
    setActivityDate('all');
    setActivityUserIds([]);
    setActivityTeamIds([]);
    setActivityFrom('');
    setActivityTo('');
    setActivitySearch('');
  };

  // R5b: opening a composer moves the timeline to its tab, the search emptied (ac.js:1053,
  // :1704-1705, through setTab, at.js:389).
  useEffect(() => {
    const next = drawer ? DRAWER_TAB[drawer] : undefined;
    if (!next || next === activityType) return;
    setActivityType(next);
    setActivitySearch('');
    // eslint-disable-next-line react-hooks/exhaustive-deps -- only when a composer opens
  }, [drawer]);

  const activityByMonth = useMemo(() => {
    const map = new Map<string, TimelineItem[]>();
    for (const item of filteredTimeline) {
      // QA #352: the month heading in the user's region format and time zone, as its items.
      const key = formatUserMonthYear(item.occurredAt, {
        region: prefs.regionFormat,
        timeZone: prefs.timeZone,
      });
      const list = map.get(key) ?? [];
      list.push(item);
      map.set(key, list);
    }
    return [...map.entries()];
  }, [filteredTimeline, prefs.regionFormat, prefs.timeZone]);

  const closeDrawer = useCallback(() => setDrawer(null), [setDrawer]);
  const openExtensionAction = useCallback(
    (action: (typeof EXTENSION_ACTIONS)[number]) => {
      setDrawer(action);
    },
    [setDrawer],
  );
  useOpenRecordAction(
    `/contacts/${contactId}`,
    EXTENSION_ACTIONS,
    Boolean(contact) && !deleted,
    openExtensionAction,
  );
  // R7: a sidebar row's "View all properties" on another record opens this one's drawer.
  usePanelParam(`/contacts/${contactId}`, Boolean(contact), () => setPropsOpen(true));

  /**
   * "View all properties": every standard and custom property with its value. Declared before
   * `useRecordTools`, which calls it while rendering its drawer (CQ3: after it, opening the drawer
   * threw "Cannot access before initialization").
   */
  const allPropertyRows = (): Array<{ label: string; value: string }> => {
    if (!contact) return [];
    const standard: Array<[string, string]> = [
      ['First name', contact.firstName ?? ''],
      ['Last name', contact.lastName ?? ''],
      ['Email', contact.email ?? ''],
      ['Phone number', contact.phone ?? ''],
      ['Job title', contact.jobTitle ?? ''],
      // CQ3 #19: the design's All Properties reads the one company value (record.php:253).
      ['Company name', contactCompanyText(contact)],
      ['Contact owner', contact.owner?.name ?? ''],
      ['Lifecycle stage', describeHistory('lifecycleStage').text(contact.lifecycleStage)],
      ['Lead status', describeHistory('leadStatus').text(contact.leadStatus)],
      ['Email status', contact.emailStatus ?? ''],
      ['Record source', contact.source ?? ''],
      ['Create date', createdText(contact.createdAt, datePrefs)],
      ['Last modified', formatDate(contact.updatedAt)],
      // G18: the contacts merged into this one.
      [MERGED_IDS_LABEL.contact, mergedIdsText(contact.mergedIds)],
      // CB8 (CT-05): their emails, kept here (the API leaves them out when Email is hidden).
      [ADDITIONAL_LABEL.contact, additionalText(contact.additionalEmails)],
    ];
    const custom = customDefs.map((d) => {
      const info = describeHistory(customHistoryField(d.name));
      return [info.label, info.text(contact.customProperties?.[d.name])] as [string, string];
    });
    return [...standard, ...custom].map(([label, value]) => ({
      label,
      value: value === '--' ? '' : value,
    }));
  };

  // HUB-571 / HUB-382: Follow, View all properties, association history, Review
  // associations, Search in Google, Opt out of email, Restore activity, Record access, Clone.
  const toolsCanEdit =
    Boolean(contact) &&
    !deleted &&
    scopeCovers(
      me.permissionSet.rules.objects.contact.edit,
      contact?.owner?.id,
      me,
      contact?.sharedWithMe,
      contact?.ownerFieldMatch,
    );
  const tools = useRecordTools({
    // LD2: Restore activity opens the recycle bin, as the design.
    restoreDesign: true,
    recordType: 'contact',
    recordId: contactId,
    name: contact ? contactDisplayName(contact) : '',
    email: contact?.email,
    searchText: contact
      ? [contactDisplayName(contact), contact.companies.find((c) => c.isPrimary)?.name]
          .filter(Boolean)
          .join(' ')
      : '',
    canEdit: toolsCanEdit,
    canLog: !deleted && me.role !== 'read_only',
    timeZone: prefs.timeZone,
    properties: () => allPropertyRows(),
    onChanged: () => {
      setRefreshKey((k) => k + 1);
      void load(true);
    },
    // R2: Clone opens the design's form (CloneRecordDrawer).
    onClone: () => setCloneOpen(true),
    icon: (name) => <ToolIcon name={name} />,
    // R2: Opt out as the design's modal with its "I understand" box.
    optOutDesign: true,
    // G12: View record access as the 28 Oct design, saving the owner as the About card does.
    accessDesign: {
      variant: 'record',
      one: names.singular.toLowerCase(),
      ownerLabel: `${names.singular} owner`,
      owner: contact?.owner ? { id: contact.owner.id, name: contact.owner.name } : null,
      ...ownerLock({
        canEdit: toolsCanEdit,
        deletedTitle: deleted ? 'This contact is deleted' : null,
        viewOnlyTitle: access.locked('ownerId') ? VIEW_ONLY_TITLE : null,
      }),
      saveOwner: async (ownerId) => {
        if (!contact) return;
        const saved = await updateContact(contact.id, { ownerId, updatedAt: contact.updatedAt });
        setContact((prev) => keepMergedIds(prev, saved));
      },
      loadHistory: (params) => getContactHistory(contactId, params),
      describe: describeHistory,
      reloadKey: contact?.updatedAt,
    },
  });

  // R2: the copy is master's clone body with the form's values on top (record-popups-hs.js:577).
  const cloneContact = async (v: Record<string, string>) => {
    if (!contact) return;
    try {
      const copy = await createContact({
        ...cloneContactBody(contact),
        email: v.email || null,
        firstName: v.firstName || null,
        lastName: v.lastName || null,
        companyName: v.companyName || null,
        jobTitle: v.jobTitle || null,
        phone: v.phone || null,
      });
      toast(`${[v.firstName, v.lastName].filter(Boolean).join(' ')} was created`);
      setCloneOpen(false);
      router.push(`/contacts/${copy.id}`);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
      throw err;
    }
  };

  /** After a note, call, task, meeting or email: show it on the timeline. */
  const afterActivity = useCallback(
    (reloadContact = false) => {
      setTab('activity');
      setRefreshKey((k) => k + 1);
      if (reloadContact) void load(true);
    },
    [load],
  );

  /** After linking / unlinking a company or deal: reload the contact (the open tab follows). */
  const afterAssociation = useCallback(() => load(true), [load]);

  /** Opens the preview: who is eligible and when each step runs; Confirm there enrolls. */
  const onEnrollInSequence = () => {
    if (!contact) return;
    if (!selectedSequenceId) {
      toast('Select a sequence first', 'info');
      return;
    }
    if (!mailboxReady || !mailboxId) {
      toast('Connect your mailbox in Settings > Email before enrolling contacts', 'info');
      return;
    }
    setEnrollOpen(true);
  };

  const onEnrollmentAction = async (
    row: SequenceEnrollment,
    action: 'pause' | 'resume' | 'stop',
  ) => {
    const id = row.id;
    // #63: unenrolling asks first, in the app's dialog, as the sequence's Enrollments tab does
    // (HubSpot confirms in a dialog with an "Unenroll" button).
    if (
      action === 'stop' &&
      !(await confirmEnrollment({
        title: 'Unenroll contact',
        message: `Unenroll ${contact ? contactDisplayName(contact) : 'this contact'} from ${row.sequenceName}? No more steps will run for them.`,
        confirmLabel: 'Unenroll',
        danger: true,
      }))
    ) {
      return;
    }
    setBusyEnrollmentId(id);
    try {
      await controlSequenceEnrollment(id, action);
      toast(ENROLLMENT_ACTION_DONE[action]);
      await loadSequenceData();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusyEnrollmentId(null);
    }
  };

  const onRestore = async () => {
    if (restoring) return;
    setRestoring(true);
    try {
      setContact(await restoreContact(contactId));
      setDeleted(false);
      setRefreshKey((k) => k + 1);
      toast('Contact restored');
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setRestoring(false);
    }
  };

  if (loading) {
    return (
      <div className="crm-contact-layout">
        <p className="crm-text-body-secondary crm-p-3">Loading contact…</p>
      </div>
    );
  }

  if (error || !contact) {
    return (
      <div className="crm-contact-layout crm-p-3">
        <Alert tone="danger">{error ?? 'Contact not found.'}</Alert>
        <Link className="link crm-mt-3 crm-d-inline-block" href="/contacts">
          Back to contacts
        </Link>
      </div>
    );
  }

  const name = contactDisplayName(contact);
  const noteAssociations = [
    ...contact.companies.map(asCompanyAssoc),
    ...contact.deals.map(asDealAssoc),
  ];
  const primaryCompany = contact.companies.find((c) => c.isPrimary) ?? contact.companies[0] ?? null;
  // CQ3 #19: the header and About "Company name" show one value, as the design's
  // (record.php:144, record-page.js:157).
  const designation = headerSubtitle(contact, { textHidden: access.hidden('companyName') });

  // what the permission set allows (the API checks again; a 403 shows as a toast)
  const rule = me.permissionSet.rules.objects.contact;
  // `team` (HUB-322): records of the user's team too.
  // P2a: Delete and Merge follow their own scopes on this record (`recordRights`).
  const rights = recordRights(
    rule,
    contact.owner?.id,
    me,
    contact.sharedWithMe,
    contact.ownerFieldMatch,
  );
  const canEdit = !deleted && rights.edit;
  const canDelete = !deleted && rights.delete;
  const canMerge = !deleted && rights.merge;
  const canLog = !deleted && me.role !== 'read_only';
  // PB7: the Playbooks card's rows open the playbook dialog on this contact. Logging needs edit
  // access on the contact (the API's `assertLinkedRecordsEditable`).
  const playbookRun: PlaybookRunContext = {
    record: {
      objectType: 'contact',
      id: contact.id,
      name,
      canLog: canLog && canEdit,
      links: {
        company: contact.companies.map((c) => ({ id: c.id, name: c.name, primary: c.isPrimary })),
        deal: contact.deals.map((d) => ({ id: d.id, name: d.name })),
      },
      values: contact.customProperties ?? {},
    },
    snippetTarget: { contactId: contact.id },
    onLogged: () => afterActivity(true),
  };
  const editTitle = deleted
    ? 'This contact is deleted'
    : canEdit
      ? undefined
      : "Your permissions don't allow you to edit this record";
  const logTitle = deleted
    ? 'This contact is deleted'
    : canLog
      ? undefined
      : "Your permissions don't allow you to log activity";
  const activityAdd = activityTabAddAction(activityType);
  const activityLog = activityTabLogAction(activityType);

  const picklistLabel = (field: string, value: string | null) =>
    value
      ? (contactPicklists.find((o) => o.field === field && o.value === value)?.label ??
        formatPicklistLabel(value))
      : '--';
  const activeOptions = (list: PicklistOption[], field: string) =>
    list.filter((o) => o.field === field && !o.archived);

  // R2: one record tool by key, after a divider when `separated` (record.php:299-323).
  const toolAction = (key: string, separated = false): ContactAction[] => {
    const a = tools.actions.find((x) => x.key === key);
    // R3: "View all properties" opens the design's drawer (AllPropertiesDesignDrawer).
    const own = a?.key === 'all-properties' ? { ...a, onSelect: () => setPropsOpen(true) } : a;
    return own ? [separated ? { ...own, separated: true } : own] : [];
  };
  const historyAction: ContactAction = {
    key: 'history',
    label: 'View property history',
    icon: <HistoryActionIcon />,
    onSelect: () => setHistoryField('all'),
  };
  // R2: the design's Actions menu, in its order and groups (record.php:299-323). Summarize (AI)
  // and Export (a design stub) are left out. Edit contact and Activity display settings are
  // master's own, kept in a last group. Activities moved to More (`moreItems`).
  const actions: ContactAction[] = [
    ...toolAction('follow'),
    ...toolAction('all-properties', true),
    historyAction,
    ...toolAction('association-history', true),
    ...toolAction('review-associations'),
    ...toolAction('google', true),
    ...toolAction('opt-out'),
    ...toolAction('restore-activity', true),
    ...toolAction('record-access'),
    {
      key: 'merge',
      label: 'Merge',
      icon: <MergeActionIcon />,
      onSelect: () => setMergeOpen(true),
      disabled: !canMerge,
      title: canMerge ? undefined : MERGE_DENIED_TITLE,
    },
    ...toolAction('clone'),
    {
      key: 'delete',
      // R1: the design's label (record.php:320).
      label: 'Delete',
      icon: <DeleteActionIcon />,
      onSelect: () => setDrawer('delete'),
      disabled: !canDelete,
      title: canDelete ? undefined : "Your permissions don't allow you to delete this record",
    },
    {
      key: 'edit',
      label: 'Edit contact',
      icon: <EditActionIcon />,
      onSelect: () => setDrawer('edit'),
      disabled: !canEdit,
      title: editTitle,
      separated: true,
    },
    {
      key: 'display',
      label: 'Activity display settings',
      icon: <HistoryActionIcon />,
      onSelect: () => setPrefsDialog('display'),
    },
  ];
  // R2: the About card's Actions (record-tabs.js:235). LD6: Customize properties opens the record
  // page editor on About (record.php:433; manage_settings only). Fill smart properties (AI) is
  // left out.
  const aboutActions: ContactAction[] = [
    ...(me.permissionSet.rules.app.manage_settings
      ? [
          {
            key: 'customize-properties',
            label: 'Customize properties',
            icon: <EditActionIcon />,
            // LD6: the editor on About, with no `from`, as record.php:433.
            onSelect: () =>
              router.push(
                recordEditorHref({
                  object: 'contact',
                  view: editorViewParam(myLayout.view),
                  card: 'about',
                }),
              ),
          },
        ]
      : []),
    ...toolAction('all-properties'),
    historyAction,
  ];
  const QUICK_ICONS: Record<RecordActionButton, ReactNode> = {
    note: <NoteActionIcon />,
    email: <EmailActionIcon />,
    call: <CallActionIcon />,
    task: <TaskActionIcon />,
    meeting: <MeetingActionIcon />,
  };
  // HUB-572: the buttons in the user's order.
  const order = buttonOrder ?? prefs.recordActionButtons;
  // C9b: Call opens the dialer window, as the design (record.php:344, record-popups-hs.js:979),
  // by the user's call (20 Nov); Log a call stays in More, the sticky header and the Calls tab.
  const quickDrawer = (key: RecordActionButton): Drawer => (key === 'call' ? 'dial' : key);
  const quickActions: Array<{ key: Drawer; label: string; title: string; icon: ReactNode }> =
    order.map((key) => ({
      key: quickDrawer(key),
      label: BUTTON_LABELS[key],
      title: BUTTON_TITLES[key],
      icon: QUICK_ICONS[key],
    }));
  const logItem = (key: string, label: string, icon: ReactNode, open: () => void) => ({
    key,
    label,
    icon,
    onSelect: open,
    disabled: !canLog,
    title: logTitle,
  });
  const logCommunication = (channel: CommunicationChannel) => () => {
    setCommChannel(channel);
    setDrawer('communication');
  };
  // R2: More's activities, in the design's order (record-popups-hs.js:982-986): any button not
  // in the row, then the rest. LinkedIn and WhatsApp keep master's working actions; Enroll opens
  // the design's dialog (SQ1, MM1).
  // R4: the sticky header's "Create activities" (record.php:365-372). "Make a call" is the
  // dialer window (C9).
  const stickyActivities: ContactAction[] = [
    logItem('s-note', 'Create note', <NoteActionIcon />, () => setDrawer('note')),
    logItem('s-email', 'Create email', <EmailActionIcon />, () => setDrawer('email')),
    logItem('s-log-email', 'Log email', <EmailActionIcon />, () => setDrawer('log-email')),
    logItem('s-dial', 'Make a call', <CallActionIcon />, () => setDrawer('dial')),
    logItem('s-call', 'Log call', <CallActionIcon />, () => setDrawer('call')),
    logItem('s-task', 'Create task', <TaskActionIcon />, () => setDrawer('task')),
    logItem('s-meeting', 'Schedule meeting', <MeetingActionIcon />, () => setDrawer('meeting')),
    logItem('s-log-meeting', 'Log meeting', <MeetingActionIcon />, () => setDrawer('log-meeting')),
  ];
  // MM1: the design's current order (record-popups-hs.js:997 on design.admedia.com, 20 Nov
  // 2026): Create a contract / payment link / quote / invoice first, each opening its create
  // dialog (`commerce()`), and the design's outline icons (:969-991). Engage on LinkedIn has the
  // design's › but keeps master's LinkedIn search (the user, 20 Nov).
  const moreItems: MoreMenuItem[] = [
    ...COMMERCE_KINDS.map((kind) =>
      logItem(kind, COMMERCE[kind].title, <MoreMenuIcon name={kind} />, () =>
        setCommerceKind(kind),
      ),
    ),
    ...fullOrder([])
      .filter((key) => !order.includes(key))
      .map((key) =>
        logItem(key, BUTTON_TITLES[key], QUICK_ICONS[key], () => setDrawer(quickDrawer(key))),
      ),
    {
      key: 'enroll-sequence',
      label: 'Enroll in a sequence',
      icon: <MoreMenuIcon name="seq" />,
      onSelect: () => setEnrollDialogOpen(true),
      disabled: !canLog || !canUseSequences,
    },
    {
      key: 'linkedin',
      label: 'Engage on LinkedIn',
      icon: <MoreMenuIcon name="li" />,
      chevron: true,
      onSelect: () =>
        window.open(
          `https://www.linkedin.com/search/results/people/?keywords=${encodeURIComponent(
            [name, primaryCompany?.name].filter(Boolean).join(' '),
          )}`,
          '_blank',
          'noopener',
        ),
    },
    logItem('sms', 'Log SMS', <MoreMenuIcon name="sms" />, logCommunication('sms')),
    logItem(
      'linkedin-log',
      'Log a LinkedIn message',
      <MoreMenuIcon name="li" />,
      logCommunication('linkedin_message'),
    ),
    logItem(
      'whatsapp-log',
      'Log a WhatsApp message',
      <MoreMenuIcon name="wa" />,
      logCommunication('whats_app'),
    ),
    logItem('call-log', 'Log a call', <MoreMenuIcon name="logcall" />, () => setDrawer('call')),
    logItem('log-meeting', 'Log a meeting', <MoreMenuIcon name="logmeet" />, () =>
      setDrawer('log-meeting'),
    ),
    logItem('log-email', 'Log an email', <MoreMenuIcon name="mail" />, () =>
      setDrawer('log-email'),
    ),
    logItem('postal-mail', 'Log postal mail', <MoreMenuIcon name="post" />, () =>
      setDrawer('postal-mail'),
    ),
    {
      key: 'whatsapp',
      label: 'Create a WhatsApp message',
      icon: <MoreMenuIcon name="wa" />,
      onSelect: () =>
        window.open(
          `https://wa.me/${(contact.phone ?? '').replace(/\D+/g, '')}`,
          '_blank',
          'noopener',
        ),
      disabled: !contact.phone,
      title: contact.phone ? undefined : 'This contact has no phone number',
    },
  ];

  // G8: the activity list also waits for the pins, so a pinned item doesn't jump to the top.
  const activityLoading = !noTypes && (timelineState.loading || !timelinePins.settled);
  const activityError = noTypes ? null : timelineState.error;

  const selectedSequence = sequenceChoices.find((s) => s.id === selectedSequenceId) ?? null;

  /** HUB-615: save one in-place edit (PATCH with the loaded `updatedAt`) and show the result. */
  const saveContact = async (body: UpdateContactBody) => {
    let saved;
    try {
      saved = await updateContact(contact.id, { ...body, updatedAt: contact.updatedAt });
    } catch (err) {
      // CQ1 #2: the field the API rejected, in words, in the editor's error line (InlineEdit
      // shows a plain Error's message); anything else goes on as it came.
      if (hasFieldDetails(err)) {
        throw new Error(contactErrorText(err, (key) => contactFieldLabel(key, customDefs)));
      }
      throw err;
    }
    setContact((prev) => keepMergedIds(prev, saved));
    const dupText = duplicateWarningText(saved.warnings?.find((w) => w.code === 'duplicate_email'));
    if (dupText) toast(dupText, 'info', { durationMs: 8000 });
  };
  /** HUB-615: an email can be changed, never cleared, and must stay unique (sheet #147-148). */
  const checkEmail = async (email: string | null) => {
    if (!email) throw new Error('Email is required');
    const bad = emailError(email);
    if (bad) throw new Error(bad);
    const taken = await contactsWithEmail(email, contact.id).catch(() => ({
      matches: [],
      hidden: 0,
    }));
    if (emailInUse(taken)) throw new Error(duplicateEmailText(taken.matches, taken.hidden));
  };
  /**
   * LD3: the name popover's fields (record.php:113-120): First name, Last name, Job title (with
   * Details) and Email, with the old name editor's rules: hidden fields out, locked ones read-only.
   */
  const nameFields: NameField[] = [
    {
      key: 'firstName',
      label: 'First name',
      value: contact.firstName ?? '',
      maxLength: RECORD_TEXT_MAX.firstName,
      lockedTitle: lockFor('firstName')?.lockedTitle,
    },
    {
      key: 'lastName',
      label: 'Last name',
      value: contact.lastName ?? '',
      maxLength: RECORD_TEXT_MAX.lastName,
      lockedTitle: lockFor('lastName')?.lockedTitle,
    },
    ...(access.hidden('jobTitle')
      ? []
      : [
          {
            key: 'jobTitle',
            label: 'Job title',
            value: contact.jobTitle ?? '',
            maxLength: RECORD_TEXT_MAX.jobTitle,
            lockedTitle: lockFor('jobTitle')?.lockedTitle,
            details: true,
          },
        ]),
    ...(access.hidden('email')
      ? []
      : [
          {
            key: 'email',
            label: 'Email',
            value: contact.email ?? '',
            kind: 'email' as const,
            maxLength: RECORD_TEXT_MAX.email,
            lockedTitle: lockFor('email')?.lockedTitle,
          },
        ]),
  ];
  /** LD3: one name field saved alone; First name is required, Email checked (HUB-615). */
  const saveNameField = async (key: string, value: string) => {
    if (key === 'firstName' && !value) throw new Error('First name is required');
    if (key === 'email') await checkEmail(value || null);
    await saveContact({ [key]: value || null } as UpdateContactBody);
  };
  const textEdit = (
    // R3: first and last name too, for "View all properties".
    field: 'firstName' | 'lastName' | 'email' | 'phone' | 'jobTitle' | 'companyName',
    label: string,
    type: 'text' | 'email' | 'tel',
  ) => {
    // CQ3 #19: Company name shows the linked company when its text is empty, and opens on it.
    const company = field === 'companyName' ? companyNameEdit(contact) : null;
    return (
      <InlineEdit<string>
        label={label}
        display={company ? company.display : (contact[field] ?? '--')}
        canEdit={lockFor(field)?.canEdit ?? canEdit}
        lockedTitle={lockFor(field)?.lockedTitle ?? editTitle}
        initial={() => (company ? company.initial : (contact[field] ?? ''))}
        renderInput={(input) => (
          <InlineTextInput {...input} type={type} maxLength={RECORD_TEXT_MAX[field]} />
        )}
        onSave={async (raw) => {
          if (company) {
            const body = company.toSave(raw);
            if (body) await saveContact(body);
            return;
          }
          if (field === 'phone') {
            const phone = inlinePhoneValue(raw, contact.phone ?? null);
            if (phone !== undefined) await saveContact({ phone });
            return;
          }
          const next = raw.trim() || null;
          if (next === (contact[field] ?? null)) return;
          const invalid = next && field === 'email' ? emailError(next) : null;
          if (invalid) throw new Error(invalid);
          if (field === 'email') await checkEmail(next);
          await saveContact({ [field]: next });
        }}
      />
    );
  };
  const picklistEdit = (field: 'lifecycleStage' | 'leadStatus', label: string) => (
    <InlineEdit<string>
      label={label}
      saveOn="change"
      dropdown
      display={picklistLabel(field, contact[field])}
      canEdit={lockFor(field)?.canEdit ?? canEdit}
      lockedTitle={lockFor(field)?.lockedTitle ?? editTitle}
      initial={() => contact[field] ?? ''}
      renderInput={(input) => (
        <InlineSelectInput
          {...input}
          emptyLabel="--"
          options={picklistChoices(
            contactPicklists.filter((o) => o.field === field),
            contact[field],
          )}
        />
      )}
      onSave={async (value) => {
        if ((value || null) === (contact[field] ?? null)) return;
        await saveContact({ [field]: value || null });
      }}
    />
  );

  // HUB-380 / HUB-381: the About card's properties, in the order of the record layout.
  const aboutFieldMap: Record<string, ReactNode> = {
    email: (
      <>
        {access.hidden('email') ? null : (
          <AboutField label="Email" onHistory={() => setHistoryField('email')}>
            {textEdit('email', 'Email', 'email')}
          </AboutField>
        )}
      </>
    ),
    phone: (
      <>
        {access.hidden('phone') ? null : (
          <AboutField label="Phone number" onHistory={() => setHistoryField('phone')}>
            {textEdit('phone', 'Phone number', 'tel')}
          </AboutField>
        )}
      </>
    ),
    jobTitle: (
      <>
        {access.hidden('jobTitle') ? null : (
          <AboutField label="Job title" onHistory={() => setHistoryField('jobTitle')}>
            {textEdit('jobTitle', 'Job title', 'text')}
          </AboutField>
        )}
      </>
    ),
    companyName: (
      <>
        {access.hidden('companyName') ? null : (
          <AboutField label="Company name" onHistory={() => setHistoryField('companyName')}>
            {textEdit('companyName', 'Company name', 'text')}
          </AboutField>
        )}
      </>
    ),
    ownerId: (
      <>
        <AboutField label="Owner" onHistory={() => setHistoryField('ownerId')}>
          <InlineEdit<string>
            label="Owner"
            saveOn="change"
            dropdown
            display={ownerLabelFromCache(contact.owner, ownerById)}
            canEdit={lockFor('ownerId')?.canEdit ?? canEdit}
            lockedTitle={lockFor('ownerId')?.lockedTitle ?? editTitle}
            initial={() => contact.owner?.id ?? ''}
            renderInput={(input) => (
              <InlineSelectInput
                {...input}
                emptyLabel="No owner"
                options={ownerChoices(owners, contact.owner)}
              />
            )}
            onSave={async (value) => {
              if ((value || null) === (contact.owner?.id ?? null)) return;
              await saveContact({ ownerId: value || null });
            }}
          />
        </AboutField>
      </>
    ),
    additionalOwners: (
      <>
        <AboutField label="Additional owners">
          <AdditionalOwnersEdit
            current={contact.additionalOwners}
            owners={owners}
            canEdit={canEdit}
            lockedTitle={editTitle}
            onSave={(ids) => saveContact({ additionalOwnerIds: ids })}
          />
        </AboutField>
      </>
    ),
    lifecycleStage: (
      <>
        {access.hidden('lifecycleStage') ? null : (
          <AboutField label="Lifecycle" onHistory={() => setHistoryField('lifecycleStage')}>
            {picklistEdit('lifecycleStage', 'Lifecycle')}
          </AboutField>
        )}
      </>
    ),
    leadStatus: (
      <>
        {access.hidden('leadStatus') ? null : (
          <AboutField label="Lead status" onHistory={() => setHistoryField('leadStatus')}>
            {picklistEdit('leadStatus', 'Lead status')}
          </AboutField>
        )}
      </>
    ),
    emailStatus: (
      <>
        <AboutField label="Email status" value={formatPicklistLabel(contact.emailStatus)} />
      </>
    ),
    source: (
      <>
        <AboutField label="Source" value={formatPicklistLabel(contact.source)} />
      </>
    ),
    createdAt: (
      <>
        <AboutField label="Created" value={createdText(contact.createdAt, datePrefs)} />
      </>
    ),
    nextMeetingAt: (
      <>
        <AboutField label="Next meeting" value={formatDate(contact.nextMeetingAt)} />
      </>
    ),
    lastMeetingBookedAt: (
      <>
        <AboutField label="Last meeting booked" value={formatDate(contact.lastMeetingBookedAt)} />
      </>
    ),
    lastEmailOpenedAt: (
      <>
        <AboutField label="Last email opened" value={formatDate(contact.lastEmailOpenedAt)} />
      </>
    ),
    lastEmailClickedAt: (
      <>
        <AboutField label="Last email clicked" value={formatDate(contact.lastEmailClickedAt)} />
      </>
    ),
  };
  const aboutOrder = recordLayout?.cards.about?.props?.length
    ? recordLayout.cards.about.props
    : Object.keys(aboutFieldMap);
  /** A custom field the layout puts in the About card: its value, with its history. */
  const customAbout = (key: string) => {
    if (!key.startsWith('custom.')) return null;
    const info = describeHistory(key);
    return (
      <AboutField label={info.label} onHistory={() => setHistoryField(key)}>
        {info.text(contact.customProperties?.[key.slice('custom.'.length)])}
      </AboutField>
    );
  };
  const aboutFields = (
    <>
      {aboutOrder.map((key) => (
        <Fragment key={key}>{aboutFieldMap[key] ?? customAbout(key)}</Fragment>
      ))}
    </>
  );

  // R3: "View all properties" rows. Built-in fields in "Contact information" (as the list
  // pickers), edited with the About card's own editors; custom fields in their groups, with
  // the sidebar group cards' editor. Hidden fields are left out (`access.hidden`).
  const customEdit = {
    canEdit,
    lockedTitle: editTitle,
    timeZone: prefs.timeZone,
    formatDateTime: formatDate,
    onSave: (fieldName: string, value: CustomProperties[string] | null) =>
      saveContact({ customProperties: { [fieldName]: value } }),
  };
  const builtInRow = (
    key: string,
    label: string,
    text: string,
    node?: ReactNode,
    history = true,
  ): PropertyRow[] =>
    access.hidden(key)
      ? []
      : [
          {
            key,
            label,
            group: CONTACT_INFO,
            text,
            node: node ?? <AboutField label={label} value={text || '--'} />,
            onHistory: history ? () => setHistoryField(key) : undefined,
          },
        ];
  const propertyRows: PropertyRow[] = [
    ...builtInRow(
      'firstName',
      'First name',
      contact.firstName ?? '',
      <AboutField label="First name">{textEdit('firstName', 'First name', 'text')}</AboutField>,
    ),
    ...builtInRow(
      'lastName',
      'Last name',
      contact.lastName ?? '',
      <AboutField label="Last name">{textEdit('lastName', 'Last name', 'text')}</AboutField>,
    ),
    ...builtInRow('email', 'Email', contact.email ?? '', aboutFieldMap.email),
    ...builtInRow('phone', 'Phone number', contact.phone ?? '', aboutFieldMap.phone),
    ...builtInRow('jobTitle', 'Job title', contact.jobTitle ?? '', aboutFieldMap.jobTitle),
    ...builtInRow(
      'companyName',
      'Company name',
      contactCompanyText(contact),
      aboutFieldMap.companyName,
    ),
    ...builtInRow('ownerId', 'Contact owner', contact.owner?.name ?? '', aboutFieldMap.ownerId),
    ...builtInRow(
      'lifecycleStage',
      'Lifecycle stage',
      describeHistory('lifecycleStage').text(contact.lifecycleStage),
      aboutFieldMap.lifecycleStage,
    ),
    ...builtInRow(
      'leadStatus',
      'Lead status',
      describeHistory('leadStatus').text(contact.leadStatus),
      aboutFieldMap.leadStatus,
    ),
    ...builtInRow(
      'emailStatus',
      'Email status',
      formatPicklistLabel(contact.emailStatus),
      undefined,
      false,
    ),
    ...builtInRow('source', 'Record source', formatPicklistLabel(contact.source), undefined, false),
    ...builtInRow(
      'createdAt',
      'Create date',
      createdText(contact.createdAt, datePrefs),
      undefined,
      false,
    ),
    ...builtInRow('updatedAt', 'Last modified', formatDate(contact.updatedAt), undefined, false),
    // G18: the contacts merged into this one.
    ...builtInRow(
      'mergedIds',
      MERGED_IDS_LABEL.contact,
      mergedIdsText(contact.mergedIds),
      undefined,
      false,
    ),
    // CB8 (CT-05): emails of the contacts merged into this one; read-only, as Merged IDs, and
    // hidden with Email.
    ...(access.hidden('email')
      ? []
      : builtInRow(
          'additionalEmails',
          ADDITIONAL_LABEL.contact,
          additionalText(contact.additionalEmails),
          undefined,
          false,
        )),
    ...customDefs.map((d) => ({
      key: `custom.${d.name}`,
      label: d.label,
      group: (d.groupName && contactGroups.labelOf(d.groupName)) || 'Other properties',
      text: describeHistory(customHistoryField(d.name)).text(contact.customProperties?.[d.name]),
      node: (
        <CustomFieldsList defs={[d]} values={contact.customProperties ?? {}} edit={customEdit} />
      ),
      onHistory: () => setHistoryField(customHistoryField(d.name)),
    })),
  ];

  /**
   * R8b: Data highlights, as the design (record-tabs.js:124-127): the layout's
   * `cards.highlights.props`, else Create date, Lifecycle stage, Last activity date
   * (record-layout.js:109). Values from the property rows, so hidden fields are left out.
   */
  const highlightKeys = recordLayout?.cards.highlights?.props?.length
    ? recordLayout.cards.highlights.props
    : ['createdAt', 'lifecycleStage', 'lastActivity'];
  const overviewHighlights = highlightKeys.flatMap((key) => {
    if (key === 'lastActivity') {
      const last = contact.customProperties?.notes_last_updated;
      return [
        {
          key,
          label: 'Last activity date',
          value: last
            ? formatUserDate(String(last), { region: prefs.regionFormat, timeZone: prefs.timeZone })
            : '',
        },
      ];
    }
    const row = propertyRows.find((r) => r.key === key);
    return row ? [{ key, label: row.label, value: row.text }] : [];
  });
  /** R10c: a property's label and text on this contact (hidden fields left out). */
  const propText = (key: string): { label: string; value: string } | null => {
    if (key === 'lastActivity') return overviewHighlights.find((h) => h.key === key) ?? null;
    const row = propertyRows.find((r) => r.key === key);
    return row ? { label: row.label, value: row.text } : null;
  };
  const propValues = Object.fromEntries(propertyRows.map((r) => [r.key, r.text]));
  /**
   * R10d: whether a tab or card shows under the layout's conditional logic (record-tabs.js:20-27).
   * A rule tests the property's shown text and its stored value.
   */
  const condValue = (prop: string): string[] =>
    recordTexts(
      propValues[prop],
      prop.startsWith('custom.')
        ? contact.customProperties?.[prop.slice('custom.'.length)]
        : (contact as unknown as Record<string, unknown>)[prop],
    );
  const condShows = (key: string) => condOk(recordLayout?.cond, key, condValue);
  /** LD8: the left column's order: the layout's, else the built-in one (the design's five). */
  const leftOrder = recordLayout?.left ?? BUILT_IN_CONTACT_LAYOUT.left;
  /** LD8: the properties this business has, for the preset cards' rows. */
  const knownProps = new Set([
    ...(ABOUT_FIELDS.contact ?? []).map((f) => f.id),
    ...customDefs.map((d) => `custom.${d.name}`),
  ]);
  const leftTitle = (id: string) =>
    CARD_CATALOG.contact?.find((c) => c.id === id && c.area === 'left')?.title ?? id;
  /**
   * R10c: a left property card (record-tabs.js:228-237): the page's own About rows for its
   * properties (editable, hidden fields left out), and the gear for admins.
   */
  const leftPropCard = (id: string) => {
    const conf = recordLayout?.cards[id];
    const title = conf?.title || leftTitle(id);
    return (
      <CollapsibleCard
        title={title}
        cardId={id}
        defaultOpen
        action={withCardGear(null, cardView(id).onGear, title)}
      >
        <div className="crm-about-contact">
          {(conf?.props ?? presetProps(id, knownProps)).map((k) => (
            <Fragment key={k}>{aboutFieldMap[k] ?? customAbout(k)}</Fragment>
          ))}
        </div>
      </CollapsibleCard>
    );
  };
  const KNOWN_LEFT = ['about', 'groups', 'subscriptions', 'website'];
  /**
   * LD8: Function at Company and Location are on the left by default (record-layout.js:112);
   * until a layout saves their rows, they show the business's own of their properties
   * (`presetProps`), and an empty card when it has none (the user's choice).
   */
  const PRESET_LEFT = ['fncompany', 'location'];
  const extraLeft: Record<string, ReactNode> = Object.fromEntries(
    leftOrder
      .filter(
        (id) =>
          !KNOWN_LEFT.includes(id) &&
          (recordLayout?.cards[id]?.props || PRESET_LEFT.includes(baseCardId(id))),
      )
      .map((id) => [id, leftPropCard(id)]),
  );
  /**
   * R10c: a property card in a tab (record-tabs.js:217-219): its rows as label / value pairs, or a
   * data highlight's grid, with the gear.
   */
  const centerPropCard = (id: string) => {
    const conf = recordLayout?.cards[id];
    if (!conf?.props) return null;
    const title = conf.title || 'Untitled card';
    const rows = conf.props.flatMap((k) => {
      const t = propText(k);
      return t ? [{ key: k, ...t }] : [];
    });
    const highlight = cardDef(id, title, 'contact').props?.highlight;
    return (
      <section className="rt-card" data-rt-card={id}>
        <header className="rt-card__head">
          <h3>{title}</h3>
          <span className="rt-card__acts">{withCardGear(null, cardView(id).onGear, title)}</span>
        </header>
        <div className="rt-card__body">
          {highlight ? (
            <dl className="rt-hl">
              {rows.map((r) => (
                <div key={r.key}>
                  <dt>{r.label.toUpperCase()}</dt>
                  <dd>{r.value || '--'}</dd>
                </div>
              ))}
            </dl>
          ) : (
            <div className="crm-about-contact">
              {rows.map((r) => (
                <div key={r.key} className="crm-about-field rp-field">
                  <div className="crm-about-label">{r.label}</div>
                  <div className="crm-about-value">{r.value || '--'}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    );
  };
  /** R8b: the Overview tables' "+ Add" runs Review associations (record-tabs.js:940). */
  const reviewTool = tools.actions.find((x) => x.key === 'review-associations');

  /** One timeline card; `pinned` cards sit above the dated list (G8). */
  const canPin = canEdit && timelinePins.ready;
  const renderActivityCard = (item: TimelineItem, pinned: boolean) => {
    const r = readable(item, readableCtx);
    const collapsed = collapsedIds.has(item.id);
    const taskId =
      item.type === 'task' && typeof item.activityId === 'string' ? item.activityId : null;
    return (
      <article
        key={item.id}
        className={cn(
          'crm-activity-card',
          `crm-activity-card--${item.type}`,
          collapsed && 'is-collapsed',
          pinned && 'is-pinned',
        )}
      >
        {pinned ? <PinnedBadge /> : null}
        <div
          className="crm-activity-card__top"
          role="button"
          tabIndex={0}
          onClick={() => {
            setCollapsedIds((prev) => {
              const next = new Set(prev);
              if (next.has(item.id)) next.delete(item.id);
              else next.add(item.id);
              return next;
            });
          }}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              (e.currentTarget as HTMLElement).click();
            }
          }}
        >
          <div className="crm-activity-card__title">
            <svg
              className="crm-activity-card__chevron"
              viewBox="0 0 24 24"
              style={{
                width: 14,
                height: 14,
                stroke: 'currentColor',
                fill: 'none',
                strokeWidth: 2,
                marginRight: 2,
                transform: collapsed ? 'rotate(-90deg)' : undefined,
              }}
              aria-hidden
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
            <ActivityTypeIcon type={String(item.type)} />
            <strong>{r.title}</strong>
          </div>
          {canPin && isPinnable(item) ? (
            <span className="crm-pin-end">
              <TimelinePinToggle
                pinned={pinned}
                busy={timelinePins.busyId === item.id}
                onToggle={() => void timelinePins.toggle(item, pinned)}
              />
              <time dateTime={item.occurredAt}>{formatDate(item.occurredAt)}</time>
            </span>
          ) : (
            <time dateTime={item.occurredAt}>{formatDate(item.occurredAt)}</time>
          )}
        </div>
        {/* LD12: a collapsed card is its header row only, as the design (activity-tabs.css:260). */}
        {!collapsed ? (
          <>
            {r.sentence ? <p className="crm-activity-card__sentence">{r.sentence}</p> : null}
            {r.meta.length ? (
              <div className="crm-activity-card__meta">
                {r.meta.map((m) => (
                  <span key={m}>{m}</span>
                ))}
              </div>
            ) : null}
            {r.body ? <p className="crm-activity-card__description">{r.body}</p> : null}
            {timelineEditing.actions(item)}
            {taskId ? (
              <div className="crm-d-flex crm-gap-3 crm-mt-2">
                <Link className="rp-link--btn" href={`/tasks?id=${taskId}`}>
                  Edit
                </Link>
                {item.status !== 'completed' && canLog ? (
                  <button
                    type="button"
                    className="rp-link--btn"
                    onClick={() =>
                      void completeTask(taskId).then(
                        () => {
                          timelineState.updateItem(item.id, {
                            status: 'completed',
                          });
                          timelinePins.patchItem(item.id, { status: 'completed' });
                          toast('Task completed');
                        },
                        (err: unknown) => toast(errorText(err), 'danger'),
                      )
                    }
                  >
                    Complete
                  </button>
                ) : null}
              </div>
            ) : null}
          </>
        ) : null}
      </article>
    );
  };

  /* Right sidebar association cards, by layout id; a clone (`<id>~<n>`) draws as its card. */
  const openAssocHistory = (type: 'company' | 'deal') =>
    setAssocHistory({
      type,
      title: type === 'company' ? 'Company association history' : 'Deal association history',
    });
  const assocCard = (id: string, which: 'companies' | 'deals') => (
    <ContactAssociations
      contact={contact}
      contactName={name}
      canEdit={canEdit}
      onChanged={afterAssociation}
      onViewHistory={openAssocHistory}
      only={which}
      cards={{ [which]: cardView(id) }}
      dateText={cardDate}
      design
      onPreview={setPreviewTarget}
    />
  );
  const othersCard = (id: string) =>
    !deleted ? (
      <OtherContactsCard
        contactId={contact.id}
        company={primaryCompany ? { id: primaryCompany.id, name: primaryCompany.name } : null}
        canAdd={canEdit}
        onViewHistory={() =>
          setAssocHistory({ type: 'company', title: 'Company association history' })
        }
        view={cardView(id)}
        dateText={cardDate}
        onPreview={setPreviewTarget}
      />
    ) : null;
  const assocRenderers: Record<string, (id: string) => ReactNode> = {
    'r-companies': (id) => assocCard(id, 'companies'),
    'r-deals': (id) => assocCard(id, 'deals'),
    'r-others': othersCard,
  };
  const cloneCards = Object.fromEntries(
    (recordLayout?.right ?? []).flatMap((id) => {
      const make = id.includes('~') ? assocRenderers[baseCardId(id)] : undefined;
      return make ? [[id, make(id)] as const] : [];
    }),
  );

  /**
   * R10b: one middle-column card by id (record-tabs.js `CARDS`): the timeline, Emails, History,
   * the panels, and the Overview cards (R8b). Unknown ids draw nothing.
   */
  const centerCard = (id: string): ReactNode => {
    if (OVERVIEW_CARDS.includes(id)) {
      return (
        <ContactOverviewCard
          id={id}
          data={overviewData}
          highlights={overviewHighlights}
          companies={contact.companies.map((c) => ({
            id: c.id,
            name: c.name,
            href: `/companies/${c.id}`,
            values: {
              ...companyRecord(c, cardDate).values,
              // R8b: the link's real label (the design hard-codes the first row, rt.js:99).
              label: (
                <span className="rt-tag">
                  {c.isPrimary ? 'Primary' : c.labels?.map((l) => l.name).join(', ') || 'Unlabeled'}
                </span>
              ),
            },
          }))}
          deals={contact.deals.map((d) => ({
            id: d.id,
            name: d.name,
            href: `/deals/${d.id}`,
            values: dealRecord(d, cardDate).values,
          }))}
          onAddAssociation={
            reviewTool ? { onClick: reviewTool.onSelect, disabled: reviewTool.disabled } : undefined
          }
          readableCtx={readableCtx}
          onViewAll={() => setTab('activity')}
          customizeHref={
            me.permissionSet.rules.app.manage_settings
              ? '/settings/objects?object=contact&tab=record'
              : null
          }
        />
      );
    }
    switch (id) {
      case 'activities':
        return (
          <>
            <TimelineTypeTabs
              tabs={ACTIVITY_TABS}
              active={activityType}
              onChange={(next) => {
                // R1: another sub-tab empties the search, as the design (activity-tabs.js:389).
                setActivityType(next);
                setActivitySearch('');
              }}
              label="Contact activity types"
              keys
            />
            {activityLoading ? <p className="crm-activity-empty">Loading…</p> : null}
            {activityError ? <Alert tone="danger">{activityError}</Alert> : null}
            {!activityLoading ? (
              <>
                <div className="crm-activity-toolbar">
                  <div className="crm-activity-search">
                    <SearchIcon />
                    <input
                      type="search"
                      placeholder={activityTabSearchPlaceholder(activityType)}
                      value={activitySearch}
                      onChange={(e) => setActivitySearch(e.target.value)}
                      aria-label={activityTabSearchPlaceholder(activityType)}
                    />
                  </div>
                  <div className="crm-activity-toolbar__actions">
                    {/* R5b: the design's "Expand all ▾" menu (raf.js:92, :208-213). */}
                    <TimelineExpandMenu
                      onCollapseAll={() =>
                        setCollapsedIds(
                          new Set([
                            ...shownPins.map((p) => p.itemId),
                            ...filteredTimeline.map((i) => i.id),
                          ]),
                        )
                      }
                      onExpandAll={() => setCollapsedIds(new Set())}
                    />
                  </div>
                </div>

                {/* R5b: the design's filter row under the search (raf.js:93-114). */}
                <TimelineFilterChips
                  types={chosenTypes}
                  onTypes={setActivityTypes}
                  date={activityDate}
                  from={activityFrom}
                  to={activityTo}
                  onDate={(d, f, t) => {
                    setActivityDate(d);
                    setActivityFrom(f);
                    setActivityTo(t);
                  }}
                  userIds={activityUserIds}
                  onUsers={setActivityUserIds}
                  owners={owners}
                  meId={me.user.id}
                  teamIds={activityTeamIds}
                  onTeams={setActivityTeamIds}
                  teams={teamOptions}
                  sort={activitySort}
                  onSort={setActivitySort}
                  onClearAll={clearActivityFilters}
                />

                <div className="crm-activity-actions">
                  <span className="crm-activity-actions__spacer" />
                  {activityLog ? (
                    <ActivityTabAddButton
                      kind={activityLog.kind === 'log-email' ? 'email' : 'meeting'}
                      label={activityLog.label}
                      disabled={!canLog}
                      title={logTitle}
                      onClick={() => setDrawer(activityLog.kind)}
                    />
                  ) : null}
                  {activityAdd ? (
                    <ActivityTabAddButton
                      kind={activityAdd.kind}
                      label={activityAdd.label}
                      disabled={!canLog}
                      title={logTitle}
                      onClick={() => setDrawer(activityAdd.kind)}
                    />
                  ) : null}
                  {activityAdd?.kind === 'call' ? (
                    <ActivityTabAddButton
                      kind="call"
                      label="Make a phone call"
                      disabled={!canLog}
                      title={logTitle}
                      onClick={() => setDrawer('dial')}
                    />
                  ) : null}
                </div>

                {timelinePins.failed ? <PinsLoadError /> : null}
                {shownPins.length ? (
                  <div className="crm-activity-list crm-pins-list">
                    {shownPins.map((p) => renderActivityCard(p.item, true))}
                  </div>
                ) : null}
                {activityByMonth.length === 0 && shownPins.length === 0 ? (
                  <TimelineEmpty
                    what={
                      activityType === 'all'
                        ? 'activities'
                        : (ACTIVITY_TABS.find((t) => t.key === activityType)?.label.toLowerCase() ??
                          'activities')
                    }
                    record={contact ? contactDisplayName(contact) : ''}
                    filtered={activityFiltered}
                    canCreate={Boolean(activityAdd || activityLog)}
                  />
                ) : activityByMonth.length ? (
                  <div className="crm-activity-list">
                    {activityByMonth.map(([month, items]) => (
                      <div key={month} className="crm-activity-month-group">
                        <div className="crm-activity-month">{month}</div>
                        {items.map((item) => renderActivityCard(item, false))}
                      </div>
                    ))}
                  </div>
                ) : null}
                <TimelineLoadMore
                  hasMore={!noTypes && timelineState.hasMore}
                  loading={timelineState.loadingMore}
                  onLoadMore={() => void timelineState.loadMore()}
                />
              </>
            ) : null}
          </>
        );
      case 'salesnav':
        return (
          <ComingSoonPanel
            title="LinkedIn Sales Navigator"
            text={`See ${name}'s LinkedIn profile, shared connections and InMail here once Sales Navigator is connected.`}
          />
        );
      case 'docusign':
        return (
          <ComingSoonPanel
            title="DocuSign"
            text="Send documents for signature and track their status from this record once DocuSign is connected."
          />
        );
      default:
        return centerPropCard(id);
    }
  };
  /**
   * R10b: the open tab's items as the page draws them (record-tabs.js:872-886): sections open and
   * close the cards after them; the Overview cards sit in `.rp-overview` (their styles), as before.
   */
  const closedHere = new Set(
    [...closedSecs]
      .filter((k) => k.startsWith(`${openTabId}|`))
      .map((k) => Number(k.split('|')[1])),
  );
  // R10d: the open tab's cards that its conditional logic hides aren't drawn (record-tabs.js:215).
  const shownItems = currentItems.filter((id) => isSection(id) || condShows(`${openTabId}|${id}`));
  const groups = tabGroups(shownItems, closedHere, (id) =>
    OVERVIEW_CARDS.includes(id) || recordLayout?.cards[id]?.props
      ? 'overview'
      : PLAIN_CARDS.has(id)
        ? 'plain'
        : null,
  );
  // R10d: a hidden tab stays in the bar; its body says so (record-tabs.js:145, :876).
  const centerBody: ReactNode = !condShows(`tab|${openTabId}`) ? (
    <div className="rp-overview rt-panel">
      <div className="rt-empty">
        <svg className="rt-emptyart" viewBox="0 0 120 90" aria-hidden="true">
          <ellipse cx="60" cy="78" rx="34" ry="8" fill="#eef1f5" />
          <circle cx="54" cy="34" r="18" fill="#fff" stroke="#b9c0cc" strokeWidth="3" />
          <path d="m67 47 14 14" stroke="#b9c0cc" strokeWidth="5" strokeLinecap="round" />
        </svg>
        <span>Cards in this tab are hidden due to conditional logic.</span>
      </div>
    </div>
  ) : groups.length ? (
    groups.map((g) => {
      const inner = g.entries.map((e) =>
        isSection(e.id) ? (
          <TabSection
            key={`sec-${e.index}`}
            name={sectionName(e.id)}
            open={!closedHere.has(e.index)}
            className="rt-section company-about-section"
            onToggle={() =>
              setClosedSecs((cur) => {
                const k = `${openTabId}|${e.index}`;
                const next = new Set(cur);
                if (next.has(k)) next.delete(k);
                else next.add(k);
                return next;
              })
            }
          />
        ) : (
          <Fragment key={`${e.id}-${e.index}`}>{centerCard(e.id)}</Fragment>
        ),
      );
      const key = `g-${g.entries[0]!.index}`;
      return g.family === 'overview' ? (
        <section key={key} className="rp-overview rt-panel" aria-label="Overview">
          {inner}
        </section>
      ) : (
        <Fragment key={key}>{inner}</Fragment>
      );
    })
  ) : (
    <p className="crm-activity-empty">No cards in this tab yet.</p>
  );

  return (
    <div className="crm-contact-layout">
      {deleted ? (
        <div className="crm-p-3">
          <Alert tone="warning">
            This contact was deleted.{' '}
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={onRestore}
              disabled={restoring}
              aria-busy={restoring}
            >
              {restoring ? 'Restoring…' : 'Restore'}
            </button>
          </Alert>
        </div>
      ) : null}
      <div className="crm-contact-layout__row">
        {/* LEFT */}
        <aside className="crm-contact-layout__left" ref={leftColumnRef}>
          {/* R4: the compact header once the quick actions scroll away (record-page.js:102-126). */}
          {!deleted ? (
            <RecordStickyHeader
              watchRef={quickRowRef}
              columnRef={leftColumnRef}
              backHref="/contacts"
              backLabel={names.plural}
              actions={actions}
              avatar={<Avatar name={name} size="xs" />}
              name={name}
              activities={stickyActivities}
            />
          ) : null}
          {/* R4: left cards start collapsed on phones (record-tabs.js:250-251). */}
          <CardMemory.Provider value={LEFT_CARD_MEMORY}>
            <div className="crm-sidebar-cards">
              <section className="crm-contact-profile-card">
                <div className="crm-contact-profile">
                  <div className="crm-contact-profile__top">
                    {/* R1: one link holding the chevron and the plural (record-ui.php:231-234). */}
                    <Link
                      className="crm-contact-profile__back crm-contact-profile__back--text"
                      href="/contacts"
                    >
                      <BackIcon />
                      <span className="crm-contact-profile__section-title">{names.plural}</span>
                    </Link>
                    {/* R2: no search box, the design's keys (record-ui.php:125, record-actions.js). */}
                    <ContactActionsMenu
                      actions={actions}
                      disabled={deleted}
                      showSearch={false}
                      keyboard
                    />
                  </div>

                  <div className="crm-contact-profile__info">
                    <div className="crm-contact-profile__identity crm-mt-3">
                      <Avatar name={name} size="lg" />
                      <div>
                        {/* LD3: the name as text, its pencil and popover (record-page.js:128-254). */}
                        <div className="rp-namerow">
                          <ContactNameHeading>{name}</ContactNameHeading>
                          <RecordNamePopover
                            object="contact"
                            recordName={name}
                            fields={nameFields}
                            disabledTitle={canEdit ? undefined : editTitle}
                            onSave={saveNameField}
                            onDetails={() => setPropsOpen(true)}
                          />
                        </div>
                      </div>
                    </div>

                    {designation ? (
                      <div className="crm-contact-profile__designation">{designation}</div>
                    ) : null}

                    {contact.email ? (
                      <div className="crm-contact-profile__email">
                        {/* R1: link, open, copy, as the design (record.php:396-400, record-page.js:379-382). */}
                        <a href={`mailto:${contact.email}`}>{contact.email}</a>
                        <a
                          className="crm-contact-profile__open"
                          href={`mailto:${contact.email}`}
                          aria-label={`Open ${contact.email}`}
                          title={`Open ${contact.email}`}
                        >
                          <ExternalLinkIcon />
                        </a>
                        <button
                          type="button"
                          className="crm-copy-btn"
                          aria-label="Copy email"
                          title="Copy email"
                          onClick={() => {
                            const email = contact.email ?? '';
                            void navigator.clipboard
                              .writeText(email)
                              .then(() => toast(`Copied ${email}`))
                              .catch(() => toast('Copy failed', 'danger'));
                          }}
                        >
                          <CopyIcon />
                        </button>
                      </div>
                    ) : null}
                  </div>

                  <div className="crm-contact-profile__quick-actions" ref={quickRowRef}>
                    {quickActions.map((a) => (
                      <button
                        key={a.key}
                        type="button"
                        title={logTitle ?? a.title}
                        disabled={!canLog}
                        onClick={() => setDrawer(a.key)}
                      >
                        <span className="crm-contact-profile__action-icon">{a.icon}</span>
                        <span>{a.label}</span>
                      </button>
                    ))}
                    {/* R2: More holds activities only (record-popups-hs.js:1032-1067). */}
                    <ActivitiesMoreMenu
                      items={moreItems}
                      onReorder={() => setPrefsDialog('buttons')}
                      disabled={deleted}
                    >
                      <span className="crm-contact-profile__action-icon">
                        <MoreActionIcon />
                      </span>
                      <span>More</span>
                    </ActivitiesMoreMenu>
                  </div>
                </div>
              </section>

              {/* HUB-381: left sidebar cards in the order of the record layout. */}
              {orderedCards(
                leftOrder.filter((id) => id === 'about' || condShows(`left|${id}`)),
                {
                  // R10c: property cards the layout adds (Function at Company, Location, created).
                  ...extraLeft,
                  about: (
                    <>
                      <CollapsibleCard
                        title={recordLayout?.cards.about?.title || 'About this contact'}
                        cardId="about"
                        defaultOpen
                        action={withCardGear(
                          !deleted ? (
                            <ContactActionsMenu
                              actions={aboutActions}
                              showSearch={false}
                              triggerClassName="crm-collapsible-card__action"
                              keyboard
                            />
                          ) : undefined,
                          // R10c: the gear on left property cards (record-tabs.js:236).
                          cardView('about').onGear,
                          'About this contact',
                        )}
                      >
                        <div className="crm-about-contact">{aboutFields}</div>
                      </CollapsibleCard>
                    </>
                  ),
                  groups: (
                    <>
                      <PropertyGroupCards
                        objectType="contact"
                        defs={customDefs}
                        values={contact.customProperties}
                        builtIns={{
                          lifecycleStage: contact.lifecycleStage,
                          leadStatus: contact.leadStatus,
                        }}
                        edit={{
                          canEdit,
                          lockedTitle: editTitle,
                          timeZone: prefs.timeZone,
                          formatDateTime: formatDate,
                          onSave: (name, value) =>
                            saveContact({ customProperties: { [name]: value } }),
                        }}
                        onHistory={(field) => setHistoryField(customHistoryField(field))}
                      />
                    </>
                  ),
                  /* R1: subscriptions before website when no layout is saved, as the design's
                 default left list (record-layout.js:112). */
                  subscriptions: (
                    <>
                      {/* HUB-321: the contact's choice per subscription type. */}
                      {!deleted ? (
                        <ContactSubscriptionsCard contactId={contact.id} canEdit={canEdit} />
                      ) : null}
                    </>
                  ),
                  website: (
                    <>
                      {/* HUB-466: visits and page views from the website tracking code. */}
                      {!deleted ? (
                        <WebsiteActivityCard
                          contactId={contact.id}
                          region={prefs.regionFormat}
                          timeZone={prefs.timeZone}
                        />
                      ) : null}
                    </>
                  ),
                },
              )}
            </div>
          </CardMemory.Provider>
        </aside>

        {/* CENTER */}
        <main className="crm-contact-layout__center">
          <div className="crm-center-panel">
            <RecordTabBar
              label="Contact sections"
              tabs={centerTabs.map(([key, label]) => ({ key, label }))}
              active={tab}
              onSelect={setTab}
              fit
              allTabs
              customizeHref={
                me.permissionSet.rules.app.manage_settings
                  ? '/settings/objects?object=contact&tab=record'
                  : null
              }
            />

            <div className="crm-center-content">
              {deleted ? (
                tab === 'overview' ? (
                  <div className="crm-about-contact">{aboutFields}</div>
                ) : (
                  <div className="crm-activity-empty">
                    <p>This contact is deleted</p>
                    <p>Restore it to see its activity, emails and history.</p>
                  </div>
                )
              ) : (
                centerBody
              )}
            </div>
          </div>
        </main>

        {/* RIGHT */}
        <aside className="crm-contact-layout__right">
          {/* R4: right cards remember being collapsed, per viewer (record-tabs.js:262-264). */}
          <CardMemory.Provider value={CONTACT_RIGHT_MEMORY}>
            <div className="crm-sidebar-cards">
              {/* HUB-381: right sidebar cards in the order of the record layout. */}
              {orderedCards(
                recordLayout?.right?.filter((id) => condShows(`right|${id}`)),
                {
                  'r-companies': assocCard('r-companies', 'companies'),
                  // R6b: Playbooks third, in the layout, as the design (record-layout.js:120).
                  // PB8: only with the "Playbooks" permission.
                  playbooks: canUsePlaybooks(me) ? <PlaybooksCard run={playbookRun} /> : null,
                  'r-deals': assocCard('r-deals', 'deals'),
                  // HUB-617: the primary company's other contacts.
                  'r-others': othersCard('r-others'),
                  ...cloneCards,
                  'r-related': (
                    <>
                      {/* Other contacts linked to this one (HUB-574). */}
                      <RelatedRecordsCard
                        type="contact"
                        recordId={contact.id}
                        recordName={name}
                        canEdit={canEdit}
                        view={cardView('r-related')}
                      />
                    </>
                  ),
                  'r-objects': (
                    <>
                      {/* Events, Leads, Tickets and other custom objects linked to the contact (HUB-269). */}
                      <LinkedObjectCards
                        anchorType="contact"
                        variant="contact"
                        anchorId={contact.id}
                        anchorName={name}
                        canEdit={canEdit}
                        designEmpty
                        onViewHistory={(key, plural) =>
                          setAssocHistory({ type: key, title: `${plural} association history` })
                        }
                        cardView={(key) => cardView(`object-${key}`)}
                      />
                    </>
                  ),
                  sequences: (
                    <>
                      <CollapsibleCard title="Sequences" cardId="sequences" defaultOpen>
                        {!canUseSequences ? (
                          <p className="crm-text-body-secondary crm-fs-7">
                            Your permissions do not allow using sequences.
                          </p>
                        ) : (
                          <div className="crm-d-grid crm-gap-3 rp-seq-enroll">
                            <div className="field crm-mb-0">
                              <label className="field__label" htmlFor="contactSequenceSelect">
                                Sequence
                              </label>
                              <select
                                id="contactSequenceSelect"
                                className="select"
                                value={selectedSequenceId}
                                onChange={(e) => setSelectedSequenceId(e.target.value)}
                              >
                                <option value="">Select sequence</option>
                                {sequenceChoices.map((sequence) => (
                                  <option key={sequence.id} value={sequence.id}>
                                    {sequence.name}
                                  </option>
                                ))}
                              </select>
                              {!enrollmentsLoading && sequenceChoices.length === 0 ? (
                                <span className="crm-fs-8 crm-text-muted">
                                  No active sequences yet.{' '}
                                  <Link className="link" href="/sequences">
                                    Create and activate one
                                  </Link>
                                  .
                                </span>
                              ) : null}
                            </div>

                            {/* Sequences QA BUG-04: a long name ends in an ellipsis inside the
                                card (full text in the title), so the column and the note below
                                keep the card's width. */}
                            <button
                              type="button"
                              className="btn-crm btn-crm--primary crm-text-truncate"
                              title={`Enroll in ${selectedSequence ? selectedSequence.name : 'sequence'}…`}
                              disabled={
                                !selectedSequenceId || !mailboxReady || !mailboxId || deleted
                              }
                              onClick={onEnrollInSequence}
                            >
                              <span className="crm-text-truncate">
                                Enroll in {selectedSequence ? selectedSequence.name : 'sequence'}…
                              </span>
                            </button>

                            {!mailboxReady ? (
                              <p className="crm-text-body-secondary crm-fs-8 crm-mb-0">
                                Connect your mailbox in Settings &gt; Email before enrolling
                                contacts.
                              </p>
                            ) : null}

                            <div className="crm-d-grid crm-gap-2">
                              <div className="crm-fs-7 crm-text-body-secondary">
                                Current enrollments (
                                {enrollments.filter(isCurrentEnrollment).length})
                              </div>
                              {enrollmentsLoading ? (
                                <p className="crm-text-body-secondary crm-fs-8 crm-mb-0">
                                  Loading…
                                </p>
                              ) : enrollments.length === 0 ? (
                                <p className="crm-text-body-secondary crm-fs-8 crm-mb-0">
                                  No sequence enrollments yet.
                                </p>
                              ) : (
                                [
                                  ...enrollments.filter(isCurrentEnrollment),
                                  ...enrollments.filter((row) => !isCurrentEnrollment(row)),
                                ].map((row, index, all) => {
                                  const busy = busyEnrollmentId === row.id;
                                  const canPause = row.status === 'active';
                                  const canResume = row.status === 'paused';
                                  const canStop =
                                    row.status === 'active' || row.status === 'paused';

                                  // The ended ones under their own heading, after the current ones.
                                  const firstPast =
                                    !isCurrentEnrollment(row) &&
                                    (index === 0 || isCurrentEnrollment(all[index - 1]!));
                                  return (
                                    <Fragment key={row.id}>
                                      {firstPast ? (
                                        <div className="crm-fs-7 crm-text-body-secondary crm-mt-2">
                                          Past enrollments (
                                          {
                                            enrollments.filter((r) => !isCurrentEnrollment(r))
                                              .length
                                          }
                                          )
                                        </div>
                                      ) : null}
                                      <div className="card crm-p-2 crm-d-grid crm-gap-2">
                                        <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-2">
                                          <div className="crm-fs-7 crm-fw-semibold">
                                            {row.sequenceName}
                                          </div>
                                          <span className={enrollmentStatusClass(row.status)}>
                                            {enrollmentStatusLabel(row)}
                                          </span>
                                        </div>
                                        <div className="crm-fs-8 crm-text-body-secondary">
                                          {isCurrentEnrollment(row)
                                            ? row.waitingOnTask
                                              ? 'Next step: when the task is done'
                                              : `Next step: ${formatDate(row.nextRunAt)}`
                                            : `Ended: ${formatDate(row.endedAt)}`}
                                        </div>
                                        <div className="crm-d-flex crm-gap-2 crm-flex-wrap">
                                          {canPause ? (
                                            <button
                                              type="button"
                                              className="btn-crm btn-crm--outline btn-crm--sm"
                                              disabled={busy}
                                              onClick={() => void onEnrollmentAction(row, 'pause')}
                                            >
                                              Pause
                                            </button>
                                          ) : null}
                                          {canResume ? (
                                            <button
                                              type="button"
                                              className="btn-crm btn-crm--outline btn-crm--sm"
                                              disabled={busy}
                                              onClick={() => void onEnrollmentAction(row, 'resume')}
                                            >
                                              Resume
                                            </button>
                                          ) : null}
                                          {canStop ? (
                                            <button
                                              type="button"
                                              className="btn-crm btn-crm--outline btn-crm--sm"
                                              disabled={busy}
                                              onClick={() => void onEnrollmentAction(row, 'stop')}
                                            >
                                              Unenroll
                                            </button>
                                          ) : null}
                                        </div>
                                      </div>
                                    </Fragment>
                                  );
                                })
                              )}
                            </div>
                          </div>
                        )}
                      </CollapsibleCard>
                    </>
                  ),
                  tasks: (
                    <>
                      {!deleted ? (
                        <RecordTasksCard
                          linkedType="contact"
                          linkedId={contact.id}
                          timeZone={prefs.timeZone}
                          refreshKey={refreshKey}
                          canAdd={canLog}
                          canComplete={canLog}
                          onAdd={() => setDrawer('task')}
                        />
                      ) : null}
                    </>
                  ),
                  attachments: (
                    <>
                      {!deleted ? (
                        <AttachmentsSidebarCard
                          link={{ type: 'contact', id: contact.id }}
                          canEdit={canEdit}
                          refreshKey={refreshKey}
                          designAdd
                        />
                      ) : null}
                    </>
                  ),
                  // LR2: the design's Lead stage tracker (record-tabs.js:469-490, live design),
                  // open by default (record-tabs.js:263): one block per lead (user, 25 Nov).
                  // A conversion reloads the contact quietly, so the Deals card shows the deal.
                  'r-leadstage': (
                    <>
                      {!deleted ? (
                        <ContactLeadStageCard
                          contactId={contact.id}
                          onConverted={afterAssociation}
                        />
                      ) : null}
                    </>
                  ),
                  // R6b: the design's contact Quotes card, after Attachments (record-layout.js:120).
                  quotes: (
                    <>
                      {!deleted ? (
                        <RecordQuotesCard
                          anchor={{ type: 'contact', id: contact.id }}
                          canAdd={canLog}
                        />
                      ) : null}
                    </>
                  ),
                },
              )}
            </div>
          </CardMemory.Provider>
        </aside>
      </div>

      {/* ------------------------------------------------------ actions */}
      <EditContactDrawer
        open={drawer === 'edit'}
        onClose={closeDrawer}
        contact={contact}
        lifecycleStages={activeOptions(contactPicklists, 'lifecycleStage')}
        leadStatuses={activeOptions(contactPicklists, 'leadStatus')}
        customDefs={customDefs}
        timeZone={prefs.timeZone}
        onSaved={setContact}
      />
      {timelineEditing.dialogs}
      <LogNoteDrawer
        composer={composer}
        open={drawer === 'note'}
        onClose={closeDrawer}
        link={{ type: 'contact', id: contact.id }}
        recordName={name}
        recordSecondary={contact.email}
        initialAssociations={noteAssociations}
        onLogged={() => afterActivity()}
      />
      <LogCallDrawer
        composer={composer}
        open={drawer === 'call' || drawer === 'dial'}
        dial={drawer === 'dial' ? { name, phone: contact.phone ?? null } : null}
        onClose={closeDrawer}
        link={{ type: 'contact', id: contact.id }}
        recordName={name}
        recordSecondary={contact.email}
        initialAssociations={noteAssociations}
        outcomes={activeOptions(activityPicklists, 'callOutcome')}
        timeZone={prefs.timeZone}
        onLogged={() => afterActivity()}
        callFields
      />
      <LogCommunicationDrawer
        open={drawer === 'communication'}
        onClose={closeDrawer}
        link={{ type: 'contact', id: contact.id }}
        recordName={name}
        timeZone={prefs.timeZone}
        onLogged={() => afterActivity()}
        channel={commChannel}
      />
      <LogPostalMailDrawer
        open={drawer === 'postal-mail'}
        onClose={closeDrawer}
        link={{ type: 'contact', id: contact.id }}
        recordName={name}
        timeZone={prefs.timeZone}
        onLogged={() => afterActivity()}
      />
      <CreateTaskDrawer
        composer={composer}
        open={drawer === 'task'}
        onClose={closeDrawer}
        link={{ objectType: 'contact', id: contact.id }}
        recordName={name}
        // LD10 (CT-26): the same default links as Note and Call (activity-composer.js:354-366).
        initialAssociations={noteAssociations}
        taskTypes={activeOptions(activityPicklists, 'taskType')}
        timeZone={prefs.timeZone}
        onCreated={() => afterActivity()}
      />
      <ScheduleMeetingDrawer
        // One window for both: going from one to the other must start clean.
        key={drawer === 'log-meeting' ? 'log-meeting' : 'meeting'}
        composer={composer}
        open={drawer === 'meeting' || drawer === 'log-meeting'}
        onClose={closeDrawer}
        link={{ type: 'contact', id: contact.id }}
        recordName={name}
        defaultAttendeeEmail={contact.email}
        attendeeOptions={
          contact.email
            ? [
                {
                  value: contact.email.trim().toLowerCase(),
                  label: `${name} (${contact.email.trim().toLowerCase()})`,
                },
              ]
            : []
        }
        timeZone={prefs.timeZone}
        defaultMinutes={prefs.meetingMinutes}
        defaultAddToCalendar={drawer === 'meeting'}
        onScheduled={() => afterActivity(true)}
      />
      <LogEmailDrawer
        composer={composer}
        open={drawer === 'log-email'}
        onClose={closeDrawer}
        link={{ type: 'contact', id: contact.id }}
        recordName={name}
        recordSecondary={contact.email}
        onLogged={() => afterActivity()}
      />
      <SendEmailDrawer
        composer={composer}
        open={drawer === 'email'}
        onClose={closeDrawer}
        contactId={contact.id}
        contactEmail={contact.email}
        recipientOptions={
          contact.email
            ? [
                {
                  value: contact.email.trim().toLowerCase(),
                  label: `${name} (${contact.email.trim().toLowerCase()})`,
                  contactId: contact.id,
                },
              ]
            : []
        }
        dealId={contact.deals[0]?.id}
        recordLink={{ type: 'contact', id: contact.id }}
        recordName={name}
        signature={prefs.signature}
        onSent={() => afterActivity()}
      />
      {/* SEQ-R-B4: the card, More > Enroll and the sequence's own Enroll share one review. */}
      <EnrollPreviewDialog
        open={enrollOpen}
        onClose={() => setEnrollOpen(false)}
        sequence={selectedSequence}
        contact={{ id: contact.id, name, email: contact.email }}
        sender={sequenceSender}
        onEnrolled={() => void loadSequenceData()}
      />
      {enrollmentConfirmDialog}
      <EnrollSequenceDialog
        open={enrollDialogOpen}
        onClose={closeEnrollDialog}
        sequences={sequenceChoices}
        load={enrollmentsLoading ? 'loading' : sequencesFailed ? 'failed' : 'ready'}
        contactId={contact.id}
        contactName={name}
        contactEmail={contact.email}
        sender={sequenceSender}
        formatDate={(iso) => formatUserDate(iso, datePrefs)}
        onEnrolled={() => void loadSequenceData()}
      />
      <CommerceCreateDialog
        kind={commerceKind}
        recordName={name}
        companyName={primaryCompany?.name ?? null}
        onClose={closeCommerce}
      />
      {tools.drawers}
      <AssociationHistoryDrawer
        open={assocHistory !== null}
        onClose={() => setAssocHistory(null)}
        recordType="contact"
        recordId={contact.id}
        otherType={assocHistory?.type}
        title={assocHistory?.title ?? 'Association history'}
        timeZone={prefs.timeZone}
      />
      {/* R7: a sidebar row's Preview (record-tabs.js:659-780). */}
      <AssociatedPreview
        target={previewTarget}
        onClose={() => setPreviewTarget(null)}
        onChanged={() => void afterAssociation()}
      />
      {/* R3: View all properties as the design's drawer (record-tabs.js:614-649). */}
      <AllPropertiesDesignDrawer
        open={propsOpen}
        onClose={() => setPropsOpen(false)}
        name={name}
        rows={propertyRows}
        groupOrder={contactGroups.order}
        manageHref={propertySettingsHref(me, 'contact')}
        docHref={canEditPropertySettings(me) ? '/settings/properties?object=contact' : null}
      />
      {/* R2: Clone as the design's form (record-popups-hs.js:564-594). */}
      <CloneRecordDrawer
        open={cloneOpen}
        title={`Clone ${names.singular}`}
        fields={[
          { name: 'email', label: 'Email', required: true, type: 'email' },
          { name: 'firstName', label: 'First name', required: true },
          { name: 'lastName', label: 'Last name', required: true },
          { name: 'companyName', label: 'Company name', required: true },
          { name: 'jobTitle', label: 'Job title' },
          { name: 'phone', label: 'Phone number', type: 'tel' },
        ]}
        initial={{
          email: '',
          firstName: contact.firstName ?? '',
          lastName: `${contact.lastName ?? ''} (clone)`.trim(),
          companyName: contactCompanyText(contact),
          jobTitle: contact.jobTitle ?? '',
          phone: contact.phone ?? '',
        }}
        editFormHref={isAdmin ? '/create-form-editor?object=contact' : undefined}
        onClose={() => setCloneOpen(false)}
        onClone={cloneContact}
      />
      <ButtonOrderDialog
        open={prefsDialog === 'buttons'}
        order={order}
        onClose={() => setPrefsDialog(null)}
        onSaved={setButtonOrder}
      />
      <ActivityDisplayDialog
        open={prefsDialog === 'display'}
        types={defaultTypes ?? null}
        onClose={() => setPrefsDialog(null)}
        onSaved={setDisplayTypes}
      />
      <MergeDesignDialog
        open={mergeOpen}
        objectType="contact"
        record={{ id: contact.id, label: name, secondary: contact.email }}
        onClose={() => setMergeOpen(false)}
        timeZone={prefs.timeZone}
      />
      <PropertyHistoryDrawer
        open={historyField !== null}
        onClose={() => setHistoryField(null)}
        load={(params) => getContactHistory(contact.id, params)}
        describe={describeHistory}
        initialField={historyField ?? 'all'}
        reloadKey={contact.updatedAt}
        timeZone={prefs.timeZone}
        design={{
          recordName: name,
          objectType: 'contact',
          canManageProperties: canOpenPropertySettings(me),
        }}
      />
      <DeleteContactDialog
        open={drawer === 'delete'}
        onClose={closeDrawer}
        contactId={contact.id}
        contactName={name}
        onDeleted={() => {
          setDrawer(null);
          router.push('/contacts');
        }}
      />
    </div>
  );
}
