'use client';

import {
  propertyLogicState,
  propertyLogicValues,
  usePropertyLogic,
} from '@/features/custom-properties/logic';
import {
  useClosedLostReason,
  attachContract,
  useClosedWonReason,
  type LostAnswer,
  type WonAnswerWithContract,
} from '@/features/deals/ui/actions/ClosedLostDialog';
import { MergeDesignDialog } from '@/features/duplicates/design/MergeDesignDialog';
import { EventReviewAssociations } from '@/features/objects/record/ui/EventReviewAssociations';
import { DealLineItemsCard } from '@/features/products/ui/DealLineItemsCard';
import {
  ComingSoonPanel,
  PlaybooksCard,
  RecordTabBar,
  type PlaybookRunContext,
  SampleCard,
} from '@/features/record-pages/RecordTabs';
import { scopeCovers } from '@/features/auth/record-access';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Fragment, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import type { CommunicationChannel } from '@/features/activities/api.client';
import { cloneLocked } from '@/features/companies/clone';
import {
  BUTTON_LABELS,
  BUTTON_TITLES,
  ButtonOrderDialog,
  fullOrder,
} from '@/features/contacts/ui/record/RecordPrefsDialogs';
import {
  cloneDealBody,
  cloneDealOwnerId,
  dealNameFields,
  dealNameSave,
} from '@/features/deals/record/dealHeader';
import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import { ActivitiesMoreMenu } from '@/features/record-pages/ActivitiesMoreMenu';
import {
  COMMERCE,
  COMMERCE_KINDS,
  CommerceCreateDialog,
  type CommerceKind,
} from '@/features/record-pages/CommerceCreateDialog';
import { MoreMenuIcon, type MoreMenuIconName } from '@/features/record-pages/MoreMenuIcon';
import { RecordNamePopover } from '@/features/record-pages/RecordNamePopover';
import { RecordStickyHeader } from '@/features/record-pages/RecordStickyHeader';
import { useNarrowRightCollapse } from '@/features/record-pages/useNarrowRightCollapse';
import { CloneRecordDrawer } from '@/features/record-tools/ui/CloneRecordDrawer';
import type { RecordActionButton } from '@/features/settings/types';
import { ABOUT_FIELDS, useMyRecordLayout } from '@/features/record-layouts/api.client';
import type { CustomProperties } from '@/types/api';
import { cardDef, listMode } from '@/features/record-layouts/cardSettings';
import { condOk } from '@/features/record-layouts/cond';
import { editorViewParam, recordEditorHref } from '@/features/record-layouts/editorLinks';
import { isSection, sectionName, TabSection, tabGroups } from '@/features/record-layouts/tabItems';
import { canEditCards, withCardGear } from '@/features/record-layouts/ui/CardGear';
import {
  dealAboutKeys,
  dealAreaCards,
  dealCompany,
  dealCondValue,
  dealHighlightText,
  dealOpenTab,
  dealTabItems,
  dealTabs,
  dealTexts,
} from '@/features/deals/record/dealLayout';
import { Alert } from '@/components/crm/Alert';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { canUsePlaybooks } from '@/features/playbooks/access';
import { LinkedObjectCards } from '@/features/objects/ui/LinkedObjectCards';
import { ownerLabelFromCache } from '@/features/owners/labels';
import { useOwners } from '@/features/owners/useOwners';
import { useAccountCurrencies } from '@/features/settings/currencies';
import type { ActivityLink } from '@/features/activities/api.client';
import {
  BLANK,
  MEANINGFUL_FIELDS,
  readable,
  type ReadableContext,
  type ReadableItem,
} from '@/features/activities/readable';
import { useUserDates } from '@/features/activities/useUserDates';
import { useTimelineEditing } from '@/features/activities/ui/TimelineActivityEditing';
import {
  ActivityTabAddButton,
  ActivityTypeIcon,
  activityTabAddAction,
  activityTabLogAction,
  activityTabSearchPlaceholder,
  TimelineLoadMore,
  TimelineTypeTabs,
} from '@/features/activities/ui/TimelineControls';
import {
  ALL_TIMELINE_TYPES,
  timelineServerFilters,
  type TimelineDateFilter,
} from '@/features/activities/timelineFilters';
import {
  TimelineEmpty,
  TimelineExpandMenu,
  TimelineFilterChips,
} from '@/features/activities/ui/TimelineFilterChips';
import { dealChosenTypes, dealTimelineTypes } from '@/features/deals/record/dealActivity';
import { dealTableRows, useDealTables } from '@/features/deals/record/dealTables';
import {
  ContactOverviewCard,
  useContactOverviewData,
  type OverviewTimeline,
} from '@/features/contacts/ui/record/ContactOverview';
import { listTeamOptions } from '@/features/members/api.client';
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 { CardMemory } from '@/features/contacts/ui/CollapsibleCard';
import { DealAssociationCard } from '@/features/deals/ui/DealAssociations';
import { AssociatedPreview, type PreviewTarget } from '@/features/record-pages/AssociatedPreview';
import type { CardView } from '@/features/record-layouts/ui/AssocLines';
import {
  changeDealStage,
  createDeal,
  getDeal,
  getDealHistory,
  getDealStageHistory,
  getDealTimeline,
  listPipelines,
  restoreDeal,
  updateDeal,
} from '@/features/deals/api.client';
import type {
  Deal,
  DealPriority,
  Pipeline,
  PipelineStage,
  StageHistoryEntry,
  TimelineItem,
  UpdateDealBody,
} from '@/features/deals/types';
import { DeleteDealDialog } from '@/features/deals/ui/actions/DeleteDealDialog';
import {
  AllPropertiesDesignDrawer,
  type PropertyRow,
} from '@/features/record-tools/ui/AllPropertiesDesign';
import { ownerLock } from '@/features/record-tools/recordAccessView';
import {
  canEditPropertySettings,
  canOpenPropertySettings,
  propertySettingsHref,
} from '@/features/permission-sets/property-settings';
import { usePickerGroups } from '@/features/list-page/propertyGroups';
import { CustomFieldsList } from '@/features/contacts/ui/actions/custom-fields';
import { EditDealDrawer } from '@/features/deals/ui/actions/EditDealDrawer';
import { MoveDealPipelineDrawer } from '@/features/deals/ui/actions/MoveDealPipelineDrawer';
import { DealStageBar, stageBarSteps } from '@/features/deals/ui/DealStageBar';
import {
  aboutStageChoices,
  isClosedStage,
  reopenConfirm,
  reopensDeal,
} from '@/features/deals/stageMove';
import { useConfirm } from '@/components/crm/useConfirm';
import { recordMoney } from '@/features/list-page/money';
import { requiredNames, stageRequirementsOf } from '@/features/pipelines/stageRules';
import { useDealStageGate } from '@/features/pipelines/ui/useStageGate';
import {
  ContactActionsMenu,
  type ContactAction,
} from '@/features/contacts/ui/actions/ContactActionsMenu';
import { CreateTaskDrawer } from '@/features/tasks/ui/CreateTaskDrawer';
import { RecordTasksCard } from '@/features/tasks/ui/RecordTasksCard';
import { AttachmentsSidebarCard } from '@/features/files/ui/AttachmentsCard';
import { RecordQuotesCard } from '@/features/quotes/ui/RecordQuotesCard';
import { LogCallDrawer } from '@/features/contacts/ui/actions/LogCallDrawer';
import { LogCommunicationDrawer } from '@/features/contacts/ui/actions/LogCommunicationDrawer';
import { LogPostalMailDrawer } from '@/features/contacts/ui/actions/LogPostalMailDrawer';
import { LogEmailDrawer } from '@/features/contacts/ui/actions/LogEmailDrawer';
import { asCompanyAssoc, asContactAssoc } from '@/features/contacts/ui/actions/assocTypes';
import { LogNoteDrawer } from '@/features/contacts/ui/actions/LogNoteDrawer';
import { ScheduleMeetingDrawer } from '@/features/contacts/ui/actions/ScheduleMeetingDrawer';
import { SendEmailDrawer } from '@/features/contacts/ui/actions/SendEmailDrawer';
import { AdditionalOwnersEdit } from '@/features/contacts/ui/actions/AdditionalOwners';
import { useUserPrefs } from '@/features/contacts/ui/actions/shared';
import { PropertyGroupCards } from '@/features/contacts/ui/actions/PropertyGroupCards';
import { customHistoryField } from '@/features/property-history/describe';
import { PropertyHistoryButton } from '@/features/property-history/PropertyHistoryButton';
import { PropertyHistoryDrawer } from '@/features/property-history/PropertyHistoryDrawer';
import { dealHistoryDescriber } from '@/features/property-history/records';
import {
  InlineEdit,
  InlineSelectInput,
  InlineTextInput,
  ownerChoices,
  picklistChoices,
} from '@/features/contacts/ui/actions/InlineEdit';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { TagChips } from '@/features/objects/ui/TagChips';
import { useAppliedTags } from '@/features/objects/useAppliedTags';
import { listPicklistOptions, type PicklistOption } from '@/features/picklists/api.client';
import { errorText, isApiError } from '@/lib/api/errors';
import { RecordToolIcon, useRecordTools } from '@/features/record-tools/ui/RecordTools';
import { cn } from '@/lib/utils/cn';
import { useFieldAccess, VIEW_ONLY_TITLE } from '@/features/permission-sets/field-access';
import { useObjectNames } from '@/features/objects/useObjectNames';
import { usePanelParam } from '@/features/record-pages/usePanelParam';

type ActivityTab =
  | 'all'
  | 'notes'
  | 'emails'
  | 'calls'
  | 'tasks'
  | 'meetings'
  | 'communications'
  | 'postal-mail'
  | 'stage-history';
type Drawer =
  | 'note'
  | 'email'
  | 'log-email'
  | 'dial'
  | 'call'
  | 'task'
  | 'meeting'
  | 'log-meeting'
  | 'communication'
  | 'postal-mail';
type Panel = 'properties' | 'delete' | 'edit' | 'move';

const ACTIVITY_TABS: Array<{ key: ActivityTab; 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' },
  { key: 'communications', label: 'Communications' },
  { key: 'postal-mail', label: 'Postal mail' },
  { key: 'stage-history', label: 'Stage history' },
];

/**
 * DR5b: the deal as Review associations reads an object: every built-in object and each custom
 * object that allows deals (`assocLinkTypes`).
 */
const DEAL_ASSOC_DEFINITION = { key: 'deal', associatedTypes: null };

/** DR5a: the deal's own fields' group in View all properties (HubSpot's name, as list pickers). */
const DEAL_INFO = 'Deal information';
const DEAL_GROUPS = [DEAL_INFO] as const;

/** DR6: the Pinned activity card asks for every pin (no type or date filter). */
const NO_PIN_PARAMS = {};

/** DR4b: the Overview cards the contact page's `ContactOverviewCard` draws on a deal. */
const DEAL_OVERVIEW_CARDS = [
  // DR6: Pinned activity (record-tabs.js:133).
  'pinned',
  'recent',
  'upcoming',
  'totals',
  't-contacts',
  't-companies',
  't-deals',
];

/** DR4a (R4): the right cards' memory; Quotes starts collapsed (record-tabs.js:262-264). */
const DEAL_RIGHT_MEMORY = { storageKey: 'rt.collapsed.deals', defaultCollapsed: ['quotes'] };

/** DR3: a sub-tab whose type the Activity chip turned off shows nothing. */
const NO_ITEMS: TimelineItem[] = [];

const DEAL_PRIORITIES: DealPriority[] = ['low', 'medium', 'high'];

/** DL5: the design's record amount (`recordMoney`): "$1,123", not the browser's "US$1,123". */
function formatMoney(amount: string | null, currency: string): string {
  return recordMoney(amount, currency) ?? BLANK;
}

function formatPicklistLabel(value: string | null | undefined): string {
  if (!value) return BLANK;
  return value.replace(/[_-]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}

/** Days to the close date, from today in the user's time zone (QA #368). */
function daysLeftLabel(
  closeDate: string | null,
  timeZone: string,
): { text: string; overdue: boolean } | null {
  if (!closeDate) return null;
  const close = Date.parse(`${closeDate.slice(0, 10)}T00:00:00Z`);
  if (!Number.isFinite(close)) return null;
  let todayText: string;
  try {
    todayText = new Intl.DateTimeFormat('en-CA', { timeZone }).format(new Date());
  } catch {
    todayText = new Date().toISOString().slice(0, 10);
  }
  const today = Date.parse(`${todayText}T00:00:00Z`);
  const diff = Math.round((close - today) / (24 * 60 * 60 * 1000));
  if (diff === 0) return { text: 'Due today', overdue: false };
  if (diff > 0) return { text: `${diff} day${diff === 1 ? '' : 's'} left`, overdue: false };
  const overdue = Math.abs(diff);
  return { text: `${overdue} day${overdue === 1 ? '' : 's'} overdue`, overdue: true };
}

/**
 * HUB-618: only meaningful property changes (owner, stage, amount…) in All activities, as on
 * contacts and companies; the rest stay in property history.
 */
const inFeed = (item: TimelineItem) =>
  item.type !== 'field_change' || MEANINGFUL_FIELDS.has(String(item.field ?? ''));

/** The searchable text of a readable timeline item. */
const readableText = (r: ReadableItem) =>
  [r.title, r.body ?? '', ...r.meta].join(' ').toLowerCase();

/** DR2: the quick row's More (record.php:413). */
function MoreDotsIcon() {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden>
      <circle cx="5" cy="12" r="1.8" />
      <circle cx="12" cy="12" r="1.8" />
      <circle cx="19" cy="12" r="1.8" />
    </svg>
  );
}

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

function ChevronIcon() {
  return (
    <svg className="crm-collapsible-card__chevron" viewBox="0 0 24 24" aria-hidden>
      <path d="m6 9 6 6 6-6" />
    </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="M7 4h10v16H7z" />
      <path d="M9 8h6M9 12h6M9 16h4" />
    </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="m4 7 8 6 8-6" />
    </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 TaskActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <path d="M9 5h11M9 12h11M9 19h11" />
      <path d="M4 5h1M4 12h1M4 19h1" />
    </svg>
  );
}

function MeetingActionIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <rect x="4" y="6" width="16" height="14" rx="2" />
      <path d="M8 4v4M16 4v4M4 10h16" />
    </svg>
  );
}

function CollapsibleCard({
  title,
  action,
  defaultOpen = true,
  children,
  cardId,
}: {
  title: string;
  action?: ReactNode;
  defaultOpen?: boolean;
  children: ReactNode;
  cardId?: string;
}) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <section className={cn('crm-collapsible-card', !open && 'is-collapsed')} data-card-id={cardId}>
      <header className="crm-collapsible-card__header">
        <button
          type="button"
          className="crm-collapsible-card__toggle"
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
        >
          <ChevronIcon />
          <span>{title}</span>
        </button>
        {action}
      </header>
      <div className="crm-collapsible-card__body">
        <div className="crm-collapsible-card__body-inner">{children}</div>
      </div>
    </section>
  );
}

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;
}) {
  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 DealDetailsView({ dealId }: { dealId: string }) {
  // HUB-226 D1: the object as the business names it ("Clients").
  const names = useObjectNames('deal');
  const me = useCurrentUser();
  /**
   * DR1: the page follows its record layout (my team's view, else the default; the built-in one
   * when none is saved or it failed to load), as the contact page and the 28 Oct design
   * (record-tabs.js:17, :248-249, :339). The open tab: the one picked here, else `?tab=`, else the
   * layout's default (record-tabs.js:862).
   */
  const myLayout = useMyRecordLayout('deal');
  const recordLayout = myLayout.layout;
  const [dealTab, setDealTab] = useState<string | null>(null);
  const [urlTab, setUrlTab] = useState<string | null>(null);
  useEffect(() => {
    setUrlTab(new URLSearchParams(window.location.search).get('tab'));
  }, []);
  /** R10b: closed sections of a tab, by `<tab id>|<index>` (open by default, not remembered). */
  const [closedSecs, setClosedSecs] = useState<Set<string>>(() => new Set());
  // HUB-317: built-in fields the permission set hides (not shown) or makes view-only (locked).
  const access = useFieldAccess('deal');
  const lockFor = (key: string) =>
    access.locked(key) ? { canEdit: false, lockedTitle: VIEW_ONLY_TITLE } : null;
  const { owners } = useOwners(true, true);
  const ownerById = useMemo(() => new Map(owners.map((o) => [o.userId, o])), [owners]);
  const toast = useToast();
  const router = useRouter();
  const prefs = useUserPrefs();
  // QA #352/#368: dates in the user's format and time zone, as on contacts and companies.
  const dates = useUserDates();

  const [deal, setDeal] = useState<Deal | null>(null);
  // HUB-226: its deal tags, worked out again after every save (a field may change them).
  const dealIds = useMemo(() => (deal ? [deal.id] : []), [deal]);
  const dealTags = useAppliedTags('deal', dealIds, deal?.updatedAt).get(deal?.id ?? '') ?? [];
  const [dealTypes, setDealTypes] = useState<PicklistOption[]>([]);
  const [customDefs, setCustomDefs] = useState<CustomPropertyDefinition[]>([]);
  // HubSpot's Deal Stage rules can hide Deal type (field rules on built-in fields).
  const dealRules = usePropertyLogic('deal');
  // 24 Nov: a stage with required properties asks for the deal's empty ones first.
  const stageGate = useDealStageGate({ defs: customDefs, owners, dealTypes });
  // DL1: reopening a won or lost deal asks first (stage bar, About, Move to pipeline).
  const reopen = useConfirm();
  const [pipeline, setPipeline] = useState<Pipeline | null>(null);
  const [deleted, setDeleted] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activityTab, setActivityTab] = useState<ActivityTab>('all');
  const [drawer, setOpenDrawer] = useState<Drawer | null>(null);
  /**
   * DL8 (QA D16): the design's composer windows (record.php loads one for every object, as
   * CompanyDetailsView's CQS1 #715). The page stays usable behind one, so anything opening here
   * asks it first and one window is open at a time.
   */
  const composer = useRef<ComposerWindowHandle | null>(null);
  const openWindow = useRef<Drawer | null>(null);
  const setDrawer = useCallback((next: Drawer | null) => {
    if (next && composer.current?.holdOpen(next === openWindow.current)) return;
    openWindow.current = next;
    setOpenDrawer(next);
  }, []);
  const [panel, setPanel] = useState<Panel | null>(null);
  /**
   * DL8: Edit, Move to pipeline and Delete ask the composer too. A draft keeps it open (it shows
   * its discard bar) and the panel waits; otherwise the composer closes and the panel opens.
   */
  const openPanel = (next: Panel) => {
    if (composer.current?.holdOpen(false)) return;
    setDrawer(null);
    setPanel(next);
  };
  // R7: a contact or company sidebar row's "View all properties" (`?panel=properties`) opens
  // this deal's properties panel; without the query the page is as before.
  usePanelParam(`/deals/${dealId}`, Boolean(deal), () => setPanel('properties'));
  /** HUB-315: the Merge flow (pick the other record, then review). */
  const [mergeOpen, setMergeOpen] = useState(false);
  /** HUB-392: the Closed Lost reason dialog (stage bar). */
  const lostReason = useClosedLostReason();
  // DL3: moving into a won stage asks an optional won reason.
  const wonReason = useClosedWonReason();
  /** HUB-707 #752: attaches the won dialog's signed contract; the move stands if it fails. */
  const attachContractOrWarn = async (dealId: string, file: File) => {
    try {
      await attachContract(dealId, file);
      toast('Signed contract attached', 'success');
    } catch (err) {
      toast(`The deal is won, but the contract wasn't attached: ${errorText(err)}`, 'danger');
    }
  };
  /** HUB-356: the property history drawer's field (`all` for every field); null when closed. */
  const [historyField, setHistoryField] = useState<string | null>(null);
  /** DR5a (R3): View all properties' groups, the deal's own first, as the company page. */
  const dealGroups = usePickerGroups('deal', DEAL_GROUPS);
  const dealCurrency = deal?.currency ?? 'USD';
  const currencies = useAccountCurrencies(dealCurrency);
  const describeHistory = useMemo(
    () =>
      dealHistoryDescriber({
        defs: customDefs,
        owners,
        dealTypes,
        currency: dealCurrency,
        formatDateTime: dates.dateTime,
      }),
    [customDefs, owners, dealTypes, dealCurrency, dates],
  );
  const [menuRequest] = useState(0);
  /** DR2 (R4): the sticky header watches the quick row scroll out of the left column. */
  const leftColumnRef = useRef<HTMLElement>(null);
  const quickRowRef = useRef<HTMLDivElement>(null);
  /** DR2 (R2): the quick row in the user's saved order (one for every record page). */
  const [buttonOrder, setButtonOrder] = useState<RecordActionButton[] | null>(null);
  const [reorderOpen, setReorderOpen] = useState(false);
  /** DR2 (MM1): More's Create a contract / payment link / quote / invoice dialog. */
  const [commerceKind, setCommerceKind] = useState<CommerceKind | null>(null);
  const closeCommerce = useCallback(() => setCommerceKind(null), []);
  /** DR2: the channel More's "Log SMS / LinkedIn / WhatsApp message" opens the log drawer on. */
  const [commChannel, setCommChannel] = useState<CommunicationChannel>('linkedin_message');
  /** DR2: Actions › Clone (record-popups-hs.js:564-578). */
  const [cloneOpen, setCloneOpen] = useState(false);
  /** DR5b: Actions › Review associations (the design's modal of the deal's own links). */
  const [reviewOpen, setReviewOpen] = useState(false);
  /** DR4a (R7): a right card row's Preview (record-tabs.js:659-780). */
  const [previewTarget, setPreviewTarget] = useState<PreviewTarget>(null);
  const [restoring, setRestoring] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);
  // GLM (go-live M1): on a 1280px laptop the right column starts collapsed behind its toggle.
  const [rightCollapsed, setRightCollapsed] = useNarrowRightCollapse();
  /** QA #366: a stage bar move is being saved. */
  const [stageBusy, setStageBusy] = useState(false);

  const [activityPicklists, setActivityPicklists] = useState<PicklistOption[]>([]);
  const [stageHistory, setStageHistory] = useState<StageHistoryEntry[]>([]);
  const [stageLoading, setStageLoading] = useState(false);
  const [stageError, setStageError] = useState<string | null>(null);
  const [activitySearch, setActivitySearch] = useState('');
  const [collapsedIds, setCollapsedIds] = useState<Set<string>>(new Set());
  /**
   * DR3 (R5b): the design's filter chips (record-activity-filters.js:93-114), as the contact and
   * company pages: the Activity types (null follows the Activity display settings), the date
   * presets or a custom range, several users and teams (applied by the API), and the sort.
   */
  const [activitySort, setActivitySort] = useState<'newest' | 'oldest'>('newest');
  const [activityDate, setActivityDate] = useState<TimelineDateFilter>('all');
  const [activityFrom, setActivityFrom] = useState('');
  const [activityTo, setActivityTo] = useState('');
  const [activityUserIds, setActivityUserIds] = useState<string[]>([]);
  const [activityTeamIds, setActivityTeamIds] = useState<string[]>([]);
  const [activityTypes, setActivityTypes] = useState<string[] | null>(null);
  const [teamOptions, setTeamOptions] = useState<Array<{ value: string; label: string }>>([]);
  useEffect(() => {
    listTeamOptions().then(
      (res) => setTeamOptions(res.data.map((t) => ({ value: t.id, label: t.name }))),
      () => setTeamOptions([]),
    );
  }, []);

  const isAdmin = me.role === 'admin';
  const activeOptions = (opts: PicklistOption[], field: string) =>
    opts.filter((o) => o.field === field && !o.archived);

  const load = useCallback(
    async (quiet = false) => {
      if (!quiet) setLoading(true);
      setError(null);
      try {
        const data = await getDeal(dealId);
        setDeal(data);
        setDeleted(false);
        const pipes = await listPipelines();
        const match =
          pipes.data.find((p) => p.id === data.pipeline.id) ??
          pipes.data.find((p) => !p.archived) ??
          null;
        setPipeline(match);
      } catch (err) {
        if (isApiError(err) && err.isNotFound && isAdmin) {
          try {
            const data = await getDeal(dealId, true);
            setDeal(data);
            setDeleted(true);
            setPipeline(null);
          } catch (inner) {
            setDeal(null);
            setError(errorText(inner));
          }
        } else {
          setDeal(null);
          setError(errorText(err));
        }
      } finally {
        if (!quiet) setLoading(false);
      }
    },
    [dealId, isAdmin],
  );

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

  useEffect(() => {
    listPicklistOptions({ objectType: 'activity' }).then(setActivityPicklists, () =>
      setActivityPicklists([]),
    );
    listPicklistOptions({ objectType: 'deal', field: 'dealType', includeArchived: true }).then(
      (list) => setDealTypes(list.filter((o) => o.field === 'dealType')),
      () => setDealTypes([]),
    );
    listCustomProperties({ objectType: 'deal' }).then(
      (defs) =>
        setCustomDefs(
          defs.filter((d) => !d.archived).sort((a, b) => a.displayOrder - b.displayOrder),
        ),
      () => setCustomDefs([]),
    );
  }, []);

  useEffect(() => {
    if (!deal || deleted || activityTab !== 'stage-history') return;
    let cancelled = false;
    setStageLoading(true);
    setStageError(null);

    const run = async () => {
      try {
        const res = await getDealStageHistory(dealId, { limit: 50 });
        if (!cancelled) setStageHistory(res.data);
      } catch (err) {
        if (!cancelled) setStageError(errorText(err));
      } finally {
        if (!cancelled) setStageLoading(false);
      }
    };
    void run();
    return () => {
      cancelled = true;
    };
  }, [deal, deleted, dealId, activityTab, refreshKey]);

  /** DR3 (HUB-426): the date, user and team chips go to the API, so 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) => getDealTimeline(dealId, { ...params, ...serverFilters }),
    [dealId, serverFilters],
  );
  /** DR3 (R5b): the Activity chip applies on every tab; a sub-tab whose type is off shows nothing. */
  const chosenTypes = useMemo(
    () => dealChosenTypes(activityTypes, prefs.timelineTypes),
    [activityTypes, prefs.timelineTypes],
  );
  const tabQuery = dealTimelineTypes(activityTab, chosenTypes);
  const noTypes = activityTab !== 'stage-history' && !tabQuery.fetches;
  const timelineState = useRecordTimeline({
    fetchPage: fetchTimeline,
    types: tabQuery.types ?? undefined,
    enabled: Boolean(deal) && !deleted && tabQuery.fetches,
    reloadKey: `${refreshKey}|${deal?.updatedAt ?? ''}|${JSON.stringify(serverFilters)}`,
  });
  const timeline = noTypes ? NO_ITEMS : timelineState.items;
  /**
   * DR6 (G8, the user's call of 25 Nov 2026): pinned items at the top of the timeline, with the
   * same types and filters as the list (as the contact and company pages); search applies below.
   */
  const pinParams = useMemo(
    () => ({ ...(tabQuery.types ? { types: tabQuery.types } : {}), ...serverFilters }),
    [tabQuery.types, serverFilters],
  );
  const timelineReloadKey = `${refreshKey}|${deal?.updatedAt ?? ''}|${JSON.stringify(serverFilters)}`;
  const timelinePins = useTimelinePins({
    record: 'deals',
    recordId: dealId,
    params: pinParams,
    enabled: Boolean(deal) && !deleted && tabQuery.fetches,
    reloadKey: timelineReloadKey,
  });
  /**
   * DR4b: the Overview cards' data, for the cards the open tab holds (as the contact page's R10b).
   * Conditional logic needs the deal, so this reads the tab's items without it: a card a rule
   * hides may load, never the other way round.
   */
  const loadItems = dealTabItems(
    recordLayout,
    dealOpenTab(
      dealTabs(recordLayout, () => true),
      dealTab ?? urlTab ?? recordLayout?.defaultTab,
    ),
    () => true,
  );
  const overviewKey = `${refreshKey}|${deal?.updatedAt ?? ''}`;
  const overviewTimeline = useCallback<OverviewTimeline>(
    (params) => getDealTimeline(dealId, params),
    [dealId],
  );
  const overviewData = useContactOverviewData(
    dealId,
    overviewKey,
    {
      recent: Boolean(deal) && !deleted && loadItems.includes('recent'),
      upcoming: Boolean(deal) && !deleted && loadItems.includes('upcoming'),
      totals: Boolean(deal) && !deleted && loadItems.includes('totals'),
    },
    overviewTimeline,
  );
  const tableRecords = useDealTables(
    dealId,
    {
      contacts: Boolean(deal) && !deleted && loadItems.includes('t-contacts'),
      companies: Boolean(deal) && !deleted && loadItems.includes('t-companies'),
      deals: Boolean(deal) && !deleted && loadItems.includes('t-deals'),
    },
    overviewKey,
  );
  /** DR6: the Overview's Pinned activity card (record-tabs.js:133): every pin, no filters. */
  const overviewPins = useTimelinePins({
    record: 'deals',
    recordId: dealId,
    params: NO_PIN_PARAMS,
    enabled: Boolean(deal) && !deleted && loadItems.includes('pinned'),
    reloadKey: `${overviewKey}|${timelinePins.pins.length}`,
  });
  // A sub-tab whose type the chip turned off loads nothing (the hook keeps its last state).
  // G8: the list also waits for the pins, so a pinned item doesn't jump to the top.
  const tabLoading =
    activityTab === 'stage-history'
      ? stageLoading
      : !noTypes && (timelineState.loading || !timelinePins.settled);
  const tabError = activityTab === 'stage-history' ? stageError : timelineState.error;
  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);
    },
  });

  const refresh = () => {
    setRefreshKey((n) => n + 1);
    void load(true);
  };

  const onRestore = async () => {
    setRestoring(true);
    try {
      await restoreDeal(dealId);
      toast('Deal restored');
      await load();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setRestoring(false);
    }
  };

  /** QA #367: how timeline items read (labels and values in plain words, as on contacts). */
  const readableCtx: ReadableContext = useMemo(
    () => ({
      recordName: deal?.name ?? '',
      describe: describeHistory,
      region: dates.prefs.region,
      timeZone: dates.prefs.timeZone,
      objectLabel: names.singular,
    }),
    [deal?.name, describeHistory, dates, names.singular],
  );

  /** DR3: date, users and teams are applied by the API (`serverFilters`); search and sort here. */
  const activityMatches = useCallback(
    (item: TimelineItem) => {
      const q = activitySearch.trim().toLowerCase();
      if (activityTab === 'all' && !inFeed(item)) return false;
      if (!q) return true;
      return readableText(readable(item, readableCtx)).includes(q) || String(item.type).includes(q);
    },
    [activitySearch, activityTab, readableCtx],
  );
  const filteredTimeline = useMemo(() => {
    // DR6 (G8): a pinned item shows once, at the top.
    const filtered = withoutPinned(timeline, timelinePins.pins).filter(activityMatches);
    return [...filtered].sort((a, b) => {
      const diff = new Date(a.occurredAt).getTime() - new Date(b.occurredAt).getTime();
      return activitySort === 'newest' ? -diff : diff;
    });
  }, [timeline, timelinePins.pins, activitySort, activityMatches]);
  /** DR6 (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],
  );

  /** DR3 (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;

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

  const activityByMonth = useMemo(() => {
    const map = new Map<string, TimelineItem[]>();
    for (const item of filteredTimeline) {
      const key = dates.monthYear(item.occurredAt);
      const list = map.get(key) ?? [];
      list.push(item);
      map.set(key, list);
    }
    return Array.from(map.entries());
  }, [filteredTimeline, dates]);

  const filteredStageHistory = useMemo(() => {
    const q = activitySearch.trim().toLowerCase();
    if (!q) return stageHistory;
    return stageHistory.filter((entry) => {
      const blob = [
        entry.to.stage.name,
        entry.from?.stage.name,
        entry.changedBy?.name,
        entry.changedAt,
      ]
        .filter(Boolean)
        .join(' ')
        .toLowerCase();
      return blob.includes(q);
    });
  }, [stageHistory, activitySearch]);

  // HUB-571 / HUB-382: Follow and the HubSpot Actions menu items (before the early returns).
  const tools = useRecordTools({
    // DR2 (LD2): Restore activity opens the recycle bin, as the design and Companies.
    restoreDesign: true,
    // DR2: Clone opens the design's form (CloneRecordDrawer).
    onClone: () => setCloneOpen(true),
    recordType: 'deal',
    recordId: dealId,
    name: deal?.name ?? '',
    searchText: deal?.name ?? '',
    canEdit:
      Boolean(deal) &&
      !deleted &&
      scopeCovers(me.permissionSet.rules.objects.deal.edit, deal?.owner?.id, me),
    canLog: !deleted && me.role !== 'read_only',
    timeZone: prefs.timeZone,
    properties: () =>
      deal
        ? Object.entries({
            'Deal name': deal.name,
            Pipeline: deal.pipeline?.name ?? '',
            'Deal stage': deal.stage?.name ?? '',
            // DL5: as the record's other amounts (it was the raw "USD 3623.00").
            Amount: recordMoney(deal.amount, deal.currency) ?? '',
            // The user's date format, as on the rest of the record (CRM-BUG #145).
            'Close date': deal.closeDate ? dates.date(deal.closeDate) : '',
            'Deal owner': deal.owner?.name ?? '',
            'Create date': dates.dateTime(deal.createdAt),
            ...Object.fromEntries(
              Object.entries(deal.customProperties ?? {}).map(([k, v]) => [
                k,
                Array.isArray(v) ? v.join(', ') : String(v ?? ''),
              ]),
            ),
          }).map(([label, value]) => ({ label, value }))
        : [],
    onChanged: () => {
      setRefreshKey((n) => n + 1);
      void load(true);
    },
    icon: (name) => <RecordToolIcon name={name} />,
    /**
     * DR5a (G12): View record access as the 28 Oct design (record-popups-hs.js:609-689), saving
     * the owner as the About card does. Reverses G12's "Deals keep HUB-571" (user's Q5).
     */
    accessDesign: {
      variant: 'record',
      one: names.singular.toLowerCase(),
      ownerLabel: `${names.singular} owner`,
      owner: deal?.owner ? { id: deal.owner.id, name: deal.owner.name } : null,
      ...ownerLock({
        canEdit:
          Boolean(deal) &&
          scopeCovers(me.permissionSet.rules.objects.deal.edit, deal?.owner?.id, me),
        deletedTitle: deleted ? 'This deal is deleted' : null,
        viewOnlyTitle: access.locked('ownerId') ? VIEW_ONLY_TITLE : null,
      }),
      saveOwner: async (ownerId) => {
        if (!deal) return;
        setDeal(await updateDeal(deal.id, { ownerId, updatedAt: deal.updatedAt }));
      },
      loadHistory: (params) => getDealHistory(dealId, params),
      describe: describeHistory,
      reloadKey: deal?.updatedAt,
    },
  });

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

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

  const rule = me.permissionSet.rules.objects.deal;
  // `team` (HUB-322): records of the user's team too.
  const canEdit = !deleted && scopeCovers(rule.edit, deal.owner?.id, me);
  const canDelete = !deleted && rule.delete;
  const canLog = !deleted && me.role !== 'read_only';
  // PB7: the Playbooks card's rows open the playbook dialog on this deal. Logging needs edit
  // access on the deal (the API's `assertLinkedRecordsEditable`).
  const playbookRun: PlaybookRunContext = {
    record: {
      objectType: 'deal',
      id: deal.id,
      name: deal.name,
      canLog: canLog && canEdit,
      links: {
        contact: deal.contacts.map((c) => ({ id: c.id, name: c.name ?? c.email ?? 'Contact' })),
        company: deal.companies.map((c) => ({ id: c.id, name: c.name, primary: c.isPrimary })),
      },
      values: deal.customProperties ?? {},
    },
    snippetTarget: { dealId: deal.id },
    onLogged: refresh,
  };
  const editTitle = deleted
    ? 'This deal is deleted'
    : canEdit
      ? undefined
      : "Your permissions don't allow you to edit this record";
  const logTitle = deleted
    ? 'This deal is deleted'
    : canLog
      ? undefined
      : "Your permissions don't allow you to log activity";
  const activityAdd = activityTabAddAction(activityTab);
  const activityLog = activityTabLogAction(activityTab);
  const deleteTitle = canDelete
    ? undefined
    : "Your permissions don't allow you to delete this record";

  // DL1 (QA #16): a won or lost deal has no countdown: "Due today" / "N days overdue" was red on
  // closed deals. Open deals keep it (DR2 kept it beside the design's close date).
  const closeMeta = isClosedStage(deal.stage)
    ? null
    : daysLeftLabel(deal.closeDate, dates.prefs.timeZone);
  const dealLink: ActivityLink = { type: 'deal', id: deal.id };
  const primaryContact = deal.contacts.find((c) => c.email) ?? deal.contacts[0] ?? null;
  // Not a hook: this runs after the early returns above.
  const noteAssociations = [
    ...deal.companies.map(asCompanyAssoc),
    ...deal.contacts.map((c) => asContactAssoc({ id: c.id, name: c.name, email: c.email })),
  ];
  const recipientOptions = (() => {
    const seen = new Set<string>();
    const options: Array<{ value: string; label: string; contactId: string }> = [];
    for (const c of deal.contacts) {
      const email = c.email?.trim().toLowerCase();
      if (!email || seen.has(email)) continue;
      seen.add(email);
      const name = c.name?.trim();
      options.push({
        value: email,
        label: name ? `${name} (${email})` : email,
        contactId: c.id,
      });
    }
    return options;
  })();
  /**
   * DR2 (R1/R2): the design's quick row (record-popups-hs.js:985-986) in the user's saved order,
   * one for every record page (`crm.preview.qa`, :984). DL8: Call opens the dialer, as on every
   * record in the design (record.php:344 `call-make`); Log a call is in More and the sticky menu.
   */
  const buttonKeys = buttonOrder ?? prefs.recordActionButtons;
  const QUICK_ICONS: Record<RecordActionButton, ReactNode> = {
    note: <NoteActionIcon />,
    email: <EmailActionIcon />,
    call: <CallActionIcon />,
    task: <TaskActionIcon />,
    meeting: <MeetingActionIcon />,
  };
  const quickDrawer = (key: RecordActionButton): Drawer => (key === 'call' ? 'dial' : key);

  const ActionIcon = ({ d }: { d: string }) => (
    <svg
      viewBox="0 0 24 24"
      width="16"
      height="16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      aria-hidden
    >
      <path d={d} />
    </svg>
  );

  /** DR2 (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);
    return a ? [separated ? { ...a, separated: true } : a] : [];
  };
  /**
   * DR5b: Review associations opens the design's modal of the deal's own links (EV15a), not the
   * suggestions drawer: the API's suggestions answer contacts and companies only.
   */
  const reviewTool = tools.actions.find((x) => x.key === 'review-associations');
  const reviewAction: ContactAction | null = reviewTool
    ? { ...reviewTool, onSelect: () => setReviewOpen(true) }
    : null;
  // The page's own "View all properties" (DR5a: the design's drawer).
  const propertiesAction: ContactAction = {
    key: 'properties',
    label: 'View all properties',
    icon: <ActionIcon d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01" />,
    onSelect: () => setPanel('properties'),
  };
  const historyAction: ContactAction = {
    key: 'history',
    label: 'View property history',
    icon: <ActionIcon d="M12 8v4l3 3M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />,
    onSelect: () => setHistoryField('all'),
  };
  /**
   * DR2: the design's Actions menu in its order and groups (record.php:299-323), as Companies
   * (R2). Summarize (AI) and Export are left out, as on Contacts and Companies. Edit deal and Move
   * to pipeline are master's own, kept in a last group (Q2); the Log items moved to More.
   */
  const actions: ContactAction[] = [
    ...toolAction('follow'),
    { ...propertiesAction, separated: true },
    historyAction,
    ...toolAction('association-history', true),
    ...(reviewAction ? [reviewAction] : []),
    ...toolAction('google', true),
    ...toolAction('restore-activity', true),
    ...toolAction('record-access'),
    {
      key: 'merge',
      label: 'Merge',
      icon: <ActionIcon d="M6 3v6a6 6 0 0 0 6 6h6M15 12l3 3-3 3M6 21v-6" />,
      onSelect: () => setMergeOpen(true),
      disabled: !(canEdit && canDelete),
      title:
        canEdit && canDelete
          ? undefined
          : 'Merging needs permission to edit and delete this record',
    },
    ...toolAction('clone'),
    {
      key: 'delete',
      label: 'Delete',
      icon: <ActionIcon d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />,
      onSelect: () => openPanel('delete'),
      disabled: !canDelete,
      title: deleteTitle,
    },
    {
      key: 'edit',
      label: 'Edit deal',
      icon: <ActionIcon d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />,
      onSelect: () => openPanel('edit'),
      disabled: !canEdit,
      title: editTitle,
      separated: true,
    },
    {
      key: 'move',
      label: 'Move to pipeline',
      icon: <ActionIcon d="M5 12h14M13 6l6 6-6 6" />,
      onSelect: () => openPanel('move'),
      disabled: !canEdit || access.locked('stageId'),
      title: access.locked('stageId') ? VIEW_ONLY_TITLE : editTitle,
    },
  ];
  /**
   * DR2 (R2): the About card's Actions (record-tabs.js:235). Customize properties opens the
   * record page editor on About (record.php:433; manage_settings only, no `from`, as LD6). Fill
   * smart properties (AI) is left out.
   */
  const aboutActions: ContactAction[] = [
    ...(me.permissionSet.rules.app.manage_settings
      ? [
          {
            key: 'customize-properties',
            label: 'Customize properties',
            icon: <ActionIcon d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />,
            onSelect: () =>
              router.push(
                recordEditorHref({
                  object: 'deal',
                  view: editorViewParam(myLayout.view),
                  card: 'about',
                }),
              ),
          },
        ]
      : []),
    propertiesAction,
    historyAction,
  ];
  const logItem = (
    key: string,
    label: string,
    icon: MoreMenuIconName,
    open: () => void,
  ): ContactAction => ({
    key,
    label,
    icon: <MoreMenuIcon name={icon} />,
    onSelect: open,
    disabled: !canLog,
    title: logTitle,
  });
  const logCommunication = (channel: CommunicationChannel) => () => {
    setCommChannel(channel);
    setDrawer('communication');
  };
  /**
   * DR2 (MM1): More's activities in the design's order and icons (record-popups-hs.js:969-997):
   * the commerce dialogs, any quick button not in the row, then the logs. Enroll in a sequence,
   * Engage on LinkedIn and Create a WhatsApp message are contact actions on master, so they are
   * left out, as on Companies.
   */
  const moreItems: ContactAction[] = [
    ...COMMERCE_KINDS.map((kind) =>
      logItem(kind, COMMERCE[kind].title, kind, () => setCommerceKind(kind)),
    ),
    ...fullOrder([])
      .filter((key) => !buttonKeys.includes(key))
      .map((key) => ({
        key,
        label: BUTTON_TITLES[key],
        icon: QUICK_ICONS[key],
        onSelect: () => setDrawer(quickDrawer(key)),
        disabled: !canLog,
        title: logTitle,
      })),
    logItem('sms', 'Log SMS', 'sms', logCommunication('sms')),
    logItem('linkedin-log', 'Log a LinkedIn message', 'li', logCommunication('linkedin_message')),
    logItem('whatsapp-log', 'Log a WhatsApp message', 'wa', logCommunication('whats_app')),
    logItem('call-log', 'Log a call', 'logcall', () => setDrawer('call')),
    logItem('log-meeting', 'Log a meeting', 'logmeet', () => setDrawer('log-meeting')),
    logItem('log-email', 'Log an email', 'mail', () => setDrawer('log-email')),
    logItem('postal-mail', 'Log postal mail', 'post', () => setDrawer('postal-mail')),
  ];
  /** DR2 (R4): the sticky header's "Create activities" (record.php:365-372). */
  const stickyItem = (key: string, label: string, icon: ReactNode, open: () => void) => ({
    key,
    label,
    icon,
    onSelect: open,
    disabled: !canLog,
    title: logTitle,
  });
  const stickyActivities: ContactAction[] = [
    stickyItem('s-note', 'Create note', <NoteActionIcon />, () => setDrawer('note')),
    stickyItem('s-email', 'Create email', <EmailActionIcon />, () => setDrawer('email')),
    stickyItem('s-log-email', 'Log email', <EmailActionIcon />, () => setDrawer('log-email')),
    stickyItem('s-dial', 'Make a call', <CallActionIcon />, () => setDrawer('dial')),
    stickyItem('s-call', 'Log call', <CallActionIcon />, () => setDrawer('call')),
    stickyItem('s-task', 'Create task', <TaskActionIcon />, () => setDrawer('task')),
    stickyItem('s-meeting', 'Schedule meeting', <MeetingActionIcon />, () => setDrawer('meeting')),
    stickyItem('s-log-meeting', 'Log meeting', <MeetingActionIcon />, () =>
      setDrawer('log-meeting'),
    ),
  ];
  /** DR2 (LD3): the name popover's fields (record.php:136-141); hidden left out, locked read-only. */
  const nameFields = dealNameFields(deal, {
    hidden: (key) => access.hidden(key),
    lockedTitle: (key) => lockFor(key)?.lockedTitle,
  });
  const saveNameField = async (key: string, value: string) => {
    await saveDeal(dealNameSave(key, value));
  };
  /**
   * DR2: Clone (record-popups-hs.js:564-578): the form's name and owner over the deal's values
   * the person may set (as company clones, B4); then the copy opens.
   */
  const cloneDeal = async (v: Record<string, string>) => {
    const name = (v.name ?? '').trim() || `${deal.name} (clone)`;
    const body = cloneDealBody(deal, {
      name,
      ownerId: v.ownerId || null,
      locked: cloneLocked(me, customDefs, 'deal'),
    });
    try {
      const copy = await createDeal(body);
      toast(`${name} was created`);
      setCloneOpen(false);
      router.push(`/deals/${copy.id}`);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
      throw err;
    }
  };

  /** HUB-615: save one in-place edit (PATCH with the loaded `updatedAt`) and show the result. */
  const saveDeal = async (body: UpdateDealBody) => {
    setDeal(await updateDeal(deal.id, { ...body, updatedAt: deal.updatedAt }));
  };
  const selectEdit = (
    label: string,
    display: string,
    current: string | null,
    options: Array<{ value: string; label: string }>,
    emptyLabel: string,
    save: (value: string | null) => Promise<void>,
    /** The field's key, for the permission set's lock (HUB-317). */
    key: string,
  ) => (
    <InlineEdit<string>
      label={label}
      saveOn="change"
      dropdown
      display={display}
      canEdit={lockFor(key)?.canEdit ?? canEdit}
      lockedTitle={lockFor(key)?.lockedTitle ?? editTitle}
      initial={() => current ?? ''}
      renderInput={(input) => (
        <InlineSelectInput {...input} emptyLabel={emptyLabel} options={options} />
      )}
      onSave={async (value) => {
        if ((value || null) === (current ?? null)) return;
        await save(value || null);
      }}
    />
  );

  /**
   * QA #366: the stage bar moves the deal as the board and "Move to pipeline" do (POST
   * /deals/:id/stage). The API applies the stage rules (forward-only pipelines, closed won /
   * lost: close date and probability); `updatedAt` refuses a deal someone changed meanwhile.
   */
  const stageLockedTitle = !canEdit
    ? (editTitle ?? null)
    : access.locked('stageId')
      ? VIEW_ONLY_TITLE
      : null;
  const stageSteps =
    pipeline && pipeline.id === deal.pipeline.id && !deleted
      ? stageBarSteps(pipeline, deal.stage.id, {
          lockedTitle: stageLockedTitle,
          canMoveBack: pipeline.allowBackwardMoves || me.permissionSet.rules.app.restore,
        })
      : [];
  const moveToStage = async (stage: PipelineStage) => {
    if (stageBusy || stage.id === deal.stage.id) return;
    // DL1: reopening a closed deal asks first (user, 25 Nov 2026; beyond the design).
    if (
      reopensDeal(deal.stage, stage) &&
      !(await reopen.confirm(reopenConfirm(deal.name, deal.stage, stage)))
    ) {
      return;
    }
    // 24 Nov design (stageGate): the stage's required properties first, then (HUB-392) Closed
    // Lost asks why.
    let current: Deal | null = deal;
    if (requiredNames(stage).length) {
      current = await stageGate.fillRequired(deal, stage);
      if (!current) return;
      if (current !== deal) setDeal(current);
    }
    // DL3: the pipeline may let the lost reason be skipped; a won stage asks a won reason
    // (HUB-707 #752: required when the pipeline says so) and offers a signed contract.
    const answer: (LostAnswer | WonAnswerWithContract) | null =
      stage.stageType === 'lost'
        ? await lostReason.ask(deal.name, { required: pipeline?.lostReasonRequired !== false })
        : stage.stageType === 'won'
          ? await wonReason.ask(deal.name, {
              required: pipeline?.wonReasonRequired === true,
              contract: true,
            })
          : {};
    if (!answer) return;
    const { contract, ...lost } = answer as WonAnswerWithContract & LostAnswer;
    setStageBusy(true);
    try {
      const move = (from: Deal) =>
        changeDealStage(deal.id, { stageId: stage.id, updatedAt: from.updatedAt, ...lost });
      try {
        setDeal(await move(current));
      } catch (err) {
        // Required properties changed meanwhile: ask for the ones the API names, then retry.
        const names = stageRequirementsOf(err);
        if (!names) throw err;
        const filled = await stageGate.fillRequired(await getDeal(deal.id), stage, names);
        if (!filled) return;
        setDeal(await move(filled));
      }
      toast(`Moved to ${stage.name}`);
      if (contract) await attachContractOrWarn(deal.id, contract);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
      // Changed meanwhile: show the deal as it is now.
      if (isApiError(err) && err.isConflict) void load(true);
    } finally {
      setStageBusy(false);
    }
  };

  const probabilityLabel =
    deal.probabilityOverride !== null
      ? `${deal.probability}% (override)`
      : `${deal.probability}% (from stage)`;

  /* ------------------------------------------------------------ DR1: record layout */

  /** The deal's property texts, hidden fields left out: conditional logic, highlights, cards. */
  const texts = dealTexts(deal, {
    describe: describeHistory,
    date: dates.date,
    money: formatMoney,
    hidden: (key) => access.hidden(key),
  });
  /** R10d: whether a tab or card shows under the layout's conditional logic (record-tabs.js:20-27). */
  const condValue = dealCondValue(deal, texts);
  const condShows = (key: string) => condOk(recordLayout?.cond, key, condValue);
  /** A card's saved title, else the page's own. */
  const cardTitle = (id: string, fallback: string) => recordLayout?.cards[id]?.title || fallback;
  /**
   * LD6: a card's gear opens the record page editor on that card, and Exit comes back here
   * (record-tabs.js:32). Admins only, once the layout loaded: saving over a layout that failed to
   * load would replace it (as the contact page).
   */
  const cardGear = (id: string): (() => void) | null =>
    canEditCards(me.role) && myLayout.status === 'ready'
      ? () =>
          router.push(
            recordEditorHref({
              object: 'deal',
              view: editorViewParam(myLayout.view),
              card: id,
              from: `/deals/${deal.id}`,
            }),
          )
      : null;
  /**
   * DR4a: an association card's "Edit default card" settings and gear, as the contact and
   * company pages: its title, the properties each row shows, and (saved with filters, quick
   * filters or sort) its own list.
   */
  const cardView = (id: string): CardView => {
    const saved = recordLayout?.cards[id];
    const gear = cardGear(id);
    return {
      ...(saved?.title ? { title: saved.title } : {}),
      ...(saved?.assoc?.props ? { props: saved.assoc.props } : {}),
      ...(saved?.assoc && listMode(saved) ? { list: saved.assoc } : {}),
      ...(gear ? { onGear: gear } : {}),
    };
  };
  /** The design's "Associated company": the primary company (else the first). */
  const associated = dealCompany(deal);

  /**
   * DR1: the About card's rows by property key; the layout picks and orders them (`cards.about.props`,
   * record-layout.js:106). Associated company and Last activity date are the design's.
   */
  const aboutRows: Record<string, ReactNode> = {
    // DL1 (QA #4): Pipeline opens Move to pipeline (pipeline and stage, with its prompts); Deal
    // stage moves the deal as the stage bar does (record-page.js:86: editing the stage clicks
    // the bar), so the required properties, lost reason and reopen confirm all still ask.
    pipelineId: (
      <AboutField label="Pipeline">
        {stageLockedTitle === null && !deleted ? (
          // InlineEdit's value button, so it reads like the other editable rows.
          <button
            type="button"
            className="crm-inline__value"
            title="Move to another pipeline"
            onClick={() => openPanel('move')}
          >
            <span>{deal.pipeline.name}</span>
          </button>
        ) : (
          <span className="crm-inline__static" title={stageLockedTitle ?? undefined}>
            {deal.pipeline.name}
          </span>
        )}
      </AboutField>
    ),
    stageId: (
      <AboutField label="Deal stage">
        {stageSteps.length ? (
          <InlineEdit<string>
            label="Deal stage"
            saveOn="change"
            dropdown
            display={deal.stage.name}
            canEdit={stageLockedTitle === null && !stageBusy}
            lockedTitle={stageLockedTitle ?? undefined}
            initial={() => deal.stage.id}
            renderInput={(input) => (
              <InlineSelectInput {...input} options={aboutStageChoices(stageSteps)} />
            )}
            onSave={async (id) => {
              const next = stageSteps.find((s) => s.stage.id === id && !s.blocked)?.stage;
              if (next && next.id !== deal.stage.id) await moveToStage(next);
            }}
          />
        ) : (
          deal.stage.name
        )}
      </AboutField>
    ),
    amount: access.hidden('amount') ? null : (
      <AboutField label="Amount" onHistory={() => setHistoryField('amount')}>
        <InlineEdit<string>
          label="Amount"
          display={formatMoney(deal.amount, deal.currency)}
          canEdit={lockFor('amount')?.canEdit ?? canEdit}
          lockedTitle={lockFor('amount')?.lockedTitle ?? editTitle}
          initial={() => deal.amount ?? ''}
          renderInput={(input) => <InlineTextInput {...input} type="number" />}
          onSave={async (raw) => {
            const next = raw.trim() || null;
            if (next !== null && !Number.isFinite(Number(next))) {
              throw new Error('Amount must be a number');
            }
            if (next === (deal.amount ?? null)) return;
            await saveDeal({ amount: next });
          }}
        />
      </AboutField>
    ),
    closeDate: access.hidden('closeDate') ? null : (
      <AboutField label="Close date" onHistory={() => setHistoryField('closeDate')}>
        <InlineEdit<string>
          label="Close date"
          display={dates.date(deal.closeDate)}
          canEdit={lockFor('closeDate')?.canEdit ?? canEdit}
          lockedTitle={lockFor('closeDate')?.lockedTitle ?? editTitle}
          initial={() => deal.closeDate ?? ''}
          renderInput={(input) => <InlineTextInput {...input} type="date" />}
          onSave={async (raw) => {
            const next = raw.trim() || null;
            if (next === (deal.closeDate ?? null)) return;
            await saveDeal({ closeDate: next });
          }}
        />
      </AboutField>
    ),
    currency: access.hidden('currency') ? null : (
      <AboutField label="Currency">
        <select
          className="input"
          aria-label="Currency"
          disabled={!(lockFor('currency')?.canEdit ?? canEdit)}
          value={deal.currency}
          onChange={(e) => {
            const next = e.target.value;
            if (next === deal.currency) return;
            void saveDeal({ currency: next });
          }}
        >
          {currencies.map((code) => (
            <option key={code} value={code}>
              {code}
            </option>
          ))}
        </select>
      </AboutField>
    ),
    ownerId: (
      <AboutField label="Deal owner" onHistory={() => setHistoryField('ownerId')}>
        {selectEdit(
          'Deal owner',
          ownerLabelFromCache(deal.owner, ownerById),
          deal.owner?.id ?? null,
          ownerChoices(owners, deal.owner),
          'No owner',
          (ownerId) => saveDeal({ ownerId }),
          'ownerId',
        )}
      </AboutField>
    ),
    additionalOwners: (
      <AboutField label="Additional owners">
        <AdditionalOwnersEdit
          current={deal.additionalOwners}
          owners={owners}
          canEdit={canEdit}
          lockedTitle={editTitle}
          onSave={(ids) => saveDeal({ additionalOwnerIds: ids })}
        />
      </AboutField>
    ),
    dealType:
      access.hidden('dealType') ||
      propertyLogicState(
        dealRules,
        propertyLogicValues(
          'deal',
          { stageId: deal.stage?.id ?? null, dealType: deal.dealType },
          deal.customProperties,
        ),
      ).hidden.has('dealtype') ? null : (
        <AboutField label="Deal type" onHistory={() => setHistoryField('dealType')}>
          {selectEdit(
            'Deal type',
            dealTypes.find((o) => o.value === deal.dealType)?.label ??
              formatPicklistLabel(deal.dealType),
            deal.dealType,
            picklistChoices(dealTypes, deal.dealType),
            '--',
            (dealType) => saveDeal({ dealType }),
            'dealType',
          )}
        </AboutField>
      ),
    priority: access.hidden('priority') ? null : (
      <AboutField label="Priority" onHistory={() => setHistoryField('priority')}>
        {selectEdit(
          'Priority',
          formatPicklistLabel(deal.priority),
          deal.priority,
          DEAL_PRIORITIES.map((p) => ({ value: p, label: formatPicklistLabel(p) })),
          '--',
          (priority) => saveDeal({ priority: priority as DealPriority | null }),
          'priority',
        )}
      </AboutField>
    ),
    probabilityOverride: (
      <AboutField label="Win probability" onHistory={() => setHistoryField('probabilityOverride')}>
        <InlineEdit<string>
          label="Win probability"
          display={probabilityLabel}
          canEdit={canEdit}
          lockedTitle={editTitle}
          initial={() =>
            deal.probabilityOverride === null ? '' : String(deal.probabilityOverride)
          }
          renderInput={(input) => (
            <>
              <InlineTextInput {...input} type="number" />
              <span className="crm-fs-8 crm-text-muted">
                Empty uses the stage&apos;s {deal.stage.probability}%
              </span>
            </>
          )}
          onSave={async (raw) => {
            const text = raw.trim();
            const next = text ? Number(text) : null;
            if (next !== null && (!Number.isFinite(next) || next < 0 || next > 100)) {
              throw new Error('Win probability must be a number from 0 to 100');
            }
            if (next === deal.probabilityOverride) return;
            await saveDeal({
              probabilityOverride: next === null ? null : Math.round(next * 100) / 100,
            });
          }}
        />
      </AboutField>
    ),
    createdAt: <AboutField label="Create date" value={dates.date(deal.createdAt)} />,
    company: (
      <AboutField label="Associated company">
        {associated ? <Link href={`/companies/${associated.id}`}>{associated.name}</Link> : BLANK}
      </AboutField>
    ),
    lastActivity: (
      <AboutField label="Last activity date" value={texts.lastActivity?.text || BLANK} />
    ),
  };
  /** Custom properties edited in place (the group cards, View all properties). */
  const customEdit = {
    canEdit,
    lockedTitle: editTitle,
    timeZone: prefs.timeZone,
    formatDateTime: dates.dateTime,
    onSave: (name: string, value: CustomProperties[string] | null) =>
      saveDeal({ customProperties: { [name]: value } }),
  };
  /** The left property-group cards (HUB-226), one movable `groups` entry (Q2). */
  const groupCards = (
    <PropertyGroupCards
      objectType="deal"
      defs={customDefs}
      values={deal.customProperties}
      builtIns={{ stageId: deal.stage?.id ?? null, dealType: deal.dealType }}
      edit={customEdit}
      onHistory={(field) => setHistoryField(customHistoryField(field))}
    />
  );
  /**
   * DR5a (R3): "View all properties" as the design's drawer (record-tabs.js:614-649), as the
   * company page: the deal's own rows (the About card's editors) in "Deal information", then
   * every custom property in its group, edited in place. Hidden fields are left out.
   */
  const propertyRow = (key: string, label: string, node: ReactNode, history = true) =>
    access.hidden(key)
      ? []
      : [
          {
            key,
            label,
            group: DEAL_INFO,
            text: key === 'name' ? deal.name : (texts[key]?.text ?? ''),
            node,
            onHistory: history ? () => setHistoryField(key) : undefined,
          },
        ];
  const propertyRows: PropertyRow[] = [
    ...propertyRow('name', 'Deal name', <AboutField label="Deal name" value={deal.name} />),
    ...(ABOUT_FIELDS.deal ?? []).flatMap((f) =>
      aboutRows[f.id]
        ? propertyRow(f.id, f.label, aboutRows[f.id], f.id !== 'company' && f.id !== 'lastActivity')
        : [],
    ),
    ...customDefs.map((d) => ({
      key: `custom.${d.name}`,
      label: d.label,
      group: (d.groupName && dealGroups.labelOf(d.groupName)) || 'Other properties',
      text: describeHistory(customHistoryField(d.name)).text(deal.customProperties?.[d.name]),
      node: <CustomFieldsList defs={[d]} values={deal.customProperties ?? {}} edit={customEdit} />,
      onHistory: () => setHistoryField(customHistoryField(d.name)),
    })),
  ];

  /** A property's label and text, or null when hidden; a custom one without a value is blank. */
  const textOf = (key: string): { label: string; text: string } | null =>
    texts[key] ??
    (key.startsWith('custom.') && !access.hidden(key)
      ? { label: describeHistory(key).label, text: '' }
      : null);
  /** A custom property's row: its text and property history, as the contact page's About. */
  const customAbout = (key: string): ReactNode => {
    const t = key.startsWith('custom.') ? textOf(key) : null;
    if (!t) return null;
    return (
      <AboutField label={t.label} value={t.text || BLANK} onHistory={() => setHistoryField(key)} />
    );
  };
  const propRows = (keys: string[]) => (
    <div className="crm-about-contact">
      {keys.map((k) => (
        <Fragment key={k}>{aboutRows[k] ?? customAbout(k)}</Fragment>
      ))}
    </div>
  );
  /** A left property card, About or one an admin created (record-tabs.js:228-237), with its gear. */
  const leftPropCard = (id: string, fallback: string, keys: string[]) => {
    const title = cardTitle(id, fallback);
    // DR2 (R2): About's "Actions ▾" before its gear (record-tabs.js:235-236).
    const menu =
      id === 'about' && !deleted ? (
        <ContactActionsMenu
          actions={aboutActions}
          showSearch={false}
          triggerClassName="crm-collapsible-card__action"
          keyboard
        />
      ) : null;
    return (
      <CollapsibleCard
        title={title}
        cardId={id}
        defaultOpen
        action={withCardGear(menu, cardGear(id), title)}
      >
        {propRows(keys)}
      </CollapsibleCard>
    );
  };
  /** DR1: a left card by layout id; ids the page can't draw show nothing. */
  const leftCard = (id: string): ReactNode => {
    if (id === 'about')
      return leftPropCard('about', 'About this deal', dealAboutKeys(recordLayout));
    if (id === 'groups') return groupCards;
    const props = recordLayout?.cards[id]?.props;
    return props ? leftPropCard(id, 'Untitled card', props) : null;
  };

  /**
   * DR1: a property card in a tab: Data highlights' grid (record-tabs.js:124-127; the design's
   * defaults, `cardDef`) or a created card's rows (:217-219), with the gear.
   */
  const centerPropCard = (id: string): ReactNode => {
    if (id === 'about') return null;
    const def = cardDef(id, 'Untitled card', 'deal');
    // Data highlights saved with no rows show the design's defaults, as the contact page's.
    const saved = recordLayout?.cards[id]?.props;
    const keys =
      id === 'highlights' ? (saved?.length ? saved : def.props?.defaults) : (saved ?? null);
    if (!def.props || !keys) return null;
    const highlight = def.props.highlight;
    const title = cardTitle(id, id === 'highlights' ? 'Data highlights' : 'Untitled card');
    const rows = keys.flatMap((k) => {
      const t = textOf(k);
      if (!t) return [];
      return [
        { key: k, label: t.label, text: highlight ? dealHighlightText(k, texts, deal) : t.text },
      ];
    });
    return (
      <section className="rp-sample" data-card-id={id}>
        <header className="rp-sample__head">
          <h3>{title}</h3>
          {withCardGear(null, cardGear(id), title)}
        </header>
        {highlight ? (
          <dl className="rp-highlights">
            {rows.map((r) => (
              <div key={r.key}>
                <dt>{r.label.toUpperCase()}</dt>
                <dd>{r.text || BLANK}</dd>
              </div>
            ))}
          </dl>
        ) : (
          <div className="crm-about-contact">
            {rows.map((r) => (
              <div key={r.key} className="crm-about-field">
                <div className="crm-about-label">{r.label}</div>
                <div className="crm-about-value">{r.text || BLANK}</div>
              </div>
            ))}
          </div>
        )}
      </section>
    );
  };
  /** DR1: a tab's card by layout id; `activities` is the page's stage bar and timeline. */
  const centerCard = (id: string, activities: ReactNode): ReactNode => {
    if (id === 'activities') return activities;
    if (id === 'docusign') {
      return (
        <ComingSoonPanel
          title="DocuSign"
          text="Send the contract for signature and follow its status from this deal once DocuSign is connected."
        />
      );
    }
    if (id === 'predict') {
      return (
        <SampleCard title="Predictive deal score">
          <p>
            <strong>Likely to close</strong> — similar deals at this stage close in about 30 days.
            (Deal scoring isn&apos;t computed by the CRM yet.)
          </p>
        </SampleCard>
      );
    }
    if (DEAL_OVERVIEW_CARDS.includes(id)) {
      // DR4b: the contact page's Overview cards (record-tabs.js:85-132), with the deal's data.
      const review = reviewAction;
      const gear = cardGear(id);
      return (
        <ContactOverviewCard
          id={id}
          data={overviewData}
          highlights={[]}
          contacts={dealTableRows('contacts', tableRecords.contacts ?? [], dates.date)}
          // DR6: the Pinned activity card's items (null until they loaded).
          pinned={overviewPins.settled ? overviewPins.pins.map((p) => p.item) : null}
          companies={dealTableRows('companies', tableRecords.companies ?? [], dates.date)}
          deals={dealTableRows('deals', tableRecords.deals ?? [], dates.date)}
          readableCtx={readableCtx}
          onViewAll={() => selectTab('activities')}
          // The design's table "+ Add" opens Review associations (record-tabs.js:940).
          onAddAssociation={
            review ? { onClick: review.onSelect, disabled: review.disabled } : undefined
          }
          // The tables' gear: the record page editor on that card (record-tabs.js:106).
          customizeHref={
            gear
              ? recordEditorHref({
                  object: 'deal',
                  view: editorViewParam(myLayout.view),
                  card: id,
                  from: `/deals/${deal.id}`,
                })
              : null
          }
        />
      );
    }
    return centerPropCard(id);
  };
  /**
   * Which wrapper a tab card sits in (`tabGroups`): Predictive deal score and the property cards
   * share `.rp-samples`; DR4b's Overview cards `.rp-overview` (their styles, as the contact page).
   */
  const centerFamily = (id: string): string | null => {
    if (id === 'activities') return 'activity';
    if (id === 'docusign') return 'docusign';
    if (DEAL_OVERVIEW_CARDS.includes(id)) return 'overview';
    if (id === 'predict' || id === 'highlights') return 'samples';
    return id !== 'about' && recordLayout?.cards[id]?.props ? 'samples' : null;
  };
  const tabs = dealTabs(recordLayout, condShows);
  const openTab = dealOpenTab(tabs, dealTab ?? urlTab ?? recordLayout?.defaultTab);
  /** R8a: the open tab is kept in `?tab=`, and the first tab has none (record-tabs.js:917). */
  const selectTab = (id: string) => {
    setDealTab(id);
    const url = new URL(window.location.href);
    if (id === tabs[0]?.id) url.searchParams.delete('tab');
    else url.searchParams.set('tab', id);
    if (url.href !== window.location.href) {
      window.history.replaceState(window.history.state, '', url);
    }
  };
  /** DR6 (G8): whether this person may pin here (edit rights, the pins loaded). */
  const canPin = canEdit && timelinePins.ready;
  /** One timeline card; `pinned` cards sit above the dated list (DR6, G8). */
  const renderActivityCard = (item: TimelineItem, pinned: boolean) => {
    // QA #367: labels and values in plain words (no field keys or JSON).
    const r = readable(item, readableCtx);
    const collapsed = collapsedIds.has(item.id);
    return (
      <article
        key={item.id}
        className={cn(
          'crm-activity-card',
          `crm-activity-card--${item.type}`,
          pinned && 'is-pinned',
          collapsed && 'is-collapsed',
        )}
      >
        {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}>{dates.dateTime(item.occurredAt)}</time>
            </span>
          ) : (
            <time dateTime={item.occurredAt}>{dates.dateTime(item.occurredAt)}</time>
          )}
        </div>
        {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}
        {!collapsed ? (
          <>
            {r.body ? <p className="crm-activity-card__description">{r.body}</p> : null}
            {timelineEditing.actions(item)}
          </>
        ) : null}
      </article>
    );
  };
  /** DR1: the right cards the layout shows, in its order; ids the page can't draw show nothing. */
  const rightColumn = (cards: Record<string, ReactNode>): ReactNode =>
    dealAreaCards(recordLayout, 'right', condShows).map((id) => (
      <Fragment key={id}>{cards[id] ?? null}</Fragment>
    ));
  /**
   * R10b: the open tab's cards as the page draws them (record-tabs.js:872-886): sections open and
   * close the cards after them; a tab its rule hides says so (:145, :876).
   */
  const tabBody = (activities: ReactNode): ReactNode => {
    if (tabs.find((t) => t.id === openTab)?.hidden) {
      return (
        <p className="crm-activity-empty">Cards in this tab are hidden due to conditional logic.</p>
      );
    }
    const closedHere = new Set(
      [...closedSecs]
        .filter((k) => k.startsWith(`${openTab}|`))
        .map((k) => Number(k.split('|')[1])),
    );
    const groups = tabGroups(
      dealTabItems(recordLayout, openTab, condShows),
      closedHere,
      centerFamily,
    );
    if (!groups.length) return <p className="crm-activity-empty">No cards in this tab yet.</p>;
    return 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)}
            onToggle={() =>
              setClosedSecs((cur) => {
                const k = `${openTab}|${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, activities)}</Fragment>
        ),
      );
      const key = `g-${g.entries[0]!.index}`;
      if (g.family === 'overview') {
        // DR4b: the Overview cards' scoped styles, as the contact page (`.rp-overview`).
        return (
          <section key={key} className="rp-overview rt-panel" aria-label="Overview">
            {inner}
          </section>
        );
      }
      return g.family === 'samples' ? (
        <div key={key} className="rp-samples">
          {inner}
        </div>
      ) : (
        <Fragment key={key}>{inner}</Fragment>
      );
    });
  };

  return (
    <div
      className={cn(
        'crm-contact-layout crm-contact-layout--deal',
        rightCollapsed && 'is-right-collapsed',
      )}
    >
      {deleted ? (
        <div className="crm-p-3">
          <Alert tone="warning">
            This deal 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}>
          {/* DR2 (R4): the compact header once the quick row scrolls away (record-page.js:102-126). */}
          {!deleted ? (
            <RecordStickyHeader
              watchRef={quickRowRef}
              columnRef={leftColumnRef}
              backHref="/deals"
              backLabel={names.plural}
              actions={actions}
              avatar={<Avatar name={deal.name} size="xs" />}
              name={deal.name}
              activities={stickyActivities}
            />
          ) : null}
          <div className="crm-sidebar-cards">
            <section className="crm-contact-profile-card">
              <div className="crm-contact-profile">
                <div className="crm-contact-profile__top">
                  {/* DR2 (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="/deals"
                  >
                    <BackIcon />
                    <span className="crm-contact-profile__section-title">{names.plural}</span>
                  </Link>
                  {/* DR2 (R2): no search box, the design's keys (record-ui.php:125, record-actions.js). */}
                  <ContactActionsMenu
                    actions={actions}
                    disabled={deleted}
                    openRequest={menuRequest}
                    showSearch={false}
                    keyboard
                  />
                </div>

                <div className="crm-contact-profile__info">
                  <div className="crm-contact-profile__identity crm-mt-3">
                    {/* DR2: the design's initials (record.php:383). */}
                    <Avatar name={deal.name} size="lg" />
                    <div>
                      {/* DR2 (LD3): the name as text, its pencil and popover (record-page.js:128-256). */}
                      <div className="rp-namerow">
                        <h1 className="crm-contact-profile__name">{deal.name}</h1>
                        <RecordNamePopover
                          object="deal"
                          recordName={deal.name}
                          fields={nameFields}
                          disabledTitle={canEdit ? undefined : editTitle}
                          onSave={saveNameField}
                          onDetails={() => setPanel('properties')}
                        />
                      </div>
                    </div>
                  </div>
                  <div className="crm-contact-profile__designation crm-deal-profile-designation">
                    {formatMoney(deal.amount, deal.currency)}
                  </div>
                  <TagChips
                    tags={dealTags}
                    className="crm-d-flex crm-flex-wrap crm-gap-2 crm-mt-2"
                  />
                  <div className="crm-contact-profile__email crm-deal-profile-close crm-gap-1 crm-flex-wrap">
                    Close date{' '}
                    <span
                      className="crm-deal-profile-close-date"
                      style={closeMeta?.overdue ? { color: 'var(--danger)' } : undefined}
                    >
                      {dates.date(deal.closeDate)}
                    </span>
                    {closeMeta ? ` · ${closeMeta.text}` : null}
                  </div>
                </div>

                <div
                  className="crm-mt-0 crm-contact-profile__quick-actions crm-d-flex crm-align-items-start crm-justify-content-between crm-deal-quick-actions"
                  ref={quickRowRef}
                >
                  {buttonKeys.map((key) => (
                    <button
                      key={key}
                      type="button"
                      title={logTitle ?? BUTTON_TITLES[key]}
                      disabled={!canLog}
                      onClick={() => setDrawer(quickDrawer(key))}
                    >
                      <span className="crm-contact-profile__action-icon">{QUICK_ICONS[key]}</span>
                      <span>{BUTTON_LABELS[key]}</span>
                    </button>
                  ))}
                  {/* DR2 (R2): More holds activities only (record-popups-hs.js:1032-1067). */}
                  <ActivitiesMoreMenu
                    items={moreItems}
                    onReorder={() => setReorderOpen(true)}
                    disabled={deleted}
                  >
                    <span className="crm-contact-profile__action-icon">
                      <MoreDotsIcon />
                    </span>
                    <span>More</span>
                  </ActivitiesMoreMenu>
                </div>
              </div>
            </section>

            {dealAreaCards(recordLayout, 'left', condShows).map((id) => (
              <Fragment key={id}>{leftCard(id)}</Fragment>
            ))}
          </div>
        </aside>

        {/* CENTER */}
        <main className="crm-contact-layout__center">
          <div className="crm-center-panel">
            {/* DR1: the layout's tabs (the 28 Oct design's Activities, DocuSign, Overview). */}
            <RecordTabBar<string>
              label="Deal sections"
              tabs={tabs.map((t) => ({ key: t.id, label: t.label }))}
              active={openTab}
              onSelect={selectTab}
              customizeHref={
                me.permissionSet.rules.app.manage_settings
                  ? '/settings/objects?object=deal&tab=record'
                  : null
              }
            />
            {tabBody(
              <>
                <DealStageBar steps={stageSteps} busy={stageBusy} onSelect={moveToStage} />
                <TimelineTypeTabs
                  tabs={ACTIVITY_TABS}
                  active={activityTab}
                  onChange={(key) => {
                    setActivityTab(key);
                    setActivitySearch('');
                  }}
                  label="Deal activity tabs"
                />

                <div className="crm-activity-content">
                  <div className="crm-activity-toolbar">
                    <div className="crm-activity-search">
                      <SearchIcon />
                      <input
                        type="search"
                        placeholder={activityTabSearchPlaceholder(activityTab)}
                        value={activitySearch}
                        onChange={(e) => setActivitySearch(e.target.value)}
                        aria-label={activityTabSearchPlaceholder(activityTab)}
                      />
                    </div>
                    <div className="crm-activity-toolbar__actions">
                      {/* DR3 (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>

                  {activityTab !== 'stage-history' ? (
                    <>
                      {/* DR3 (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}
                      </div>
                    </>
                  ) : null}

                  {deleted ? (
                    <div className="crm-activity-empty">
                      <p>This deal is deleted</p>
                      <p>Restore it to see its activity and stage history.</p>
                    </div>
                  ) : null}

                  {!deleted && tabLoading ? <p className="crm-activity-empty">Loading…</p> : null}
                  {!deleted && tabError ? <Alert tone="danger">{tabError}</Alert> : null}

                  {!deleted && !tabLoading && activityTab === 'stage-history' ? (
                    filteredStageHistory.length === 0 ? (
                      <div className="crm-activity-empty">
                        <p>No stage history yet</p>
                      </div>
                    ) : (
                      <div className="crm-activity-list">
                        {filteredStageHistory.map((entry) => (
                          <article
                            key={entry.id}
                            className="crm-activity-card crm-activity-card--stage"
                          >
                            <div className="crm-activity-card__top">
                              <div className="crm-activity-card__title">
                                <strong>Deal Activity</strong>
                              </div>
                              <time dateTime={entry.changedAt}>
                                {dates.dateTime(entry.changedAt)}
                              </time>
                            </div>
                            <p className="crm-activity-card__description">
                              {entry.changedBy?.name ? (
                                <span className="crm-activity-actor">{entry.changedBy.name} </span>
                              ) : null}
                              moved {deal.name} to {entry.to.stage.name}
                              {entry.from ? ` (from ${entry.from.stage.name})` : ''}
                            </p>
                          </article>
                        ))}
                      </div>
                    )
                  ) : null}

                  {/* DR6 (G8): pinned items above the dated list, newest pin first. */}
                  {!deleted &&
                  !tabLoading &&
                  activityTab !== 'stage-history' &&
                  timelinePins.failed ? (
                    <PinsLoadError />
                  ) : null}
                  {!deleted &&
                  !tabLoading &&
                  activityTab !== 'stage-history' &&
                  shownPins.length ? (
                    <div className="crm-activity-list crm-pins-list">
                      {shownPins.map((p) => renderActivityCard(p.item, true))}
                    </div>
                  ) : null}
                  {!deleted && !tabLoading && activityTab !== 'stage-history' ? (
                    activityByMonth.length === 0 ? (
                      shownPins.length ? null : (
                        // DR3 (R5b): the design's empty state, "No matching …" under a filter.
                        <TimelineEmpty
                          what={
                            activityTab === 'all'
                              ? 'activities'
                              : (ACTIVITY_TABS.find(
                                  (t) => t.key === activityTab,
                                )?.label.toLowerCase() ?? 'activities')
                          }
                          record={deal.name}
                          filtered={activityFiltered}
                          canCreate={Boolean(activityAdd || activityLog)}
                        />
                      )
                    ) : (
                      <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}
                  {!deleted && !tabLoading && activityTab !== 'stage-history' ? (
                    <TimelineLoadMore
                      hasMore={!noTypes && timelineState.hasMore}
                      loading={timelineState.loadingMore}
                      onLoadMore={() => void timelineState.loadMore()}
                    />
                  ) : null}
                </div>
              </>,
            )}
          </div>
        </main>

        {/* RIGHT */}
        <aside className="crm-contact-layout__right">
          {/* DR4a (R4): right cards remember being collapsed, per viewer; Quotes starts collapsed
            (record-tabs.js:262-264). */}
          <CardMemory.Provider value={DEAL_RIGHT_MEMORY}>
            <div className="crm-sidebar-cards">
              {/* DR1: the layout's right cards, in its order (record-tabs.js:339). */}
              {rightColumn({
                // DR4a: the design's association cards (record-tabs.js:281-316), with their
                // "Edit default card" settings; Deals are the deals linked to this one (HUB-574).
                'r-contacts': (
                  <DealAssociationCard
                    kind="contacts"
                    deal={deal}
                    canEdit={canEdit}
                    view={cardView('r-contacts')}
                    onChanged={() => load(true)}
                    onPreview={setPreviewTarget}
                    dateText={dates.date}
                  />
                ),
                'r-companies': (
                  <DealAssociationCard
                    kind="companies"
                    deal={deal}
                    canEdit={canEdit}
                    view={cardView('r-companies')}
                    onChanged={() => load(true)}
                    onPreview={setPreviewTarget}
                    dateText={dates.date}
                  />
                ),
                'r-deals': (
                  <DealAssociationCard
                    kind="deals"
                    deal={deal}
                    canEdit={canEdit}
                    view={cardView('r-deals')}
                    onChanged={() => load(true)}
                    onPreview={setPreviewTarget}
                    dateText={dates.date}
                  />
                ),
                // The design's Playbooks card (record-tabs.js:322-326), as the contact page's.
                // PB8: only with the "Playbooks" permission.
                playbooks: canUsePlaybooks(me) ? <PlaybooksCard run={playbookRun} /> : null,
                // Events, Leads, Tickets and other custom objects linked to the deal (HUB-269).
                'r-objects': (
                  <LinkedObjectCards
                    anchorType="deal"
                    variant="deal"
                    anchorId={deal.id}
                    anchorName={deal.name}
                    canEdit={canEdit}
                  />
                ),
                tasks: (
                  <RecordTasksCard
                    linkedType="deal"
                    linkedId={deal.id}
                    timeZone={prefs.timeZone}
                    refreshKey={refreshKey}
                    canAdd={canLog}
                    canComplete={canLog}
                    onAdd={() => setDrawer('task')}
                  />
                ),
                attachments: !deleted ? (
                  <AttachmentsSidebarCard
                    link={{ type: 'deal', id: deal.id }}
                    canEdit={canEdit}
                    refreshKey={refreshKey}
                    // DR4a: the design's "Add ▾" (Your computer / Existing file), as Companies.
                    designAdd
                  />
                ) : null,
                // QA #364: quotes linked to the deal (design details.php "Quotes").
                quotes: !deleted ? (
                  <RecordQuotesCard
                    anchor={{
                      type: 'deal',
                      id: deal.id,
                      companyId:
                        deal.companies.find((c) => c.isPrimary)?.id ??
                        deal.companies[0]?.id ??
                        null,
                      contactId: deal.contacts[0]?.id ?? null,
                    }}
                    canAdd={canLog}
                  />
                ) : null,
                // HUB-400: line items (design "Line items" card, "Edit line items" drawer).
                'r-lineitems': !deleted ? (
                  <DealLineItemsCard
                    dealId={deal.id}
                    dealUpdatedAt={deal.updatedAt}
                    canEdit={canEdit && !access.locked('amount')}
                    onChanged={refresh}
                  />
                ) : null,
              })}
            </div>
          </CardMemory.Provider>
        </aside>
      </div>

      <button
        type="button"
        className="crm-panel-collapse"
        aria-label={rightCollapsed ? 'Expand right panel' : 'Collapse right panel'}
        aria-expanded={!rightCollapsed}
        onClick={() => setRightCollapsed((v) => !v)}
      >
        <svg viewBox="0 0 24 24" aria-hidden>
          <rect x="5" y="5" width="14" height="14" rx="2" />
          <path d="m13 9 3 3-3 3" />
        </svg>
      </button>

      {timelineEditing.dialogs}
      {/* DR4a (R7): a right card row's Preview (record-tabs.js:659-780). */}
      <AssociatedPreview
        target={previewTarget}
        onClose={() => setPreviewTarget(null)}
        onChanged={refresh}
      />
      {/* DL8: Note, Call, Log email, Email and Task open in the design's composer window, as on
          Companies. Meeting keeps master's window there too (its attendee row is one contact). */}
      <LogNoteDrawer
        composer={composer}
        open={drawer === 'note'}
        onClose={() => setDrawer(null)}
        link={dealLink}
        recordName={deal.name}
        initialAssociations={noteAssociations}
        // Snippets are filled for the deal's primary contact (and the deal), as on Companies.
        snippetContactId={primaryContact?.id}
        onLogged={refresh}
      />
      <LogCallDrawer
        snippetContactId={primaryContact?.id}
        composer={composer}
        open={drawer === 'call' || drawer === 'dial'}
        // A deal's contacts come without phone numbers (`Deal['contacts']`).
        dial={drawer === 'dial' ? { name: deal.name, phone: null } : null}
        onClose={() => setDrawer(null)}
        link={dealLink}
        recordName={deal.name}
        initialAssociations={noteAssociations}
        outcomes={activeOptions(activityPicklists, 'callOutcome')}
        timeZone={prefs.timeZone}
        onLogged={refresh}
      />
      <LogCommunicationDrawer
        snippetContactId={primaryContact?.id}
        open={drawer === 'communication'}
        onClose={() => setDrawer(null)}
        link={dealLink}
        recordName={deal.name}
        timeZone={prefs.timeZone}
        onLogged={refresh}
        channel={commChannel}
      />
      {/* DR2: Actions › Clone (record-popups-hs.js:564-578): Deal name and Deal owner. */}
      <CloneRecordDrawer
        open={cloneOpen}
        title={`Clone ${names.singular}`}
        fields={[
          { name: 'name', label: `${names.singular} name`, required: true },
          {
            name: 'ownerId',
            label: `${names.singular} owner`,
            type: 'select',
            options: ownerChoices(owners, deal.owner),
          },
        ]}
        initial={{ name: `${deal.name} (clone)`, ownerId: cloneDealOwnerId(deal, me) ?? '' }}
        editFormHref={me.role === 'admin' ? '/create-form-editor?object=deal' : undefined}
        onClose={() => setCloneOpen(false)}
        onClone={cloneDeal}
      />
      {/* DR2 (R2): More's "Reorder activity buttons": one order for every record page. */}
      <ButtonOrderDialog
        open={reorderOpen}
        order={buttonKeys}
        onClose={() => setReorderOpen(false)}
        onSaved={setButtonOrder}
      />
      <CommerceCreateDialog kind={commerceKind} recordName={deal.name} onClose={closeCommerce} />
      <LogPostalMailDrawer
        snippetContactId={primaryContact?.id}
        open={drawer === 'postal-mail'}
        onClose={() => setDrawer(null)}
        link={dealLink}
        recordName={deal.name}
        timeZone={prefs.timeZone}
        onLogged={refresh}
      />
      <ScheduleMeetingDrawer
        snippetContactId={primaryContact?.id}
        open={drawer === 'meeting' || drawer === 'log-meeting'}
        onClose={() => setDrawer(null)}
        link={dealLink}
        recordName={deal.name}
        defaultAttendeeEmail={primaryContact?.email ?? null}
        attendeeOptions={recipientOptions}
        timeZone={prefs.timeZone}
        defaultMinutes={prefs.meetingMinutes}
        defaultAddToCalendar={drawer === 'meeting'}
        onScheduled={refresh}
      />
      <LogEmailDrawer
        snippetContactId={primaryContact?.id}
        composer={composer}
        open={drawer === 'log-email'}
        onClose={() => setDrawer(null)}
        link={dealLink}
        recordName={deal.name}
        initialAssociations={noteAssociations}
        onLogged={refresh}
      />
      <SendEmailDrawer
        composer={composer}
        open={drawer === 'email'}
        onClose={() => setDrawer(null)}
        contactId={primaryContact?.id}
        contactEmail={primaryContact?.email ?? null}
        recipientOptions={recipientOptions}
        dealId={deal.id}
        recordLink={{ type: 'deal', id: deal.id }}
        recordName={deal.name}
        signature={prefs.signature}
        onSent={refresh}
      />
      <CreateTaskDrawer
        snippetContactId={primaryContact?.id}
        composer={composer}
        open={drawer === 'task'}
        onClose={() => setDrawer(null)}
        link={{ objectType: 'deal', id: deal.id }}
        recordName={deal.name}
        taskTypes={activeOptions(activityPicklists, 'taskType')}
        timeZone={prefs.timeZone}
        onCreated={refresh}
      />

      <EditDealDrawer
        open={panel === 'edit'}
        onClose={() => setPanel(null)}
        deal={deal}
        timeZone={prefs.timeZone}
        onSaved={() => {
          setPanel(null);
          refresh();
        }}
      />
      {lostReason.dialog}
      {wonReason.dialog}
      {stageGate.dialog}
      {reopen.dialog}
      <MoveDealPipelineDrawer
        open={panel === 'move'}
        onClose={() => setPanel(null)}
        deal={deal}
        // DL1: the stage gate and reopen confirm, as the stage bar.
        fillRequired={stageGate.fillRequired}
        confirmReopen={(from, to) => reopen.confirm(reopenConfirm(deal.name, from, to))}
        onMoved={() => {
          setPanel(null);
          refresh();
        }}
      />
      {/* DR5a (R3): View all properties as the design's drawer (record-tabs.js:614-649); the
          old DealPropertiesModal is no longer opened here. */}
      <AllPropertiesDesignDrawer
        open={panel === 'properties'}
        onClose={() => setPanel(null)}
        name={deal.name}
        rows={propertyRows}
        groupOrder={dealGroups.order}
        manageHref={propertySettingsHref(me, 'deal')}
        docHref={canEditPropertySettings(me) ? '/settings/properties?object=deal' : null}
      />
      {tools.drawers}
      {/* DR5b (D09): "Merge duplicate records" as the design (record-popups-hs.js:458-560),
          as the contact and company pages; reverses MDP's "deal record keeps master's". */}
      <MergeDesignDialog
        open={mergeOpen}
        objectType="deal"
        record={{ id: deal.id, label: deal.name, secondary: null }}
        onClose={() => setMergeOpen(false)}
        timeZone={prefs.timeZone}
      />
      {/* DR5b (EV15a): Review associations as the design (record-popups-hs.js:360-428): the
          deal's own links by type and label, with Dissociate. */}
      <EventReviewAssociations
        open={reviewOpen}
        onClose={() => setReviewOpen(false)}
        definition={DEAL_ASSOC_DEFINITION}
        record={{ id: deal.id, name: deal.name }}
        onChanged={refresh}
      />
      <PropertyHistoryDrawer
        open={historyField !== null}
        onClose={() => setHistoryField(null)}
        load={(params) => getDealHistory(deal.id, params)}
        describe={describeHistory}
        initialField={historyField ?? 'all'}
        reloadKey={deal.updatedAt}
        timeZone={prefs.timeZone}
        // DR5a (PH1): the design's drawer (record-popups-hs.js:301-355), as Contacts and Companies.
        design={{
          recordName: deal.name,
          objectType: 'deal',
          canManageProperties: canOpenPropertySettings(me),
        }}
      />
      <DeleteDealDialog
        open={panel === 'delete'}
        onClose={() => setPanel(null)}
        dealId={deal.id}
        dealName={deal.name}
        onDeleted={() => {
          setPanel(null);
          router.push('/deals');
        }}
      />
    </div>
  );
}
