'use client';

import { MergeDesignDialog } from '@/features/duplicates/design/MergeDesignDialog';
import {
  ADDITIONAL_LABEL,
  additionalText,
  keepMergedIds,
  MERGED_IDS_LABEL,
  mergedIdsText,
} from '@/features/duplicates/mergedIds';
import {
  ComingSoonPanel,
  PlaybooksCard,
  RecordTabBar,
  type PlaybookRunContext,
} from '@/features/record-pages/RecordTabs';
import { recordDuplicateCount } from '@/features/duplicates/api.client';
import { CATCHUP_CARDS, CatchUpCard, type InteractionsState } from './catchup/CompanyCatchUp';
import { isSection, sectionName, TabSection, tabGroups } from '@/features/record-layouts/tabItems';
import { condOk, recordTexts } from '@/features/record-layouts/cond';
import { interactionsOf, missingFields, type DuplicateCount } from './catchup/catchup';
import { MERGE_DENIED_TITLE, recordRights, 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 { Alert } from '@/components/crm/Alert';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useTimelineEditing } from '@/features/activities/ui/TimelineActivityEditing';
import { useOpenRecordAction } from '@/features/activities/ui/useOpenRecordAction';
import { usePanelParam } from '@/features/record-pages/usePanelParam';
import {
  ALL_TIMELINE_TYPES,
  timelineServerFilters,
  timelineTypesParam,
  type TimelineDateFilter,
} from '@/features/activities/timelineFilters';
import {
  TimelineEmpty,
  TimelineExpandMenu,
  TimelineFilterChips,
} from '@/features/activities/ui/TimelineFilterChips';
import { TimelineTypeTabs } from '@/features/activities/ui/TimelineControls';
import { listTeamOptions } from '@/features/members/api.client';
import { AssociatedPreview, type PreviewTarget } from '@/features/record-pages/AssociatedPreview';
import { RecordStickyHeader } from '@/features/record-pages/RecordStickyHeader';
import {
  ActivityTabAddButton,
  activityTabAddAction,
  activityTabLogAction,
  activityTabSearchPlaceholder,
  TimelineLoadMore,
} from '@/features/activities/ui/TimelineControls';
import {
  BLANK,
  MEANINGFUL_FIELDS,
  readable,
  type ReadableContext,
  type ReadableItem,
} from '@/features/activities/readable';
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 { useUserDates } from '@/features/activities/useUserDates';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { canUsePlaybooks } from '@/features/playbooks/access';
import type { CommunicationChannel } from '@/features/activities/api.client';
import {
  createCompany,
  getCompany,
  getCompanyHistory,
  getCompanyTimeline,
  restoreCompany,
  updateCompany,
} from '@/features/companies/api.client';
import { cloneCompanyBody, cloneLocked, cloneOwnerId } from '@/features/companies/clone';
import {
  BUTTON_LABELS,
  BUTTON_TITLES,
  ButtonOrderDialog,
  fullOrder,
} from '@/features/contacts/ui/record/RecordPrefsDialogs';
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 { CloneRecordDrawer } from '@/features/record-tools/ui/CloneRecordDrawer';
import type { RecordActionButton } from '@/features/settings/types';
import type { Company, TimelineItem, UpdateCompanyBody } from '@/features/companies/types';
import { timelineBody, timelineTitle } from '@/features/activities/timelineSearch';
import { DeleteCompanyDialog } from '@/features/companies/ui/actions/DeleteCompanyDialog';
import { RecordNamePopover, type NameField } from '@/features/record-pages/RecordNamePopover';
import {
  ContactActionsMenu,
  type ContactAction,
} from '@/features/contacts/ui/actions/ContactActionsMenu';
import { PropertyGroupCards } from '@/features/contacts/ui/actions/PropertyGroupCards';
import {
  CustomFieldInput,
  CustomFieldsList,
  type CustomFieldsEdit,
  fromUiValue,
  sameUiValue,
  toUiValue,
  type CustomUiValue,
} from '@/features/contacts/ui/actions/custom-fields';
import {
  InlineEdit,
  InlineSelectInput,
  InlineTextInput,
  ownerChoices,
  picklistChoices,
} from '@/features/contacts/ui/actions/InlineEdit';
import { CardMemory, CollapsibleCard } from '@/features/contacts/ui/CollapsibleCard';
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 { asContactAssoc, asDealAssoc } 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 { customHistoryField } from '@/features/property-history/describe';
import { PropertyHistoryButton } from '@/features/property-history/PropertyHistoryButton';
import { PropertyHistoryDrawer } from '@/features/property-history/PropertyHistoryDrawer';
import { companyHistoryDescriber } from '@/features/property-history/records';
import { getCreateForm, type CreateFormField } from '@/features/create-forms/api.client';
import { DEFAULT_COMPANY_FORM } from '@/features/companies/ui/companyCreate';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { applyPropertyLogic, usePropertyLogic } from '@/features/custom-properties/logic';
import { ownerDisplayName, ownerLabelFromCache, ownerRecordLabel } from '@/features/owners/labels';
import { useOwners } from '@/features/owners/useOwners';
import {
  listPicklist,
  listPicklistOptions,
  type PicklistOption,
} from '@/features/picklists/api.client';
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 { errorText, isApiError } from '@/lib/api/errors';
import { RecordToolIcon, useRecordTools } from '@/features/record-tools/ui/RecordTools';
import { ownerLock } from '@/features/record-tools/recordAccessView';
import { cn } from '@/lib/utils/cn';
import {
  inlinePhoneValue,
  normalizeWebsite,
  phoneError,
  sanitizePhoneInput,
  websiteError,
} from '@/lib/validation/contact-company';
import { LinkedObjectCards } from '@/features/objects/ui/LinkedObjectCards';
import { defaultLayout, useMyRecordLayout } from '@/features/record-layouts/api.client';
import { baseCardId, cardDef, listMode } from '@/features/record-layouts/cardSettings';
import type { CardView } from '@/features/record-layouts/ui/AssocLines';
import { canEditCards, withCardGear } from '@/features/record-layouts/ui/CardGear';
import { recordEditorHref, editorViewParam } from '@/features/record-layouts/editorLinks';
import { CompanyAssociations } from './CompanyAssociations';
import { companyHeaderLink, companySubtitle } from './companyHeaderLink';
import { companyInitials, formatMoney } from './format';
import { useFieldAccess, VIEW_ONLY_TITLE } from '@/features/permission-sets/field-access';
import {
  canEditPropertySettings,
  canOpenPropertySettings,
  propertySettingsHref,
} from '@/features/permission-sets/property-settings';
import { usePickerGroups } from '@/features/list-page/propertyGroups';
import {
  AllPropertiesDesignDrawer,
  DesignPropertyRow,
  useDesignPropertyRow,
  type PropertyRow,
} from '@/features/record-tools/ui/AllPropertiesDesign';

type KnownTab = 'catchup' | 'overview' | 'activity' | 'revenue';
/** R10b: a page tab: a known one, or `x:<layout id>` for a tab only the layout has. */
type CenterTab = KnownTab | `x:${string}`;
/** R9: record layout tab ids (the 28 Oct design's) and the page's tabs; `overview` before v4. */
const LAYOUT_TABS: Record<string, KnownTab> = {
  catchup: 'catchup',
  about: 'overview',
  overview: 'overview',
  activities: 'activity',
  revenue: 'revenue',
};
/** A page tab's record layout id (LAYOUT_TABS the other way). */
const LAYOUT_TAB_ID: Record<KnownTab, string> = {
  catchup: 'catchup',
  overview: 'about',
  activity: 'activities',
  revenue: 'revenue',
};
/** R10b: a layout tab id as the page's tab key, and back. */
const tabKeyOf = (id: string): CenterTab => LAYOUT_TABS[id] ?? `x:${id}`;
const layoutIdOf = (tab: CenterTab): string =>
  tab.startsWith('x:') ? tab.slice(2) : LAYOUT_TAB_ID[tab as KnownTab];
/** R10b: the About tab's cards (R9) and the whole-tab cards a tab can hold. */
const ABOUT_CARDS = new Set(['profile', 'summary', 'recent', 'leadscore']);
const PLAIN_CARDS = new Set(['activities', 'revenue']);
const BUILT_IN_COMPANY_LAYOUT = defaultLayout('company');
/**
 * The 28 Oct design's company tabs (record-layout.js:122-132), without a saved layout. CQS1D,
 * the user's call (23 Nov): without the design's Intelligence, as Contacts (CQS2).
 */
const BUILT_IN_TABS: Array<readonly [CenterTab, string]> = [
  ['catchup', 'Catch-up'],
  ['overview', 'About'],
  ['activity', 'Activities'],
  ['revenue', 'Revenue'],
];
type Drawer =
  | 'note'
  | 'call'
  // CQS1D: the design's dialer (Call, `call-make`); `call` is Log call.
  | 'dial'
  | 'meeting'
  | 'log-meeting'
  | 'email'
  | 'log-email'
  | 'communication'
  | 'postal-mail';
const EXTENSION_ACTIONS = ['email', 'note', 'call', 'task', 'meeting'] as const;
type Panel = 'properties' | 'delete';
type ActivitySubTab = 'activity' | 'notes' | 'emails' | 'calls' | 'tasks' | 'meetings';
type ActivityDateFilter = TimelineDateFilter;

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

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

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

const NO_ITEMS: TimelineItem[] = [];

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

/**
 * HUB-618: only meaningful property changes (owner, name…) in the activity feed; the rest
 * (HubSpot system fields such as hs_user_ids_of_all_notification_recipients) 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();

/** The sentence, facts and longer text of a readable timeline item. */
function ReadableBody({ r }: { r: ReadableItem }) {
  return (
    <>
      {r.sentence ? <p>{r.sentence}</p> : null}
      {r.meta.length ? <small>{r.meta.join(' · ')}</small> : null}
      {r.body ? <p>{r.body}</p> : null}
    </>
  );
}

function EventIcon({ type }: { type: string }) {
  const path =
    type === 'call'
      ? 'M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.12 4.1 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z'
      : type === 'email'
        ? 'M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2zm0 2 8 5 8-5'
        : type === 'meeting'
          ? 'M3 5h18v16H3zM16 3v4M8 3v4M3 11h18'
          : type === 'task'
            ? 'M9 11l3 3L22 4M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11'
            : type === 'communication'
              ? 'M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2zM8 9h8M8 13h5'
              : type === 'postal_mail'
                ? 'M4 5h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM15 8h4v4h-4zM5 9h6M5 13h6M5 16h9'
                : 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6';

  return (
    <span className="company-event-icon" aria-hidden>
      <svg
        viewBox="0 0 24 24"
        width="14"
        height="14"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
      >
        <path d={path} />
      </svg>
    </span>
  );
}

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

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

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

function ActionIcon({ d }: { d: string }) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
      <path d={d} />
    </svg>
  );
}

function customProp(props: Company['customProperties'] | undefined, keys: string[]): string | null {
  if (!props) return null;
  for (const key of keys) {
    const value = props[key];
    if (value === null || value === undefined || value === '') continue;
    if (Array.isArray(value)) return value.length ? value.join(', ') : null;
    if (typeof value === 'boolean') return value ? 'Yes' : 'No';
    return String(value);
  }
  return null;
}

function QuickActionIcon({
  kind,
}: {
  kind: 'note' | 'email' | 'call' | 'task' | 'meeting' | 'more';
}) {
  // Must be an <svg> (not a <span>) — company CSS hides `.company-quick-action span`.
  if (kind === 'more') {
    return (
      <svg
        className="icon"
        viewBox="0 0 24 24"
        width="18"
        height="18"
        fill="currentColor"
        aria-hidden
      >
        <circle cx="5" cy="12" r="1.75" />
        <circle cx="12" cy="12" r="1.75" />
        <circle cx="19" cy="12" r="1.75" />
      </svg>
    );
  }
  const paths: Record<string, string> = {
    note: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M8 13h8M8 17h5',
    email: 'M4 4h16v14H4zM4 6l8 5 8-5',
    call: 'M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.12 4.1 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z',
    // R1: the design's check-square (record.php:342).
    task: 'M9 11l3 3L22 4M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11',
    meeting: 'M3 5h18v16H3zM16 3v4M8 3v4M3 11h18',
  };
  return (
    <svg
      className="icon"
      viewBox="0 0 24 24"
      width="18"
      height="18"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      aria-hidden
    >
      <path d={paths[kind]} />
    </svg>
  );
}

/** R3: the built-in fields' group in "View all properties", as the list pickers name it. */
const COMPANY_INFO = 'Company information';
const COMPANY_GROUPS = [COMPANY_INFO] as const;

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

/** HubSpot fields the About card shows (design); the property-group cards leave them out. */

function AboutRow({ label, children }: { label: ReactNode; children: ReactNode }) {
  // R3: inside "View all properties", the design's row around the same value or editor.
  const look = useDesignPropertyRow();
  if (look) return <DesignPropertyRow look={look}>{children}</DesignPropertyRow>;
  return (
    <div className="crm-about-field">
      <div className="crm-about-label">{label}</div>
      <div className="crm-about-value">{children}</div>
    </div>
  );
}

export function CompanyDetailsView({ companyId }: { companyId: string }) {
  const me = useCurrentUser();
  /** The record layout of my team (or the default): the right sidebar's order and card settings. */
  const myLayout = useMyRecordLayout('company');
  const recordLayout = myLayout.layout;
  /** A sidebar card's layout settings, and its gear for admins (who may save layouts). */
  const cardView = (id: string): CardView => {
    const saved = recordLayout?.cards[id];
    return {
      ...(saved?.title ? { title: saved.title } : {}),
      ...(saved?.assoc?.props ? { props: saved.assoc.props } : {}),
      // batch 2: saved with filters / quick filters / sort, the card loads its own list
      ...(saved?.assoc && listMode(saved) ? { list: saved.assoc } : {}),
      // Only once the layout loaded: saving over a layout that failed to load would replace it.
      // LD6: the gear opens the record page editor on this card, and Exit comes back here
      // (record-tabs.js:32, record-layout-editor.js:663-668).
      ...(canEditCards(me.role) && myLayout.status === 'ready'
        ? {
            onGear: () =>
              router.push(
                recordEditorHref({
                  object: 'company',
                  view: editorViewParam(myLayout.view),
                  card: id,
                  from: `/companies/${companyId}`,
                }),
              ),
          }
        : {}),
    };
  };
  // HUB-317: built-in fields the permission set hides (not shown) or makes view-only (locked).
  const access = useFieldAccess('company');
  const lockFor = (key: string) =>
    access.locked(key) ? { canEdit: false, lockedTitle: VIEW_ONLY_TITLE } : null;
  const prefs = useUserPrefs();
  // QA #352/#368: dates in the user's format and time zone, "--" when blank (as contacts, deals).
  const dates = useUserDates();
  const formatDate = dates.date;
  const formatDateTime = dates.dateTime;
  const router = useRouter();
  const [company, setCompany] = useState<Company | null>(null);
  /** Shown to admins (GET ?includeDeleted=true) when the company is soft-deleted. */
  const [deleted, setDeleted] = useState(false);
  const [restoring, setRestoring] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [tab, setTab] = useState<CenterTab>('catchup');
  // R9: the tabs from the layout, opened on `?tab=` or the layout's default (as the contact page,
  // R8a), and kept in `?tab=` (record-tabs.js:862, :917).
  const layoutTabApplied = useRef(false);
  const urlTab = useRef<CenterTab | null>(null);
  const urlTabRead = useRef(false);
  useEffect(() => {
    const q = new URLSearchParams(window.location.search).get('tab');
    const key = q ? tabKeyOf(q) : undefined;
    if (key) {
      layoutTabApplied.current = true;
      urlTab.current = key;
      setTab(key);
    }
    urlTabRead.current = true;
  }, []);
  useEffect(() => {
    if (!recordLayout?.defaultTab || layoutTabApplied.current) return;
    layoutTabApplied.current = true;
    const id = recordLayout.defaultTab;
    if (recordLayout.tabs.some((t) => t.id === id)) setTab(tabKeyOf(id));
  }, [recordLayout]);
  const layoutTabs = (recordLayout?.tabs ?? []).map((t) => [tabKeyOf(t.id), t.label] as const);
  const centerTabs: Array<readonly [CenterTab, string]> = layoutTabs.length
    ? layoutTabs
    : BUILT_IN_TABS;
  const centerTabKeys = centerTabs.map(([key]) => key).join(',');
  // A `?tab=` the page's tabs don't have falls back to the first tab, as the design.
  useEffect(() => {
    if (!urlTab.current || myLayout.status === 'loading') return;
    const keys = centerTabKeys.split(',') as CenterTab[];
    if (!keys.includes(urlTab.current)) setTab(keys[0] ?? 'catchup');
    urlTab.current = null;
  }, [myLayout.status, centerTabKeys]);
  const firstTab = centerTabs[0]?.[0];
  useEffect(() => {
    if (!urlTabRead.current || urlTab.current) return;
    const url = new URL(window.location.href);
    if (tab === firstTab) url.searchParams.delete('tab');
    else url.searchParams.set('tab', layoutIdOf(tab));
    if (url.href !== window.location.href) {
      window.history.replaceState(window.history.state, '', url);
    }
  }, [tab, firstTab]);
  /**
   * R10b: the open tab's cards and sections: its saved items, else the built-in ones
   * (`defaultLayout`, today's tab bodies). Fetches follow the cards it holds, not its key.
   */
  const openTabId = layoutIdOf(tab);
  const currentItems =
    (
      recordLayout?.tabs.find((t) => t.id === openTabId) ??
      BUILT_IN_COMPANY_LAYOUT.tabs.find((t) => t.id === openTabId)
    )?.items ?? [];
  const hasCard = (id: string) => currentItems.includes(id);
  /** R10b: closed sections, by `<tab id>|<index>` (open by default, not remembered). */
  const [closedSecs, setClosedSecs] = useState<Set<string>>(() => new Set());
  const [drawer, setOpenDrawer] = useState<Drawer | null>(null);
  const [taskOpen, setOpenTask] = useState(false);
  /**
   * CQS1 #715: the design's composer windows (record.php loads one for every object). The page
   * stays usable behind one, so anything opening here asks it first, as on Contacts; Task has its
   * own state here, so both go through one opener and one window is open at a time.
   */
  const composer = useRef<ComposerWindowHandle | null>(null);
  const openWindow = useRef<Drawer | 'task' | null>(null);
  const openAs = useCallback((next: Drawer | 'task' | null) => {
    if (next && composer.current?.holdOpen(next === openWindow.current)) return;
    openWindow.current = next;
    setOpenDrawer(next === 'task' ? null : next);
    setOpenTask(next === 'task');
  }, []);
  const setDrawer = useCallback((next: Drawer | null) => openAs(next), [openAs]);
  const setTaskOpen = useCallback((open: boolean) => openAs(open ? 'task' : null), [openAs]);
  /**
   * CQS1 #715: Edit and Delete have their own state here (drawers on Contacts): they ask the
   * composer too. False while it holds a draft (it shows the discard bar); else it closes.
   */
  const leaveComposer = () => {
    if (composer.current?.holdOpen(false)) return false;
    openAs(null);
    return true;
  };
  const [panel, setPanel] = useState<Panel | null>(null);
  // R2: More's Log SMS / LinkedIn / WhatsApp, the Clone form and Reorder activity buttons.
  const [commChannel, setCommChannel] = useState<CommunicationChannel>('linkedin_message');
  const [cloneOpen, setCloneOpen] = useState(false);
  const [reorderOpen, setReorderOpen] = useState(false);
  // R3: "View all properties" groups, labelled as the list pickers.
  const companyGroups = usePickerGroups('company', COMPANY_GROUPS);
  // R7: the associated record whose preview a sidebar row opened.
  const [previewTarget, setPreviewTarget] = useState<PreviewTarget>(null);
  // R4: the sticky header watches the quick actions in the left column.
  const leftColumnRef = useRef<HTMLElement>(null);
  const quickRowRef = useRef<HTMLDivElement>(null);
  const [buttonOrder, setButtonOrder] = useState<RecordActionButton[] | null>(null);
  const toast = useToast();
  const [editOpen, setEditOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [industryOptions, setIndustryOptions] = useState<CustomSelectOption[]>([]);
  const [callOutcomes, setCallOutcomes] = useState<PicklistOption[]>([]);
  const [customDefs, setCustomDefs] = useState<CustomPropertyDefinition[]>([]);
  /** B11: whether the definitions have loaded, so Missing data never says "has data" too early. */
  const [customDefsStatus, setCustomDefsStatus] = useState<'loading' | 'ok' | 'error'>('loading');
  const [custom, setCustom] = useState<Record<string, CustomUiValue>>({});
  const propertyLogic = usePropertyLogic('company');
  const [form, setForm] = useState({
    name: '',
    domain: '',
    website: '',
    phone: '',
    industry: '',
    city: '',
    state: '',
    country: '',
    ownerId: '',
  });

  const [activitySubTab, setActivitySubTab] = useState<ActivitySubTab>('activity');
  const [activitySearch, setActivitySearch] = useState('');
  const [activitySort, setActivitySort] = useState<'newest' | 'oldest'>('newest');
  const [activityDate, setActivityDate] = useState<ActivityDateFilter>('all');
  // R5a: as the contact page: Custom range, Team, and cards that expand and collapse.
  // R5b: several users and teams, and the Activity chip's types (null: the display settings).
  const [activityUserIds, setActivityUserIds] = useState<string[]>([]);
  const [activityFrom, setActivityFrom] = useState('');
  const [activityTo, setActivityTo] = useState('');
  const [activityTeamIds, setActivityTeamIds] = useState<string[]>([]);
  const [activityTypes, setActivityTypes] = useState<string[] | null>(null);
  const [teamOptions, setTeamOptions] = useState<Array<{ value: string; label: string }>>([]);
  const [collapsedIds, setCollapsedIds] = useState<Set<string>>(() => new Set());
  const [overviewTimeline, setOverviewTimeline] = useState<TimelineItem[]>([]);
  /** B11: whether the feed behind "Last activity date" has loaded, so empty isn't unknown. */
  const [overviewStatus, setOverviewStatus] = useState<'loading' | 'ok' | 'error'>('loading');
  /** B11: Catch-up's interactions (with when they loaded) and duplicate count. */
  const [catchup, setCatchup] = useState<{ state: InteractionsState; at: Date }>(() => ({
    state: { status: 'loading' },
    at: new Date(),
  }));
  const [duplicateCount, setDuplicateCount] = useState<DuplicateCount>({ status: 'loading' });
  const [refreshKey, setRefreshKey] = useState(0);
  const [taskTypes, setTaskTypes] = useState<PicklistOption[]>([]);
  /** Bumped after a task is created, to reload the Tasks card. */
  const [taskRefresh, setTaskRefresh] = useState(0);

  const isAdmin = me.role === 'admin';

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

  const closeTask = useCallback(() => setTaskOpen(false), [setTaskOpen]);
  /** MM1: which of More's create dialogs is open (contract, payment link, quote, invoice). */
  const [commerceKind, setCommerceKind] = useState<CommerceKind | null>(null);
  const closeCommerce = useCallback(() => setCommerceKind(null), []);

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

  useEffect(() => {
    void listPicklist('company', 'industry')
      .then((options) =>
        setIndustryOptions(options.map((o) => ({ value: o.value, label: o.label }))),
      )
      .catch(() => setIndustryOptions([]));
    // GLB3 (go-live Blocker 2): task types and call outcomes from one request (was two).
    listPicklistOptions({ objectType: 'activity' }).then(
      (options) => {
        setTaskTypes(options.filter((o) => o.field === 'taskType' && !o.archived));
        setCallOutcomes(options.filter((o) => o.field === 'callOutcome' && !o.archived));
      },
      () => setCallOutcomes([]),
    );
    listCustomProperties({ objectType: 'company' }).then(
      (defs) => {
        setCustomDefs(
          defs.filter((d) => !d.archived).sort((a, b) => a.displayOrder - b.displayOrder),
        );
        setCustomDefsStatus('ok');
      },
      () => {
        setCustomDefs([]);
        setCustomDefsStatus('error');
      },
    );
  }, []);

  // Overview needs a short recent-activity feed
  useEffect(() => {
    if (!company || deleted) return;
    let cancelled = false;
    (async () => {
      try {
        const page = await getCompanyTimeline(companyId, { limit: 10 });
        if (!cancelled) {
          setOverviewTimeline(page.data);
          setOverviewStatus('ok');
        }
      } catch {
        if (!cancelled) {
          setOverviewTimeline([]);
          setOverviewStatus('error');
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [company, companyId, deleted, refreshKey]);

  // B11: Catch-up's emails, calls and meetings, and this company's duplicate count. Loaded when
  // the tab first shows (it is the first tab) and again after an activity is logged
  // (`refreshKey`), not on every return to the tab; a load that failed or was cut off by leaving
  // the tab is tried again on the next visit.
  const hasCompany = Boolean(company);
  const onCatchup = CATCHUP_CARDS.some(hasCard) && hasCompany && !deleted;
  const catchupKey = `${companyId}|${refreshKey}`;
  const catchupLoaded = useRef<string | null>(null);
  useEffect(() => {
    if (!onCatchup || catchupLoaded.current === catchupKey) return;
    let cancelled = false;
    let done = 0;
    const loaded = () => {
      if (++done === 2) catchupLoaded.current = catchupKey;
    };
    setCatchup((c) => ({ ...c, state: { status: 'loading' } }));
    getCompanyTimeline(companyId, { types: 'email,call,meeting', limit: 20 }).then(
      (page) => {
        if (cancelled) return;
        const at = new Date();
        setCatchup({ state: { status: 'ok', list: interactionsOf(page.data, at) }, at });
        loaded();
      },
      () => {
        if (!cancelled) setCatchup({ state: { status: 'error' }, at: new Date() });
      },
    );
    setDuplicateCount({ status: 'loading' });
    recordDuplicateCount('company', companyId).then(
      (count) => {
        if (cancelled) return;
        setDuplicateCount({ status: 'ok', count });
        loaded();
      },
      () => {
        if (!cancelled) setDuplicateCount({ status: 'error' });
      },
    );
    return () => {
      cancelled = true;
    };
  }, [onCatchup, catchupKey, companyId]);

  /** R5a: the user, team and date filters, applied by the API (paging stays right). */
  const serverFilters = useMemo(
    () =>
      timelineServerFilters({
        date: activityDate,
        from: activityFrom,
        to: activityTo,
        userIds: activityUserIds,
        teamIds: activityTeamIds,
      }),
    [activityDate, activityFrom, activityTo, activityUserIds, activityTeamIds],
  );
  useEffect(() => {
    listTeamOptions().then(
      (res) => setTeamOptions(res.data.map((t) => ({ value: t.id, label: t.name }))),
      () => setTeamOptions([]),
    );
  }, []);
  const fetchTimeline = useCallback<TimelineFetch>(
    (params) => getCompanyTimeline(companyId, { ...params, ...serverFilters }),
    [companyId, serverFilters],
  );
  // R5b: the Activity chip, from the user's Activity display settings (as the contact page),
  // applies on every tab (raf.js:69-71); a sub-tab whose type is off shows nothing.
  const defaultTypes = prefs.timelineTypes;
  const chosenTypes = useMemo(
    () =>
      activityTypes ??
      (defaultTypes?.length
        ? ALL_TIMELINE_TYPES.filter((t) => defaultTypes.includes(t))
        : [...ALL_TIMELINE_TYPES]),
    [activityTypes, defaultTypes],
  );
  const typesParam = timelineTypesParam(ACTIVITY_TYPES[activitySubTab], chosenTypes);
  const noTypes = typesParam === null;
  const timelineTypes = typesParam ?? undefined;
  const timelineEnabled = Boolean(company) && !deleted && hasCard('activities') && !noTypes;
  const timelineReloadKey = `${refreshKey}|${company?.updatedAt ?? ''}|${JSON.stringify(serverFilters)}`;
  const timelineState = useRecordTimeline({
    fetchPage: fetchTimeline,
    types: timelineTypes,
    enabled: timelineEnabled,
    reloadKey: timelineReloadKey,
  });
  const timeline = noTypes ? NO_ITEMS : timelineState.items;
  const tabError = noTypes ? null : timelineState.error;
  /** G8: pinned items with the same types and filters as the timeline; search applies below. */
  const pinTypes = timelineTypes;
  const pinParams = useMemo(
    () => ({ ...(pinTypes ? { types: pinTypes } : {}), ...serverFilters }),
    [pinTypes, serverFilters],
  );
  const timelinePins = useTimelinePins({
    record: 'companies',
    recordId: companyId,
    params: pinParams,
    enabled: timelineEnabled,
    reloadKey: timelineReloadKey,
  });
  // G8: the activity list also waits for the pins, so a pinned item doesn't jump to the top.
  // R5b: nothing loads while the sub-tab's type is off (an empty list).
  const tabLoading = !noTypes && (timelineState.loading || !timelinePins.settled);
  const timelineEditing = useTimelineEditing({
    outcomes: callOutcomes,
    timeZone: prefs.timeZone,
    disabled: deleted,
    onUpdated: (item, patch) => {
      timelineState.updateItem(item.id, patch);
      timelinePins.patchItem(item.id, patch);
      setOverviewTimeline((cur) => cur.map((i) => (i.id === item.id ? { ...i, ...patch } : i)));
    },
    onDeleted: (item) => {
      timelineState.removeItem(item.id);
      timelinePins.dropItem(item.id);
      setOverviewTimeline((cur) => cur.filter((i) => i.id !== item.id));
    },
  });
  const { owners: ownerRows, error: ownersError } = useOwners(true, true);
  const ownerById = useMemo(() => new Map(ownerRows.map((o) => [o.userId, o])), [ownerRows]);
  /** HUB-315: the Merge flow (pick the other record, then review). */
  const [mergeOpen, setMergeOpen] = useState(false);
  /** HUB-356: the property history drawer's field (`all` for every field); null when closed. */
  const [historyField, setHistoryField] = useState<string | null>(null);
  const describeHistory = useMemo(
    () =>
      companyHistoryDescriber({
        defs: customDefs,
        owners: ownerRows,
        industries: industryOptions,
        // D10: date-times in the user's format and time zone, as Contacts' history.
        formatDateTime: dates.dateTime,
      }),
    [customDefs, ownerRows, industryOptions, dates],
  );
  /** A label of the About card with its history button. */
  const historyLabel = (label: string, field: string) => (
    <>
      {label}
      <PropertyHistoryButton label={label} onClick={() => setHistoryField(field)} />
    </>
  );

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

  const afterActivity = useCallback(() => {
    setDrawer(null);
    setTab('activity');
    setRefreshKey((k) => k + 1);
  }, [setDrawer]);

  const afterAssociation = useCallback(() => {
    setPanel(null);
    return load(true);
  }, [load]);

  const industryLabel = useMemo(() => {
    if (!company?.industry) return BLANK;
    return (
      industryOptions.find((o) => o.value === company.industry)?.label ??
      formatPicklistLabel(company.industry)
    );
  }, [company?.industry, industryOptions]);

  // The header shows the domain, as the design (companyHeaderLink); the "Website" rows show Website.
  const headerLink = company ? companyHeaderLink(company) : null;
  const subtitle = company ? companySubtitle(industryLabel, company.city, BLANK) : '';
  const websiteLabel = company?.website || company?.domain || null;

  const dealsTotal = useMemo(() => {
    if (!company?.deals.length) return null;
    const currency = company.deals[0]?.currency ?? 'USD';
    let sum = 0;
    let ok = true;
    for (const d of company.deals) {
      const n = d.amount != null ? Number(d.amount) : NaN;
      if (!Number.isFinite(n)) {
        ok = false;
        break;
      }
      sum += n;
    }
    return ok ? formatMoney(String(sum), currency) : null;
  }, [company]);

  const lastActivityAt = overviewTimeline[0]?.occurredAt ?? null;

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

  /** Whether an item stays in view under the filters and search (pinned items too, G8). */
  const activityMatches = useCallback(
    (item: TimelineItem) => {
      const q = activitySearch.trim().toLowerCase();
      if (activitySubTab === 'activity' && !inFeed(item)) return false;
      if (!q) return true;
      // GLB4: as the contact page's search: the item's title (subject, meeting and task titles),
      // body, call details and type, not only the sentence's facts.
      const text = [
        readableText(readable(item, readableCtx)),
        timelineBody(item, formatDate) ?? '',
        timelineTitle(item, 'Company created'),
      ]
        .join(' ')
        .toLowerCase();
      return text.includes(q) || String(item.type).includes(q);
    },
    [activitySearch, activitySubTab, readableCtx, formatDate],
  );

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

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

  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 [...map.entries()];
  }, [filteredTimeline, dates]);

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

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

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

  const loadedCustom = (def: CustomPropertyDefinition) =>
    company ? toUiValue(def, company.customProperties[def.name], prefs.timeZone) : '';
  // #354: edit drawer shows create-form fields (+ required extras), not every custom property.
  const [editFormFields, setEditFormFields] = useState<CreateFormField[]>(DEFAULT_COMPANY_FORM);
  useEffect(() => {
    getCreateForm('company').then(
      (form) => setEditFormFields(form.fields),
      () => setEditFormFields(DEFAULT_COMPANY_FORM),
    );
  }, []);
  const editCustomCandidates = useMemo(() => {
    const byName = new Map(customDefs.map((d) => [d.name, d]));
    const listed = editFormFields
      .filter((f) => f.field.startsWith('custom.'))
      .flatMap((f) => {
        const def = byName.get(f.field.slice('custom.'.length));
        return def && !def.readOnly && !def.calculated
          ? [{ ...def, required: def.required || f.required }]
          : [];
      });
    const extra = customDefs.filter(
      (d) => d.required && !d.readOnly && !d.calculated && !listed.some((l) => l.name === d.name),
    );
    return [...listed, ...extra];
  }, [customDefs, editFormFields]);
  // HUB-355: conditional property logic, on the values as edited so far.
  const shownDefs = applyPropertyLogic(
    editCustomCandidates,
    propertyLogic,
    Object.fromEntries(
      editCustomCandidates.map((d) => [d.name, custom[d.name] ?? loadedCustom(d)]),
    ),
  );

  // GLB4 (go-live Medium 3): Escape closes Edit company, as the design's drawers
  // (record-popups.js:87-90). A popover or menu inside it that handles Escape stops it first.
  useEffect(() => {
    if (!editOpen) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !e.defaultPrevented) setEditOpen(false);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [editOpen]);

  const openEdit = () => {
    if (!company || !leaveComposer()) return;
    setFormError(null);
    setCustom({});
    setForm({
      name: company.name,
      domain: company.domain ?? '',
      website: company.website ?? '',
      phone: company.phone ?? '',
      industry: company.industry ?? '',
      city: company.city ?? '',
      state: company.state ?? '',
      country: company.country ?? '',
      ownerId: company.owner?.id ?? '',
    });
    setEditOpen(true);
  };

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

  const showOwnerPicker = !ownersError && ownerRows.length > 0;
  const ownerOptions: CustomSelectOption[] = ownerRows
    .filter((o) => o.active || o.userId === company?.owner?.id)
    .map((o) => ({
      value: o.userId,
      label: o.active ? o.name : ownerDisplayName(o),
    }));
  if (company?.owner && !ownerOptions.some((o) => o.value === company.owner?.id)) {
    ownerOptions.push({
      value: company.owner.id,
      label: ownerRecordLabel({
        name: company.owner.name,
        status: company.owner.status,
      }),
    });
  }

  const onSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!company) return;
    if (!form.name.trim()) {
      setFormError('Company name is required.');
      return;
    }
    // Website and phone are only checked (and reformatted) when the user changes them, so a
    // migrated company with an unusual value can still be edited.
    const websiteChanged = (form.website.trim() || null) !== (company.website ?? null);
    const phoneChanged = (form.phone.trim() || null) !== (company.phone ?? null);
    const siteErr = websiteChanged && !access.locked('website') ? websiteError(form.website) : null;
    if (siteErr) {
      setFormError(siteErr);
      return;
    }
    const phoneErr = phoneChanged && !access.locked('phone') ? phoneError(form.phone) : null;
    if (phoneErr) {
      setFormError(phoneErr);
      return;
    }

    const customBody: NonNullable<UpdateCompanyBody['customProperties']> = {};
    // Hidden fields are left as they are.
    for (const def of shownDefs) {
      const ui = custom[def.name];
      if (ui === undefined || sameUiValue(ui, loadedCustom(def))) continue;
      const result = fromUiValue(def, ui, prefs.timeZone);
      if ('error' in result) {
        toast(result.error, 'danger');
        return;
      }
      if (result.value === null && def.required) {
        toast(`${def.label} is required`, 'danger');
        return;
      }
      customBody[def.name] = result.value;
    }

    setSaving(true);
    setFormError(null);
    const ownerId = form.ownerId || null;
    const body: UpdateCompanyBody = {
      updatedAt: company.updatedAt,
      name: form.name.trim(),
      domain: form.domain.trim() || null,
      website: websiteChanged ? normalizeWebsite(form.website) : (company.website ?? null),
      phone: phoneChanged ? form.phone.trim() || null : (company.phone ?? null),
      industry: form.industry.trim() || null,
      city: form.city.trim() || null,
      state: form.state.trim() || null,
      country: form.country.trim() || null,
      ...(showOwnerPicker && ownerId !== (company.owner?.id ?? null) ? { ownerId } : {}),
      ...(Object.keys(customBody).length ? { customProperties: customBody } : {}),
    };
    // HUB-317: fields the permission set locks are left as they are.
    for (const key of [
      'name',
      'domain',
      'website',
      'phone',
      'industry',
      'city',
      'state',
      'country',
      'ownerId',
    ] as const) {
      if (access.locked(key)) delete body[key];
    }
    try {
      const updated = await updateCompany(company.id, body);
      setCompany((prev) => keepMergedIds(prev, updated));
      setEditOpen(false);
    } catch (err) {
      setFormError(
        isApiError(err) && err.isConflict
          ? 'Someone else changed this, reload'
          : isApiError(err)
            ? err.message
            : 'Could not save changes.',
      );
    } finally {
      setSaving(false);
    }
  };

  // HUB-571 / HUB-382: Follow and the HubSpot Actions menu items (before the early returns).
  const tools = useRecordTools({
    // LD2: Restore activity opens the recycle bin, as the design.
    restoreDesign: true,
    recordType: 'company',
    recordId: companyId,
    name: company?.name ?? '',
    searchText: [company?.name, company?.domain].filter(Boolean).join(' '),
    canEdit:
      Boolean(company) &&
      !deleted &&
      scopeCovers(
        me.permissionSet.rules.objects.company.edit,
        company?.owner?.id,
        me,
        company?.sharedWithMe,
        company?.ownerFieldMatch,
      ),
    canLog: !deleted && me.role !== 'read_only',
    timeZone: prefs.timeZone,
    properties: () =>
      company
        ? Object.entries({
            'Company name': company.name,
            'Company domain name': company.domain ?? '',
            Website: company.website ?? '',
            Industry: company.industry ?? '',
            'Phone number': company.phone ?? '',
            City: company.city ?? '',
            'State/Region': company.state ?? '',
            'Country/Region': company.country ?? '',
            'Company owner': company.owner?.name ?? '',
            'Create date': company.createdAt,
            // G18: the companies merged into this one.
            [MERGED_IDS_LABEL.company]: mergedIdsText(company.mergedIds),
            // CB8 (CT-05): their domains, kept here.
            [ADDITIONAL_LABEL.company]: additionalText(company.additionalDomains),
            ...Object.fromEntries(
              Object.entries(company.customProperties ?? {}).map(([k, v]) => [
                k,
                Array.isArray(v) ? v.join(', ') : String(v ?? ''),
              ]),
            ),
          }).map(([label, value]) => ({ label, value }))
        : [],
    onChanged: () => {
      setRefreshKey((k) => k + 1);
      void load(true);
    },
    // R2: Clone opens the design's form on the record page too (CloneRecordDrawer).
    onClone: () => setCloneOpen(true),
    icon: (name) => <RecordToolIcon name={name} />,
    // G12: View record access as the 28 Oct design, saving the owner as the About card does.
    accessDesign: {
      variant: 'record',
      one: 'company',
      ownerLabel: 'Company owner',
      owner: company?.owner ? { id: company.owner.id, name: company.owner.name } : null,
      ...ownerLock({
        canEdit:
          Boolean(company) &&
          scopeCovers(
            me.permissionSet.rules.objects.company.edit,
            company?.owner?.id,
            me,
            company?.sharedWithMe,
            company?.ownerFieldMatch,
          ),
        deletedTitle: deleted ? 'This company is deleted' : null,
        viewOnlyTitle: access.locked('ownerId') ? VIEW_ONLY_TITLE : null,
      }),
      saveOwner: async (ownerId) => {
        if (!company) return;
        const saved = await updateCompany(company.id, { ownerId, updatedAt: company.updatedAt });
        setCompany((prev) => keepMergedIds(prev, saved));
      },
      loadHistory: (params) => getCompanyHistory(companyId, params),
      describe: describeHistory,
      reloadKey: company?.updatedAt,
    },
  });

  // R2: the copy is master's clone body (B4: owner, locked fields) with the form's values on top
  // (record-popups-hs.js:577), except fields this person may not set on create.
  const cloneCompany = async (v: Record<string, string>) => {
    if (!company) return;
    const locked = cloneLocked(me, customDefs);
    const body = cloneCompanyBody(company, { ownerId: cloneOwnerId(company, me), locked });
    body.name = v.name ?? body.name;
    for (const key of ['domain', 'industry', 'city', 'phone'] as const) {
      if (!locked(key)) body[key] = v[key] || null;
    }
    try {
      const copy = await createCompany(body);
      toast(`${body.name} was created`);
      setCloneOpen(false);
      router.push(`/companies/${copy.id}`);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
      throw err;
    }
  };

  if (loading) {
    return (
      <div className="company-details-body company-record-page">
        <p className="crm-text-body-secondary">Loading company…</p>
      </div>
    );
  }

  if (!company) {
    return (
      <div className="company-details-body company-record-page">
        <Alert tone="danger">{error ?? 'Company not found.'}</Alert>
        <Link className="link crm-mt-3 crm-d-inline-block" href="/companies">
          Back to companies
        </Link>
      </div>
    );
  }

  const contactsCount = company.contactsCount ?? company.contacts.length;
  const dealsCount = company.deals?.length ?? 0;
  const companyLink = { type: 'company' as const, id: company.id };
  const noteAssociations = [
    ...company.contacts.map((c) => asContactAssoc({ id: c.id, name: c.name, email: c.email })),
    ...company.deals.map(asDealAssoc),
  ];
  const primaryContact = company.contacts.find((c) => c.email) ?? company.contacts[0] ?? null;
  // CQS1D: the dialer calls one of the company's contacts, as the design names the record's
  // contacts (activity-composer.js:1242): the first with a phone, else the primary one; the
  // company's own number when none has one.
  const dialContact = company.contacts.find((c) => c.phone) ?? primaryContact;
  const recipientOptions = (() => {
    const seen = new Set<string>();
    const options: Array<{ value: string; label: string; contactId: string }> = [];
    for (const c of company.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;
  })();
  const canLog = !deleted && me.role !== 'read_only';
  const logTitle = deleted
    ? 'This company is deleted'
    : canLog
      ? undefined
      : "Your permissions don't allow you to log activity";
  const activityAdd = activityTabAddAction(activitySubTab);
  const activityLog = activityTabLogAction(activitySubTab);
  const openActivityAdd = () => {
    if (!activityAdd) return;
    if (activityAdd.kind === 'task') setTaskOpen(true);
    else setDrawer(activityAdd.kind);
  };
  const openActivityLog = () => {
    if (!activityLog) return;
    setDrawer(activityLog.kind);
  };
  const rule = me.permissionSet.rules.objects.company;
  // `team` (HUB-322): records of the user's team too.
  // P2a: Delete and Merge follow their own scopes on this record (`recordRights`).
  const rights = recordRights(
    rule,
    company.owner?.id,
    me,
    company.sharedWithMe,
    company.ownerFieldMatch,
  );
  const canEdit = !deleted && rights.edit;
  const canDelete = !deleted && rights.delete;
  const canMerge = !deleted && rights.merge;
  // PB7: the Playbooks card's rows open the playbook dialog on this company. Logging needs edit
  // access on the company (the API's `assertLinkedRecordsEditable`).
  const playbookRun: PlaybookRunContext = {
    record: {
      objectType: 'company',
      id: company.id,
      name: company.name,
      canLog: canLog && canEdit,
      links: {
        contact: company.contacts.map((c) => ({ id: c.id, name: c.name })),
        deal: company.deals.map((d) => ({ id: d.id, name: d.name })),
      },
      values: company.customProperties ?? {},
    },
    snippetTarget: { companyId: company.id },
    onLogged: () => {
      afterActivity();
      setTaskRefresh((k) => k + 1);
      void load(true);
    },
  };
  const editTitle = deleted
    ? 'This company is deleted'
    : canEdit
      ? undefined
      : "Your permissions don't allow you to edit this record";
  /** HUB-615: save one in-place edit (PATCH with the loaded `updatedAt`) and show the result. */
  const saveCompany = async (body: UpdateCompanyBody) => {
    const saved = await updateCompany(company.id, { ...body, updatedAt: company.updatedAt });
    setCompany((prev) => keepMergedIds(prev, saved));
  };
  const customEdit: CustomFieldsEdit = {
    canEdit,
    lockedTitle: editTitle,
    timeZone: prefs.timeZone,
    formatDateTime: dates.dateTime,
    onSave: (name, value) => saveCompany({ customProperties: { [name]: value } }),
  };
  /** A migrated HubSpot field shown in the About card (design), when this business has it. */
  const aboutCustomField = (name: string) => {
    const def = customDefs.find((d) => d.name === name);
    return def ? (
      <CustomFieldsList
        defs={[def]}
        values={company.customProperties}
        edit={customEdit}
        onHistory={(field) => setHistoryField(customHistoryField(field))}
      />
    ) : null;
  };
  const companyTextEdit = (
    field: 'domain' | 'city' | 'state' | 'country' | 'phone',
    label: string,
    max: number,
  ) => (
    <InlineEdit<string>
      label={label}
      display={company[field] ?? BLANK}
      canEdit={lockFor(field)?.canEdit ?? canEdit}
      lockedTitle={lockFor(field)?.lockedTitle ?? editTitle}
      initial={() => company[field] ?? ''}
      renderInput={(input) => (
        <InlineTextInput {...input} type={field === 'phone' ? 'tel' : 'text'} maxLength={max} />
      )}
      onSave={async (raw) => {
        if (field === 'phone') {
          const phone = inlinePhoneValue(raw, company.phone ?? null);
          if (phone !== undefined) await saveCompany({ phone });
          return;
        }
        const next =
          (field === 'domain'
            ? raw
                .trim()
                .replace(/^https?:\/\//i, '')
                .replace(/\/.*$/, '')
            : raw.trim()) || null;
        if (next === (company[field] ?? null)) return;
        await saveCompany({ [field]: next });
      }}
    />
  );
  const deleteTitle = deleted
    ? 'This company is deleted'
    : canDelete
      ? undefined
      : "Your permissions don't allow you to delete this record";

  // R1: the design's row, Task included (record-popups-hs.js:985-986), with its tooltips
  // (BUTTON_TITLES). R2: in the user's saved order, one order for every record page, as the
  // design keeps one (`crm.preview.qa`, record-popups-hs.js:984). Task opens the task drawer,
  // which has its own state (`taskOpen`).
  const buttonKeys = buttonOrder ?? prefs.recordActionButtons;
  // CQS1D: Call opens the dialer, as the design (record.php:344, record-popups-hs.js:979) and
  // Contacts (C9b); Log a call stays in More and the sticky menu.
  const openQuick = (key: RecordActionButton) =>
    key === 'task' ? setTaskOpen(true) : setDrawer(key === 'call' ? 'dial' : key);

  // 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] : [];
  };
  // The page has its own "View all properties" (with field labels).
  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'),
  };
  // R2: the design's Actions menu, in its order and groups (record.php:299-323). Summarize (AI)
  // and Export (a design stub) are left out; Edit company is master's own, kept last.
  // Log a communication and Log postal mail moved to More (`moreItems`).
  const actions: ContactAction[] = [
    ...toolAction('follow'),
    { ...propertiesAction, separated: true },
    historyAction,
    ...toolAction('association-history', true),
    ...toolAction('review-associations'),
    ...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: !canMerge,
      title: canMerge ? undefined : MERGE_DENIED_TITLE,
    },
    ...toolAction('clone'),
    {
      key: 'delete',
      label: 'Delete',
      icon: <ActionIcon d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />,
      onSelect: () => {
        if (leaveComposer()) setPanel('delete');
      },
      disabled: !canDelete,
      title: deleteTitle,
    },
    {
      key: 'edit',
      label: 'Edit company',
      icon: <ActionIcon d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />,
      onSelect: openEdit,
      disabled: !canEdit,
      title: editTitle,
      separated: true,
    },
  ];
  // R2: the About card's Actions (record-tabs.js:235). LD6: Customize properties opens the record
  // page editor on About (record.php:433; manage_settings only). Fill smart properties (AI) is
  // left out.
  const aboutActions: ContactAction[] = [
    ...(me.permissionSet.rules.app.manage_settings
      ? [
          {
            key: 'customize-properties',
            label: 'Customize properties',
            icon: <ActionIcon d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />,
            // LD6: the editor on About, with no `from`, as record.php:433.
            onSelect: () =>
              router.push(
                recordEditorHref({
                  object: 'company',
                  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');
  };
  // R2: More's activities, in the design's order (record-popups-hs.js:982-986): any button not
  // in the row, then the logs a company has on master. Enroll in a sequence, Engage on LinkedIn
  // and Create a WhatsApp message are contact actions on master, so they are left out here.
  // R4: the sticky header's "Create activities" (record.php:365-372); companies have no dialer,
  // so no "Make a call".
  const stickyItem = (
    key: string,
    label: string,
    kind: 'note' | 'email' | 'call' | 'task' | 'meeting',
    open: () => void,
  ): ContactAction => ({
    key,
    label,
    icon: <QuickActionIcon kind={kind} />,
    onSelect: open,
    disabled: !canLog,
    title: logTitle,
  });
  const stickyActivities: ContactAction[] = [
    stickyItem('s-note', 'Create note', 'note', () => setDrawer('note')),
    stickyItem('s-email', 'Create email', 'email', () => setDrawer('email')),
    stickyItem('s-log-email', 'Log email', 'email', () => setDrawer('log-email')),
    // CQS1D: the design's "Make a call" (record.php:368), as Contacts.
    stickyItem('s-dial', 'Make a call', 'call', () => setDrawer('dial')),
    stickyItem('s-call', 'Log call', 'call', () => setDrawer('call')),
    stickyItem('s-task', 'Create task', 'task', () => setTaskOpen(true)),
    stickyItem('s-meeting', 'Schedule meeting', 'meeting', () => setDrawer('meeting')),
    stickyItem('s-log-meeting', 'Log meeting', 'meeting', () => setDrawer('log-meeting')),
  ];
  // MM1: the design's current order and icons (record-popups-hs.js:969-997 on
  // design.admedia.com, 20 Nov 2026): Create a contract / payment link / quote / invoice first.
  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: <QuickActionIcon kind={key} />,
        onSelect: () => openQuick(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')),
  ];

  // R3: the header's name editor and the About card's editable rows, by key, so the
  // About card and "View all properties" (AllPropertiesDesignDrawer) render the same nodes.
  const nameEdit = (
    <InlineEdit<string>
      label="Company name"
      display={company.name}
      canEdit={lockFor('name')?.canEdit ?? canEdit}
      lockedTitle={lockFor('name')?.lockedTitle ?? editTitle}
      initial={() => company.name}
      renderInput={(input) => <InlineTextInput {...input} maxLength={191} />}
      onSave={async (raw) => {
        const next = raw.trim();
        if (!next) throw new Error('Company name is required');
        if (next === company.name) return;
        await saveCompany({ name: next });
      }}
    />
  );
  /**
   * LD3: the name popover's fields (record.php:121-128): Company name, Company domain name,
   * Industry (with Details; a select, as master stores a picklist value) and City. Hidden fields
   * are left out, locked ones read-only.
   */
  const nameFields: NameField[] = [
    {
      key: 'name',
      label: 'Company name',
      value: company.name,
      maxLength: 191,
      lockedTitle: lockFor('name')?.lockedTitle,
    },
    ...(access.hidden('domain')
      ? []
      : [
          {
            key: 'domain',
            label: 'Company domain name',
            value: company.domain ?? '',
            maxLength: 191,
            lockedTitle: lockFor('domain')?.lockedTitle,
          },
        ]),
    ...(access.hidden('industry')
      ? []
      : [
          {
            key: 'industry',
            label: 'Industry',
            value: company.industry ?? '',
            kind: 'select' as const,
            options: industryOptions.map((o) => ({ value: o.value, label: String(o.label) })),
            lockedTitle: lockFor('industry')?.lockedTitle,
            details: true,
          },
        ]),
    ...(access.hidden('city')
      ? []
      : [
          {
            key: 'city',
            label: 'City',
            value: company.city ?? '',
            maxLength: 100,
            lockedTitle: lockFor('city')?.lockedTitle,
          },
        ]),
  ];
  /** LD3: one name field saved alone; Company name is required. */
  const saveNameField = async (key: string, value: string) => {
    if (key === 'name' && !value) throw new Error('Company name is required');
    await saveCompany({ [key]: key === 'name' ? value : value || null } as UpdateCompanyBody);
  };
  const companyAbout: Record<string, ReactNode> = {
    domain: (
      <>
        {access.hidden('domain') ? null : (
          <AboutRow label={historyLabel('Company domain name', 'domain')}>
            {companyTextEdit('domain', 'Company domain name', 191)}
          </AboutRow>
        )}
      </>
    ),
    industry: (
      <>
        {access.hidden('industry') ? null : (
          <AboutRow label={historyLabel('Industry', 'industry')}>
            <InlineEdit<string>
              label="Industry"
              saveOn="change"
              dropdown
              display={industryLabel}
              canEdit={lockFor('industry')?.canEdit ?? canEdit}
              lockedTitle={lockFor('industry')?.lockedTitle ?? editTitle}
              initial={() => company.industry ?? ''}
              renderInput={(input) => (
                <InlineSelectInput
                  {...input}
                  emptyLabel={BLANK}
                  options={picklistChoices(industryOptions, company.industry)}
                />
              )}
              onSave={async (value) => {
                if ((value || null) === (company.industry ?? null)) return;
                await saveCompany({ industry: value || null });
              }}
            />
          </AboutRow>
        )}
      </>
    ),
    ownerId: (
      <>
        <AboutRow label={historyLabel('Company owner', 'ownerId')}>
          <InlineEdit<string>
            label="Company owner"
            saveOn="change"
            dropdown
            display={ownerLabelFromCache(company.owner, ownerById)}
            canEdit={lockFor('ownerId')?.canEdit ?? canEdit}
            lockedTitle={lockFor('ownerId')?.lockedTitle ?? editTitle}
            initial={() => company.owner?.id ?? ''}
            renderInput={(input) => (
              <InlineSelectInput
                {...input}
                emptyLabel="No owner"
                options={ownerChoices(ownerRows, company.owner)}
              />
            )}
            onSave={async (value) => {
              if ((value || null) === (company.owner?.id ?? null)) return;
              await saveCompany({ ownerId: value || null });
            }}
          />
        </AboutRow>
      </>
    ),
    city: (
      <>
        {access.hidden('city') ? null : (
          <AboutRow label={historyLabel('City', 'city')}>
            {companyTextEdit('city', 'City', 100)}
          </AboutRow>
        )}
      </>
    ),
    state: (
      <>
        {access.hidden('state') ? null : (
          <AboutRow label={historyLabel('State/Region', 'state')}>
            {companyTextEdit('state', 'State/Region', 100)}
          </AboutRow>
        )}
      </>
    ),
    country: (
      <>
        {access.hidden('country') ? null : (
          <AboutRow label={historyLabel('Country/Region', 'country')}>
            {companyTextEdit('country', 'Country/Region', 100)}
          </AboutRow>
        )}
      </>
    ),
    phone: (
      <>
        {access.hidden('phone') ? null : (
          <AboutRow label={historyLabel('Phone number', 'phone')}>
            {companyTextEdit('phone', 'Phone number', 50)}
          </AboutRow>
        )}
      </>
    ),
  };

  // R3: "View all properties" rows. Built-in fields in "Company information" (as the list
  // pickers), edited with the About card's editors (`companyAbout`, `nameEdit`); custom fields
  // in their groups. Hidden fields are left out (`access.hidden`).
  const builtInRow = (
    key: string,
    label: string,
    text: string,
    node?: ReactNode,
    history = true,
  ): PropertyRow[] =>
    access.hidden(key)
      ? []
      : [
          {
            key,
            label,
            group: COMPANY_INFO,
            text,
            node: node ?? <AboutRow label={label}>{text || BLANK}</AboutRow>,
            onHistory: history ? () => setHistoryField(key) : undefined,
          },
        ];
  const propertyRows: PropertyRow[] = [
    ...builtInRow(
      'name',
      'Company name',
      company.name,
      <AboutRow label="Company name">{nameEdit}</AboutRow>,
    ),
    ...builtInRow('domain', 'Company domain name', company.domain ?? '', companyAbout.domain),
    ...builtInRow('website', 'Website', company.website ?? '', undefined, false),
    ...builtInRow(
      'industry',
      'Industry',
      industryLabel === BLANK ? '' : industryLabel,
      companyAbout.industry,
    ),
    ...builtInRow('phone', 'Phone number', company.phone ?? '', companyAbout.phone),
    ...builtInRow('city', 'City', company.city ?? '', companyAbout.city),
    ...builtInRow('state', 'State/Region', company.state ?? '', companyAbout.state),
    ...builtInRow('country', 'Country/Region', company.country ?? '', companyAbout.country),
    ...builtInRow('ownerId', 'Company owner', company.owner?.name ?? '', companyAbout.ownerId),
    ...builtInRow('createdAt', 'Create date', formatDate(company.createdAt), undefined, false),
    // G18: the companies merged into this one.
    ...builtInRow(
      'mergedIds',
      MERGED_IDS_LABEL.company,
      mergedIdsText(company.mergedIds),
      undefined,
      false,
    ),
    // CB8 (CT-05): domains of the companies merged into this one; read-only, hidden with Domain.
    ...(access.hidden('domain')
      ? []
      : builtInRow(
          'additionalDomains',
          ADDITIONAL_LABEL.company,
          additionalText(company.additionalDomains),
          undefined,
          false,
        )),
    ...customDefs.map((d) => ({
      key: `custom.${d.name}`,
      label: d.label,
      group: (d.groupName && companyGroups.labelOf(d.groupName)) || 'Other properties',
      text: describeHistory(customHistoryField(d.name)).text(company.customProperties?.[d.name]),
      node: (
        <CustomFieldsList defs={[d]} values={company.customProperties ?? {}} edit={customEdit} />
      ),
      onHistory: () => setHistoryField(customHistoryField(d.name)),
    })),
  ];

  /** One timeline card; `pinned` cards sit above the dated list (G8). */
  const canPin = canEdit && timelinePins.ready;
  const renderTimelineCard = (item: TimelineItem, pinned: boolean) => {
    const r = readable(item, readableCtx);
    // R5a: each card expands and collapses, as the contact page's (activity-tabs.js:453-461).
    const collapsed = collapsedIds.has(item.id);
    const toggle = () =>
      setCollapsedIds((prev) => {
        const next = new Set(prev);
        if (next.has(item.id)) next.delete(item.id);
        else next.add(item.id);
        return next;
      });
    return (
      <div key={item.id} className="company-timeline-item">
        <EventIcon type={item.type} />
        <div
          className={cn(
            'company-timeline-card',
            pinned && 'is-pinned',
            collapsed && 'is-collapsed',
          )}
        >
          {pinned ? <PinnedBadge /> : null}
          <div className="company-timeline-meta">
            <strong
              className="company-timeline-toggle"
              role="button"
              tabIndex={0}
              aria-expanded={!collapsed}
              onClick={toggle}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  toggle();
                }
              }}
            >
              <svg
                className="crm-activity-card__chevron"
                viewBox="0 0 24 24"
                aria-hidden
                style={{
                  width: 14,
                  height: 14,
                  stroke: 'currentColor',
                  fill: 'none',
                  strokeWidth: 2,
                  marginRight: 4,
                  transform: collapsed ? 'rotate(-90deg)' : undefined,
                }}
              >
                <path d="m6 9 6 6 6-6" />
              </svg>
              {r.title}
            </strong>
            {canPin && isPinnable(item) ? (
              <span className="crm-pin-end">
                <TimelinePinToggle
                  pinned={pinned}
                  busy={timelinePins.busyId === item.id}
                  onToggle={() => void timelinePins.toggle(item, pinned)}
                />
                <span>{formatDateTime(item.occurredAt)}</span>
              </span>
            ) : (
              <span>{formatDateTime(item.occurredAt)}</span>
            )}
          </div>
          {collapsed ? null : (
            <>
              <ReadableBody r={r} />
              {timelineEditing.actions(item)}
            </>
          )}
        </div>
      </div>
    );
  };

  /** Right sidebar cards in the layout's order (cards it doesn't list are hidden); else built in. */
  /** R9: the left cards in the layout's order; About is always shown (it holds the actions). */
  const orderedLeft = (order: string[] | undefined, cards: Record<string, ReactNode>) => {
    const ids = order ?? Object.keys(cards);
    return (ids.includes('about') ? ids : ['about', ...ids]).map((key) =>
      key in cards ? <Fragment key={key}>{cards[key]}</Fragment> : null,
    );
  };
  /** R9: the About rows, by layout key; `custom.<name>` rows are the custom fields. */
  const aboutRows: Record<string, ReactNode> = {
    ...companyAbout,
    additionalOwners: (
      <AboutRow label="Additional owners">
        <AdditionalOwnersEdit
          current={company.additionalOwners}
          owners={ownerRows}
          canEdit={canEdit}
          lockedTitle={editTitle}
          onSave={(ids) => saveCompany({ additionalOwnerIds: ids })}
        />
      </AboutRow>
    ),
    contacts: <AboutRow label="Number of associated contacts">{String(contactsCount)}</AboutRow>,
    lastActivity: <AboutRow label="Last activity date">{formatDateTime(lastActivityAt)}</AboutRow>,
    createdAt: <AboutRow label="Create date">{formatDate(company.createdAt)}</AboutRow>,
    source: <AboutRow label="Record source">{formatPicklistLabel(company.source)}</AboutRow>,
  };
  /** R9: the layout's About rows, else the 17 shown before R9 (point 59, `defaultLayout`). */
  const aboutOrder = recordLayout?.cards.about?.props?.length
    ? recordLayout.cards.about.props
    : (defaultLayout('company').cards.about?.props ?? []);
  const propValues = Object.fromEntries(propertyRows.map((r) => [r.key, r.text]));
  /**
   * R10d: whether a tab or card shows under the layout's conditional logic (record-tabs.js:20-27).
   * A rule tests the property's shown text and its stored value.
   */
  const condValue = (prop: string): string[] =>
    recordTexts(
      propValues[prop],
      prop.startsWith('custom.')
        ? company.customProperties?.[prop.slice('custom.'.length)]
        : (company as unknown as Record<string, unknown>)[prop],
    );
  const condShows = (key: string) => condOk(recordLayout?.cond, key, condValue);
  /** R10c: a left property card (record-tabs.js:228-237): the About rows of its properties, the gear. */
  const leftPropCard = (id: string) => {
    const conf = recordLayout?.cards[id];
    const title = conf?.title || 'Untitled card';
    return (
      <CollapsibleCard
        title={title}
        cardId={id}
        defaultOpen
        action={withCardGear(null, cardView(id).onGear, title)}
      >
        <div className="crm-about-contact">
          {(conf?.props ?? []).map((k) => (
            <Fragment key={k}>
              {aboutRows[k] ??
                (k.startsWith('custom.') ? aboutCustomField(k.slice('custom.'.length)) : null)}
            </Fragment>
          ))}
        </div>
      </CollapsibleCard>
    );
  };
  const KNOWN_LEFT = ['about', 'company-info', 'groups'];
  const extraLeft: Record<string, ReactNode> = Object.fromEntries(
    (recordLayout?.left ?? [])
      .filter((id) => !KNOWN_LEFT.includes(id) && recordLayout?.cards[id]?.props)
      .map((id) => [id, leftPropCard(id)]),
  );
  /** R10c: a property card in a tab (record-tabs.js:217-219): label / value rows, or a highlight grid. */
  const centerPropCard = (id: string) => {
    const conf = recordLayout?.cards[id];
    if (!conf?.props) return null;
    const title = conf.title || 'Untitled card';
    const rows = conf.props.flatMap((k) => {
      const row = propertyRows.find((r) => r.key === k);
      return row ? [{ key: k, label: row.label, value: row.text }] : [];
    });
    const highlight = cardDef(id, title, 'company').props?.highlight;
    return (
      <section className="rt-card company-about-card" data-rt-card={id}>
        <header className="rt-card__head">
          <h3>{title}</h3>
          <span className="rt-card__acts">{withCardGear(null, cardView(id).onGear, title)}</span>
        </header>
        <div className="rt-card__body">
          {highlight ? (
            <dl className="rt-grid3">
              {rows.map((r) => (
                <div key={r.key}>
                  <dt>{r.label.toUpperCase()}</dt>
                  <dd>{r.value || BLANK}</dd>
                </div>
              ))}
            </dl>
          ) : (
            <div className="crm-about-contact">
              {rows.map((r) => (
                <div key={r.key} className="crm-about-field rp-field">
                  <div className="crm-about-label">{r.label}</div>
                  <div className="crm-about-value">{r.value || BLANK}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    );
  };
  /** Custom fields About shows stay out of the property group cards (as before R9). */
  /**
   * R9: the Company profile card (record-tabs.js:172-176): the layout's `profile.props`, else the
   * design's six (record-layout.js:158), with master's values. Hidden fields are left out.
   */
  const PROFILE_FIELDS: Record<string, { label: string; hidden: string | null; value: string }> = {
    city: { label: 'City', hidden: 'city', value: company.city ?? '' },
    street_address: {
      label: 'Street address',
      hidden: null,
      value: String(company.customProperties?.address ?? ''),
    },
    postal_code: {
      label: 'Postal code',
      hidden: null,
      value: String(company.customProperties?.zip ?? ''),
    },
    state_region: { label: 'State/Region', hidden: 'state', value: company.state ?? '' },
    country_region: { label: 'Country/Region', hidden: 'country', value: company.country ?? '' },
    industry: {
      label: 'Industry',
      hidden: 'industry',
      value: industryLabel === BLANK ? '' : industryLabel,
    },
  };
  const profileKeys = recordLayout?.cards.profile?.props?.length
    ? recordLayout.cards.profile.props
    : ['city', 'street_address', 'postal_code', 'state_region', 'country_region', 'industry'];
  const profileRows = profileKeys.flatMap((key) => {
    const f = PROFILE_FIELDS[key];
    if (f)
      return f.hidden && access.hidden(f.hidden) ? [] : [{ key, label: f.label, value: f.value }];
    const row = propertyRows.find((r) => r.key === key);
    return row ? [{ key, label: row.label, value: row.text }] : [];
  });
  const aboutCustomNames = new Set(
    aboutOrder.filter((k) => k.startsWith('custom.')).map((k) => k.slice('custom.'.length)),
  );
  const orderedRight = (order: string[] | undefined, cards: Record<string, ReactNode>) =>
    (order ?? Object.keys(cards)).map((key) =>
      key in cards ? <Fragment key={key}>{cards[key]}</Fragment> : null,
    );
  /** One association card by layout id; a clone (`<id>~<n>`) draws as its card. */
  const assocCard = (id: string, which: 'contacts' | 'related' | 'deals') => (
    <CompanyAssociations
      company={company}
      canEdit={canEdit}
      onChanged={afterAssociation}
      only={which}
      cards={{ [which]: cardView(id) }}
      dateText={formatDate}
      onPreview={setPreviewTarget}
    />
  );
  const ASSOC_BY_ID: Record<string, 'contacts' | 'related' | 'deals'> = {
    'r-contacts': 'contacts',
    'r-related': 'related',
    'r-deals': 'deals',
  };
  const cloneCards = Object.fromEntries(
    (recordLayout?.right ?? []).flatMap((id) => {
      const which = id.includes('~') ? ASSOC_BY_ID[baseCardId(id)] : undefined;
      return which ? [[id, assocCard(id, which)] as const] : [];
    }),
  );

  /** R10b: one middle-column card by id (record-tabs.js `CARDS`); unknown ids draw nothing. */
  const centerCard = (id: string): ReactNode => {
    switch (id) {
      case 'profile':
        return (
          <>
            {/* R9: the design's Company profile card (record-tabs.js:172-176). */}
            <section className="rt-card company-about-card" data-rt-card="profile">
              <header className="rt-card__head">
                <h3>Company profile</h3>
                <span className="rt-card__acts">
                  {me.permissionSet.rules.app.manage_settings ? (
                    <Link
                      className="rt-gear"
                      href="/settings/objects?object=company&tab=record"
                      aria-label="Edit Company profile card"
                      title="Edit card"
                    >
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        aria-hidden="true"
                      >
                        <circle cx="12" cy="12" r="3" />
                        <path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z" />
                      </svg>
                    </Link>
                  ) : null}
                </span>
              </header>
              <div className="rt-card__body">
                <dl className="rt-grid3">
                  {profileRows.map((row) => (
                    <div key={row.key}>
                      <dt>{row.label}</dt>
                      <dd>{row.value || BLANK}</dd>
                    </div>
                  ))}
                </dl>
              </div>
            </section>
          </>
        );
      case 'summary':
        return (
          <div className="company-overview-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
            <div className="company-overview-card">
              <span>Open deals</span>
              <strong>{dealsTotal ?? (dealsCount === 0 ? '0' : String(dealsCount))}</strong>
              <small>
                {dealsCount === 0
                  ? 'No active deals'
                  : `${dealsCount} linked deal${dealsCount === 1 ? '' : 's'}`}
              </small>
            </div>
            <div className="company-overview-card">
              <span>Contacts</span>
              <strong>{contactsCount}</strong>
              <small>
                {contactsCount === 0
                  ? 'No linked contacts'
                  : `${contactsCount} linked contact${contactsCount === 1 ? '' : 's'}`}
              </small>
            </div>
            <div className="company-overview-card">
              <span>Last activity</span>
              <strong style={{ fontSize: 13 }}>{formatDateTime(lastActivityAt)}</strong>
              <small>{lastActivityAt ? 'Most recent timeline event' : 'No activity yet'}</small>
            </div>
          </div>
        );
      case 'recent':
        return (
          <div className="company-overview-section">
            <div className="company-card-head">
              <h2>Recent activity</h2>
              <button
                type="button"
                className="company-view-link"
                style={{
                  marginTop: 0,
                  background: 'none',
                  border: 0,
                  padding: 0,
                  cursor: 'pointer',
                }}
                onClick={() => setTab('activity')}
              >
                View all
              </button>
            </div>
            {overviewTimeline.length === 0 ? (
              <p className="company-muted">No activity yet for this company.</p>
            ) : (
              <div className="company-mini-timeline">
                {overviewTimeline
                  .filter(inFeed)
                  .slice(0, 5)
                  .map((item) => {
                    const r = readable(item, readableCtx);
                    return (
                      <article key={item.id}>
                        <EventIcon type={item.type} />
                        <div>
                          <strong>{r.title}</strong>
                          <ReadableBody r={r} />
                          <small>{formatDateTime(item.occurredAt)}</small>
                        </div>
                      </article>
                    );
                  })}
              </div>
            )}
          </div>
        );
      case 'leadscore':
        return (
          <section className="rt-card company-about-card" data-rt-card="leadscore">
            <header className="rt-card__head">
              <h3>Lead Score</h3>
            </header>
            <div className="rt-card__body">
              <p>This company is not being scored.</p>
              {canEditPropertySettings(me) ? (
                <p className="rt-right">
                  <a
                    className="rt-link"
                    href="/settings/properties?object=company"
                    target="_blank"
                    rel="noopener"
                  >
                    Learn more ↗
                  </a>
                </p>
              ) : null}
            </div>
          </section>
        );
      case 'activities':
        return deleted ? (
          <div className="companies-empty">
            <h3>This company is deleted</h3>
            <p>Restore it to see its activity.</p>
          </div>
        ) : (
          <div>
            {/* R5a: the shared type tabs, as the contact page (TimelineTypeTabs). */}
            <TimelineTypeTabs
              tabs={ACTIVITY_SUB_TABS}
              active={activitySubTab}
              onChange={(next) => {
                // R1: another sub-tab empties the search (activity-tabs.js:389).
                setActivitySubTab(next);
                setActivitySearch('');
              }}
              label="Company activity types"
              keys
              // GLB4: the design's tab sizing, so Meetings fits at 1280px (company-details.css).
              className="company-activity-tabs"
            />

            <div className="crm-activity-toolbar">
              <div className="crm-activity-search">
                <SearchIcon />
                <input
                  type="search"
                  placeholder={activityTabSearchPlaceholder(activitySubTab)}
                  value={activitySearch}
                  onChange={(e) => setActivitySearch(e.target.value)}
                  aria-label={activityTabSearchPlaceholder(activitySubTab)}
                />
              </div>
              {/* R5b: the design's "Expand all ▾" menu (raf.js:92, :208-213). */}
              <div className="crm-activity-toolbar__actions">
                <TimelineExpandMenu
                  onCollapseAll={() =>
                    setCollapsedIds(
                      new Set([
                        ...shownPins.map((p) => p.itemId),
                        ...filteredTimeline.map((i) => i.id),
                      ]),
                    )
                  }
                  onExpandAll={() => setCollapsedIds(new Set())}
                />
              </div>
            </div>

            {/* R5b: the design's filter row under the search (raf.js:93-114). */}
            <TimelineFilterChips
              types={chosenTypes}
              onTypes={setActivityTypes}
              date={activityDate}
              from={activityFrom}
              to={activityTo}
              onDate={(d, f, t) => {
                setActivityDate(d);
                setActivityFrom(f);
                setActivityTo(t);
              }}
              userIds={activityUserIds}
              onUsers={setActivityUserIds}
              owners={ownerRows}
              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={openActivityLog}
                />
              ) : null}
              {activityAdd ? (
                <ActivityTabAddButton
                  kind={activityAdd.kind}
                  label={activityAdd.label}
                  disabled={!canLog}
                  title={logTitle}
                  onClick={openActivityAdd}
                />
              ) : null}
            </div>

            {tabLoading ? <p className="company-muted">Loading…</p> : null}
            {tabError ? <Alert tone="danger">{tabError}</Alert> : null}
            {!tabLoading && timelinePins.failed ? <PinsLoadError /> : null}
            {!tabLoading && shownPins.length ? (
              <div className="company-timeline crm-pins-list">
                {/* As a month group: `.company-timeline > div` lays its cards out. */}
                <div>{shownPins.map((p) => renderTimelineCard(p.item, true))}</div>
              </div>
            ) : null}
            {!tabLoading ? (
              activityByMonth.length === 0 ? (
                shownPins.length ? null : (
                  <TimelineEmpty
                    what={
                      activitySubTab === 'activity'
                        ? 'activities'
                        : (ACTIVITY_SUB_TABS.find(
                            (t) => t.key === activitySubTab,
                          )?.label.toLowerCase() ?? 'activities')
                    }
                    record={company?.name ?? ''}
                    filtered={activityFiltered}
                    canCreate={Boolean(activityAdd || activityLog)}
                  />
                )
              ) : (
                <div className="company-timeline">
                  {activityByMonth.map(([month, items]) => (
                    <div key={month}>
                      <div className="company-timeline-date">{month}</div>
                      {items.map((item) => renderTimelineCard(item, false))}
                    </div>
                  ))}
                </div>
              )
            ) : null}
            {!tabLoading ? (
              <TimelineLoadMore
                hasMore={!noTypes && timelineState.hasMore}
                loading={timelineState.loadingMore}
                onLoadMore={() => void timelineState.loadMore()}
              />
            ) : null}
          </div>
        );
      case 'revenue':
        return (
          <ComingSoonPanel
            title="Revenue"
            text="Billing, invoices, payments and subscriptions for this company will show here once payments are set up in the CRM. Quotes are in the Quotes card."
          />
        );
      default:
        return CATCHUP_CARDS.includes(id) ? (
          <CatchUpCard
            id={id}
            missing={missingFields({
              company,
              hidden: access.hidden,
              defs:
                customDefsStatus === 'ok'
                  ? customDefs
                  : customDefsStatus === 'error'
                    ? 'failed'
                    : 'pending',
              lastActivity:
                overviewStatus === 'ok'
                  ? { at: lastActivityAt }
                  : overviewStatus === 'error'
                    ? 'failed'
                    : 'pending',
            })}
            deleted={deleted}
            interactions={catchup.state}
            contactName={company.contacts[0]?.name ?? null}
            generatedAt={catchup.at}
            timeZone={prefs.timeZone}
            duplicates={duplicateCount}
            dataAgentHref={propertySettingsHref(me, 'company')}
            onCreateEmail={() => setDrawer('email')}
            emailDisabledTitle={canLog ? undefined : logTitle}
          />
        ) : (
          centerPropCard(id)
        );
    }
  };
  /**
   * R10b: the open tab's items as the page draws them (record-tabs.js:872-886): sections open and
   * close the cards after them; Catch-up's cards sit in `.company-catchup` (their styles), as
   * before; About's in a plain block, as R9.
   */
  const closedHere = new Set(
    [...closedSecs]
      .filter((k) => k.startsWith(`${openTabId}|`))
      .map((k) => Number(k.split('|')[1])),
  );
  // R10d: the open tab's cards that its conditional logic hides aren't drawn (record-tabs.js:215).
  const shownItems = currentItems.filter((id) => isSection(id) || condShows(`${openTabId}|${id}`));
  const groups = tabGroups(shownItems, closedHere, (id) =>
    CATCHUP_CARDS.includes(id)
      ? 'catchup'
      : ABOUT_CARDS.has(id) || recordLayout?.cards[id]?.props
        ? 'about'
        : PLAIN_CARDS.has(id)
          ? 'plain'
          : null,
  );
  // R10d: a hidden tab stays in the bar; its body says so (record-tabs.js:145, :876).
  const centerBody: ReactNode = !condShows(`tab|${openTabId}`) ? (
    <div className="company-catchup rt-panel">
      <div className="rt-empty">
        <svg className="rt-emptyart" viewBox="0 0 120 90" aria-hidden="true">
          <ellipse cx="60" cy="78" rx="34" ry="8" fill="#eef1f5" />
          <circle cx="54" cy="34" r="18" fill="#fff" stroke="#b9c0cc" strokeWidth="3" />
          <path d="m67 47 14 14" stroke="#b9c0cc" strokeWidth="5" strokeLinecap="round" />
        </svg>
        <span>Cards in this tab are hidden due to conditional logic.</span>
      </div>
    </div>
  ) : groups.length ? (
    groups.map((g) => {
      const key = `g-${g.entries[0]!.index}`;
      if (g.family === 'catchup' && deleted) {
        return (
          <div key={key} className="company-catchup rt-panel" data-catchup>
            <p className="rt-muted">Catch-up isn&apos;t available for a deleted company.</p>
          </div>
        );
      }
      const inner = g.entries.map((e) =>
        isSection(e.id) ? (
          <TabSection
            key={`sec-${e.index}`}
            name={sectionName(e.id)}
            open={!closedHere.has(e.index)}
            className={g.family === 'catchup' ? 'rt-section' : 'rt-section company-about-section'}
            onToggle={() =>
              setClosedSecs((cur) => {
                const k = `${openTabId}|${e.index}`;
                const next = new Set(cur);
                if (next.has(k)) next.delete(k);
                else next.add(k);
                return next;
              })
            }
          />
        ) : (
          <Fragment key={`${e.id}-${e.index}`}>{centerCard(e.id)}</Fragment>
        ),
      );
      if (g.family === 'catchup') {
        return (
          <div key={key} className="company-catchup rt-panel" data-catchup>
            {inner}
          </div>
        );
      }
      return g.family === 'about' ? (
        <div key={key}>{inner}</div>
      ) : (
        <Fragment key={key}>{inner}</Fragment>
      );
    })
  ) : (
    <p className="company-muted">No cards in this tab yet.</p>
  );
  return (
    <div className="company-details-body company-record-page">
      {deleted ? (
        <Alert tone="warning">
          This company 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>
      ) : null}
      {error ? <Alert tone="danger">{error}</Alert> : null}
      {company.warnings?.length ? (
        <Alert tone="warning">
          Another company already uses a similar domain
          {company.warnings[0]?.matches[0]
            ? ` (${company.warnings[0].matches.map((m) => m.name).join(', ')})`
            : ''}
          .
        </Alert>
      ) : null}

      <div className="company-record-grid">
        {/* LEFT */}
        <aside className="company-record-left company-record-column" ref={leftColumnRef}>
          {/* R4: the compact header once the quick actions scroll away (record-page.js:102-126). */}
          {!deleted ? (
            <RecordStickyHeader
              watchRef={quickRowRef}
              columnRef={leftColumnRef}
              backHref="/companies"
              backLabel="Companies"
              actions={actions}
              avatar={
                <span className="company-record-logo company-record-logo--xs">
                  {companyInitials(company.name)}
                </span>
              }
              name={company.name}
              activities={stickyActivities}
            />
          ) : null}
          {/* R4: left cards start collapsed on phones (record-tabs.js:250-251). */}
          <CardMemory.Provider value={LEFT_CARD_MEMORY}>
            <section className="card company-profile-card">
              {/* R1: the design's back link at the top of the card (record-ui.php:231-234). */}
              <div className="company-profile-head">
                <Link
                  className="crm-contact-profile__back crm-contact-profile__back--text"
                  href="/companies"
                >
                  <BackIcon />
                  <span className="crm-contact-profile__section-title">Companies</span>
                </Link>
                {/* R2: the design's Actions menu in the card's top row (record.php:381). */}
                <ContactActionsMenu
                  actions={actions}
                  disabled={deleted}
                  showSearch={false}
                  keyboard
                />
              </div>
              <div className="company-profile-top">
                <span className="company-record-logo" aria-hidden>
                  {companyInitials(company.name)}
                </span>
                <div className="company-profile-copy">
                  {/* LD3: the name as text, its pencil and popover (record-page.js:128-254). */}
                  <div className="rp-namerow">
                    <h1>{company.name}</h1>
                    <RecordNamePopover
                      object="company"
                      recordName={company.name}
                      fields={nameFields}
                      disabledTitle={canEdit ? undefined : editTitle}
                      onSave={saveNameField}
                      onDetails={() => setPanel('properties')}
                    />
                  </div>
                  {subtitle ? <p className="company-profile-sub">{subtitle}</p> : null}
                  {headerLink ? (
                    // R1: link, open, copy, as the design (record.php:396-399, record-page.js:379-382).
                    <div className="company-profile-link">
                      <a href={headerLink.href} target="_blank" rel="noreferrer">
                        {headerLink.label}
                      </a>
                      <a
                        className="company-profile-link__icon"
                        href={headerLink.href}
                        target="_blank"
                        rel="noreferrer"
                        aria-label={`Open ${headerLink.label}`}
                        title={`Open ${headerLink.label}`}
                      >
                        <ExternalLinkIcon />
                      </a>
                      <button
                        type="button"
                        className="company-profile-link__icon"
                        aria-label="Copy domain"
                        title="Copy domain"
                        onClick={() => {
                          const value = headerLink.label;
                          void navigator.clipboard
                            .writeText(value)
                            .then(() => toast(`Copied ${value}`))
                            .catch(() => toast('Copy failed', 'danger'));
                        }}
                      >
                        <CopyIcon />
                      </button>
                    </div>
                  ) : null}
                </div>
              </div>

              {/* R4: the design's quick row, round icons with labels (record-page.css:21, :60-64),
                drawn with the contact page's classes (details.css). */}
              <div className="crm-contact-profile__quick-actions" ref={quickRowRef}>
                {buttonKeys.map((key) => (
                  <button
                    key={key}
                    type="button"
                    title={logTitle ?? BUTTON_TITLES[key]}
                    disabled={!canLog}
                    onClick={() => openQuick(key)}
                  >
                    <span className="crm-contact-profile__action-icon">
                      <QuickActionIcon kind={key} />
                    </span>
                    <span>{BUTTON_LABELS[key]}</span>
                  </button>
                ))}
                {/* R2: More holds activities only (record-popups-hs.js:1032-1067); the record
                  actions have their own Actions button in the top row. */}
                <ActivitiesMoreMenu
                  items={moreItems}
                  onReorder={() => setReorderOpen(true)}
                  disabled={deleted}
                >
                  <span className="crm-contact-profile__action-icon">
                    <QuickActionIcon kind="more" />
                  </span>
                  <span>More</span>
                </ActivitiesMoreMenu>
              </div>
            </section>

            {/* R9: the left cards in the layout's order (About always shown). */}
            {orderedLeft(
              recordLayout?.left?.filter((id) => id === 'about' || condShows(`left|${id}`)),
              {
                // R10c: property cards the layout adds (created ones).
                ...extraLeft,
                about: (
                  <CollapsibleCard
                    title={recordLayout?.cards.about?.title || 'About this company'}
                    cardId="about"
                    defaultOpen
                    action={withCardGear(
                      // R2: the design's About Actions menu (record-tabs.js:235).
                      !deleted ? (
                        <ContactActionsMenu
                          actions={aboutActions}
                          showSearch={false}
                          triggerClassName="crm-collapsible-card__action"
                          keyboard
                        />
                      ) : (
                        <button
                          type="button"
                          className="crm-collapsible-card__action"
                          onClick={() => setPanel('properties')}
                        >
                          View all properties
                        </button>
                      ),
                      // R10c: the gear on left property cards (record-tabs.js:236).
                      cardView('about').onGear,
                      'About this company',
                    )}
                  >
                    <div className="crm-about-contact">
                      {aboutOrder.map((key) => (
                        <Fragment key={key}>
                          {aboutRows[key] ??
                            (key.startsWith('custom.')
                              ? aboutCustomField(key.slice('custom.'.length))
                              : null)}
                        </Fragment>
                      ))}
                    </div>
                  </CollapsibleCard>
                ),
                'company-info': (
                  <section className="card company-side-card">
                    <div className="company-card-head">
                      <h2>Company information</h2>
                      <button
                        type="button"
                        className="crm-d-none icon-btn icon-btn--ghost"
                        title="Edit company information"
                        disabled={!canEdit}
                        onClick={openEdit}
                      >
                        <svg
                          className="icon"
                          viewBox="0 0 24 24"
                          width="16"
                          height="16"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="1.8"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          aria-hidden
                        >
                          <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
                        </svg>
                      </button>
                    </div>
                    <div className="company-side-list">
                      <div>
                        <span>Website</span>
                        <strong>
                          {websiteLabel ? websiteLabel.replace(/^https?:\/\//i, '') : BLANK}
                        </strong>
                      </div>
                      <div>
                        <span>Primary contact</span>
                        <strong>
                          {primaryContact ? (
                            <Link href={`/contacts/${primaryContact.id}`}>
                              {primaryContact.name}
                            </Link>
                          ) : (
                            BLANK
                          )}
                        </strong>
                      </div>
                      <div>
                        <span>Time zone</span>
                        <strong>
                          {customProp(company.customProperties, [
                            'timezone',
                            'timeZone',
                            'time_zone',
                          ]) ?? prefs.timeZone}
                        </strong>
                      </div>
                      <div>
                        <span>Record source</span>
                        <strong>{formatPicklistLabel(company.source)}</strong>
                      </div>
                    </div>
                  </section>
                ),
                groups: (
                  <PropertyGroupCards
                    objectType="company"
                    defs={customDefs.filter((d) => !aboutCustomNames.has(d.name))}
                    values={company.customProperties}
                    edit={customEdit}
                    onHistory={(field) => setHistoryField(customHistoryField(field))}
                  />
                ),
              },
            )}
          </CardMemory.Provider>
        </aside>

        {/* CENTER */}
        <main className="company-record-center company-record-column">
          <section className="card company-record-main-card">
            {/* The 28 Oct design's company tabs (R9: the layout's), fitted as R8a. */}
            <RecordTabBar<CenterTab>
              label="Company sections"
              tabs={centerTabs.map(([key, label]) => ({ key, label }))}
              active={tab}
              onSelect={setTab}
              fit
              customizeHref={
                me.permissionSet.rules.app.manage_settings
                  ? '/settings/objects?object=company&tab=record'
                  : null
              }
            />

            <div className="company-primary-panel">{centerBody}</div>
          </section>
        </main>

        {/* RIGHT */}
        <aside className="company-record-right company-record-column">
          {/* R4: right cards collapse and remember it, per viewer (record-tabs.js:262-264, :274-277). */}
          <CardMemory.Provider value={COMPANY_RIGHT_MEMORY}>
            {/* The right sidebar in the order of the record layout (shown cards only). */}
            {orderedRight(
              recordLayout?.right?.filter((id) => condShows(`right|${id}`)),
              {
                'r-contacts': assocCard('r-contacts', 'contacts'),
                'r-related': assocCard('r-related', 'related'),
                'r-deals': assocCard('r-deals', 'deals'),
                ...cloneCards,
                // PB8: only with the "Playbooks" permission.
                playbooks: canUsePlaybooks(me) ? <PlaybooksCard run={playbookRun} /> : null,
                // Events, Leads, Tickets and other custom objects linked to the company (HUB-269).
                'r-objects': (
                  <LinkedObjectCards
                    anchorType="company"
                    anchorId={company.id}
                    anchorName={company.name}
                    canEdit={canEdit}
                    variant="company"
                    cardView={(key) => cardView(`object-${key}`)}
                  />
                ),
                tasks: !deleted ? (
                  <RecordTasksCard
                    variant="company"
                    linkedType="company"
                    linkedId={company.id}
                    timeZone={prefs.timeZone}
                    refreshKey={taskRefresh}
                    canAdd={canLog}
                    canComplete={canLog}
                    onAdd={() => setTaskOpen(true)}
                  />
                ) : null,
                attachments: !deleted ? (
                  <AttachmentsSidebarCard
                    variant="company"
                    link={{ type: 'company', id: company.id }}
                    canEdit={canEdit}
                    refreshKey={refreshKey}
                    designAdd
                  />
                ) : null,
                // QA #364: quotes linked to the company or its deals (design details.php "Quotes").
                quotes: !deleted ? (
                  <RecordQuotesCard
                    variant="company"
                    anchor={{
                      type: 'company',
                      id: company.id,
                      dealIds: company.deals.map((d) => d.id),
                    }}
                    canAdd={canLog}
                  />
                ) : null,
              },
            )}
          </CardMemory.Provider>
        </aside>
      </div>

      <CreateTaskDrawer
        snippetContactId={primaryContact?.id}
        composer={composer}
        open={taskOpen}
        onClose={closeTask}
        link={{ objectType: 'company', id: company.id }}
        recordName={company.name}
        // LD10 (CT-26): the same default links as Note and Call (activity-composer.js:354-366).
        initialAssociations={noteAssociations}
        taskTypes={taskTypes}
        timeZone={prefs.timeZone}
        onCreated={() => {
          setTaskRefresh((k) => k + 1);
          void load(true);
        }}
      />

      {editOpen ? (
        <>
          <div
            className="popup-overlay is-visible"
            onClick={() => setEditOpen(false)}
            aria-hidden
          />
          <div className="popup-drawer company-create-drawer is-open" role="dialog" aria-modal>
            <header className="drawer-header">
              <div>
                <h2 className="drawer-title">Edit company</h2>
                <p className="drawer-subtitle">Update company information</p>
              </div>
              <button
                type="button"
                className="drawer-close"
                aria-label="Close"
                onClick={() => setEditOpen(false)}
              >
                ×
              </button>
            </header>
            <form className="popup-body-form" onSubmit={onSave}>
              {formError ? <Alert tone="danger">{formError}</Alert> : null}
              <div className="field">
                <label className="field__label" htmlFor="edit-name">
                  Company name <span className="crm-text-danger">*</span>
                </label>
                <input
                  className="input"
                  id="edit-name"
                  disabled={access.locked('name')}
                  value={form.name}
                  onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                  required
                />
              </div>
              {access.hidden('domain') ? null : (
                <div className="field">
                  <label className="field__label" htmlFor="edit-domain">
                    Domain
                  </label>
                  <input
                    className="input"
                    id="edit-domain"
                    disabled={access.locked('domain')}
                    value={form.domain}
                    onChange={(e) => setForm((f) => ({ ...f, domain: e.target.value }))}
                  />
                </div>
              )}
              {access.hidden('website') ? null : (
                <div className="field">
                  <label className="field__label" htmlFor="edit-website">
                    Website
                  </label>
                  <input
                    className="input"
                    id="edit-website"
                    disabled={access.locked('website')}
                    type="url"
                    placeholder="https://company.com"
                    value={form.website}
                    onChange={(e) => setForm((f) => ({ ...f, website: e.target.value }))}
                  />
                </div>
              )}
              {access.hidden('phone') ? null : (
                <div className="field">
                  <label className="field__label" htmlFor="edit-phone">
                    Phone
                  </label>
                  <input
                    className="input"
                    id="edit-phone"
                    disabled={access.locked('phone')}
                    type="tel"
                    inputMode="tel"
                    maxLength={50}
                    placeholder="+919876543210"
                    value={form.phone}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, phone: sanitizePhoneInput(e.target.value) }))
                    }
                  />
                </div>
              )}
              {showOwnerPicker ? (
                <div className="field">
                  <label className="field__label" htmlFor="edit-owner">
                    Company owner
                  </label>
                  <CustomSelect
                    id="edit-owner"
                    disabled={access.locked('ownerId')}
                    className="company-drawer-select"
                    placeholder="Unassigned"
                    value={form.ownerId}
                    options={ownerOptions}
                    onChange={(v) => setForm((f) => ({ ...f, ownerId: v }))}
                    menuMinWidth={280}
                  />
                </div>
              ) : null}
              {access.hidden('industry') ? null : (
                <div className="field">
                  <label className="field__label" htmlFor="edit-industry">
                    Industry
                  </label>
                  <CustomSelect
                    id="edit-industry"
                    disabled={access.locked('industry')}
                    className="company-drawer-select"
                    placeholder="Select industry"
                    value={form.industry}
                    options={industryOptions}
                    onChange={(v) => setForm((f) => ({ ...f, industry: v }))}
                    menuMinWidth={280}
                  />
                </div>
              )}
              {access.hidden('city') ? null : (
                <div className="field">
                  <label className="field__label" htmlFor="edit-city">
                    City
                  </label>
                  <input
                    className="input"
                    id="edit-city"
                    disabled={access.locked('city')}
                    value={form.city}
                    onChange={(e) => setForm((f) => ({ ...f, city: e.target.value }))}
                  />
                </div>
              )}
              {access.hidden('state') ? null : (
                <div className="field">
                  <label className="field__label" htmlFor="edit-state">
                    State / region
                  </label>
                  <input
                    className="input"
                    id="edit-state"
                    disabled={access.locked('state')}
                    value={form.state}
                    maxLength={100}
                    onChange={(e) => setForm((f) => ({ ...f, state: e.target.value }))}
                  />
                </div>
              )}
              {access.hidden('country') ? null : (
                <div className="field">
                  <label className="field__label" htmlFor="edit-country">
                    Country
                  </label>
                  <input
                    className="input"
                    id="edit-country"
                    disabled={access.locked('country')}
                    value={form.country}
                    onChange={(e) => setForm((f) => ({ ...f, country: e.target.value }))}
                  />
                </div>
              )}

              {shownDefs.length ? (
                <p className="crm-fs-8 crm-text-muted" style={{ margin: '8px 0 0' }}>
                  Custom fields
                </p>
              ) : null}
              {shownDefs.map((def) => (
                <div key={def.id} className="field">
                  <label
                    className="field__label"
                    htmlFor={`company-edit-custom-${def.name}`}
                    title={def.description || undefined}
                  >
                    {def.required ? `${def.label} *` : def.label}
                  </label>
                  <CustomFieldInput
                    def={def}
                    id={`company-edit-custom-${def.name}`}
                    value={custom[def.name] ?? loadedCustom(def)}
                    onChange={(value) => setCustom((cur) => ({ ...cur, [def.name]: value }))}
                  />
                </div>
              ))}
              {customDefs.some((d) => d.type === 'datetime') ? (
                <p className="crm-fs-8 crm-text-muted">Times are in {prefs.timeZone}.</p>
              ) : null}

              <div className="drawer-actions crm-d-flex crm-gap-2 crm-mt-3">
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  onClick={() => setEditOpen(false)}
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className={cn('btn-crm btn-crm--primary', saving && 'is-loading')}
                  disabled={saving}
                >
                  <span className="btn-crm__spinner" aria-hidden />
                  <span className="btn-crm__text">Save changes</span>
                </button>
              </div>
            </form>
          </div>
        </>
      ) : null}

      {timelineEditing.dialogs}
      <LogNoteDrawer
        composer={composer}
        open={drawer === 'note'}
        onClose={closeDrawer}
        link={companyLink}
        recordName={company.name}
        recordSecondary={company.domain}
        initialAssociations={noteAssociations}
        // CQS1 #715: snippets are filled for the company's primary contact, as its email is.
        snippetContactId={primaryContact?.id}
        onLogged={afterActivity}
      />
      <LogCallDrawer
        snippetContactId={primaryContact?.id}
        composer={composer}
        open={drawer === 'call' || drawer === 'dial'}
        dial={
          drawer === 'dial'
            ? {
                name: dialContact?.name ?? company.name,
                phone: dialContact?.phone ?? company.phone ?? null,
              }
            : null
        }
        onClose={closeDrawer}
        link={companyLink}
        recordName={company.name}
        recordSecondary={company.domain}
        initialAssociations={noteAssociations}
        outcomes={callOutcomes.filter((o) => !o.archived)}
        timeZone={prefs.timeZone}
        onLogged={afterActivity}
        callFields
      />
      <LogCommunicationDrawer
        snippetContactId={primaryContact?.id}
        open={drawer === 'communication'}
        onClose={closeDrawer}
        link={companyLink}
        recordName={company.name}
        timeZone={prefs.timeZone}
        onLogged={afterActivity}
        channel={commChannel}
      />
      {/* R2: Clone as the design's form (record-popups-hs.js:564-594). The owner follows B4's
          rule (cloneOwnerId): the design's owner box is free text. */}
      <CloneRecordDrawer
        open={cloneOpen}
        title="Clone Company"
        fields={[
          { name: 'domain', label: 'Company domain name', required: true },
          { name: 'name', label: 'Company name', required: true },
          {
            name: 'industry',
            label: 'Industry',
            type: 'select',
            options: industryOptions.map((o) => ({ value: o.value, label: o.label })),
          },
          { name: 'city', label: 'City' },
          { name: 'phone', label: 'Phone number', type: 'tel' },
        ]}
        initial={{
          domain: '',
          name: `${company.name} (clone)`,
          industry: company.industry ?? '',
          city: company.city ?? '',
          phone: company.phone ?? '',
        }}
        editFormHref={isAdmin ? '/create-form-editor?object=company' : undefined}
        onClose={() => setCloneOpen(false)}
        onClone={cloneCompany}
      />
      <ButtonOrderDialog
        open={reorderOpen}
        order={buttonKeys}
        onClose={() => setReorderOpen(false)}
        onSaved={setButtonOrder}
      />
      <CommerceCreateDialog kind={commerceKind} recordName={company.name} onClose={closeCommerce} />
      <LogPostalMailDrawer
        snippetContactId={primaryContact?.id}
        open={drawer === 'postal-mail'}
        onClose={closeDrawer}
        link={companyLink}
        recordName={company.name}
        timeZone={prefs.timeZone}
        onLogged={afterActivity}
      />
      <ScheduleMeetingDrawer
        snippetContactId={primaryContact?.id}
        // CQS1 #715: master's window here, not the composer: the composer's attendee row is the
        // record's one contact (named after the record), and a company picks among its contacts.
        open={drawer === 'meeting' || drawer === 'log-meeting'}
        onClose={closeDrawer}
        link={companyLink}
        recordName={company.name}
        defaultAttendeeEmail={primaryContact?.email ?? null}
        attendeeOptions={recipientOptions}
        timeZone={prefs.timeZone}
        defaultMinutes={prefs.meetingMinutes}
        defaultAddToCalendar={drawer === 'meeting'}
        onScheduled={afterActivity}
      />
      <LogEmailDrawer
        snippetContactId={primaryContact?.id}
        composer={composer}
        open={drawer === 'log-email'}
        onClose={closeDrawer}
        link={companyLink}
        recordName={company.name}
        recordSecondary={company.domain}
        onLogged={afterActivity}
      />
      <SendEmailDrawer
        composer={composer}
        open={drawer === 'email'}
        onClose={closeDrawer}
        contactId={primaryContact?.id}
        contactEmail={primaryContact?.email ?? null}
        recipientOptions={recipientOptions}
        dealId={company.deals[0]?.id}
        recordLink={{ type: 'company', id: company.id }}
        recordName={company.name}
        signature={prefs.signature}
        onSent={afterActivity}
      />

      {/* R7: a sidebar row's Preview (record-tabs.js:659-780). */}
      <AssociatedPreview
        target={previewTarget}
        onClose={() => setPreviewTarget(null)}
        onChanged={() => void afterAssociation()}
      />
      {/* R3: View all properties as the design's drawer (record-tabs.js:614-649); the old
          CompanyPropertiesModal is no longer opened here. */}
      <AllPropertiesDesignDrawer
        open={panel === 'properties'}
        onClose={() => setPanel(null)}
        name={company.name}
        rows={propertyRows}
        groupOrder={companyGroups.order}
        manageHref={propertySettingsHref(me, 'company')}
        docHref={canEditPropertySettings(me) ? '/settings/properties?object=company' : null}
      />
      {tools.drawers}
      <MergeDesignDialog
        open={mergeOpen}
        objectType="company"
        record={{ id: company.id, label: company.name, secondary: company.domain }}
        onClose={() => setMergeOpen(false)}
        timeZone={prefs.timeZone}
      />
      <PropertyHistoryDrawer
        open={historyField !== null}
        onClose={() => setHistoryField(null)}
        load={(params) => getCompanyHistory(company.id, params)}
        describe={describeHistory}
        initialField={historyField ?? 'all'}
        reloadKey={company.updatedAt}
        timeZone={prefs.timeZone}
        design={{
          recordName: company.name,
          objectType: 'company',
          canManageProperties: canOpenPropertySettings(me),
        }}
      />
      <DeleteCompanyDialog
        open={panel === 'delete'}
        onClose={() => setPanel(null)}
        companyId={company.id}
        companyName={company.name}
        onDeleted={() => {
          setPanel(null);
          router.push('/companies');
        }}
      />
    </div>
  );
}
