'use client';

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { DeleteRecordsDialog, recordsText } from '@/features/list-page/ui/DeleteRecordsDialog';
import { LpIcon, type LpIconName } from '@/features/list-page/ui/LpIcon';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { LpMenu, LpPopover, type LpMenuItem } from '@/features/list-page/ui/LpPopover';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import type { ToastOptions } from '@/components/crm/Toast';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import { createList, listAllLists } from '@/features/lists/api.client';
import { listSequences } from '@/features/sequences/api.client';
import { enrollButtonText } from '@/features/sequences/enrollReview';
import type { Sequence } from '@/features/sequences/types';
import {
  EnrollReview,
  NO_MAILBOX_TEXT,
  SequenceBlockAlert,
  useEnrollReview,
  useMySender,
  type EnrollContact,
  type EnrollReviewState,
} from '@/features/sequences/ui/EnrollReview';
import { listWorkflows } from '@/features/workflows/api.client';
import { listTasks, updateTask } from '@/features/tasks/api.client';
import type { WorkflowObject } from '@/features/workflows/types';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { DesignBulkPanels, type BulkPanel, type BxRecord } from './DesignBulkPanels';
import { subscriptionsDoneMessage } from '../subscriptionsResult';
import {
  getBulkOperation,
  startBulk,
  type BulkAction,
  type BulkObject,
  type BulkOperation,
  type BulkSelection,
} from '../api.client';

/** A standard field the "Edit property" action can set on every selected record. */
export type BulkField = {
  key: string;
  label: string;
  /** Picklist values; a text input when left out. */
  options?: CustomSelectOption[];
  type?: 'text' | 'number' | 'date';
  /**
   * B6: the field's own rule for a typed value (Companies' domain: no `https://`, no path, no
   * spaces), applied before it is sent. Without it, the value is trimmed as before.
   */
  clean?: (raw: string) => { value: string | null } | { error: string };
};

/** The values an "Edit property" sends for a typed value, or the field rule's error. */
export function bulkEditValues(
  field: BulkField,
  raw: string,
): { values: Record<string, unknown> } | { error: string } {
  let typed: unknown;
  if (field.clean) {
    const cleaned = field.clean(raw);
    if ('error' in cleaned) return cleaned;
    typed = cleaned.value;
  } else {
    const trimmed = raw.trim();
    typed = trimmed === '' ? null : field.type === 'number' ? Number(trimmed) : trimmed;
  }
  return { values: fieldValues(field, typed) };
}

/** The update body that sets `field` to `typed` (custom properties under `customProperties`). */
function fieldValues(field: BulkField, typed: unknown): Record<string, unknown> {
  if (field.key.startsWith('custom.')) {
    return { customProperties: { [field.key.slice('custom.'.length)]: typed } };
  }
  return { [field.key]: typed };
}

/** CT-28: the values an "Edit property" sends to clear `field` on every selected record. */
export function bulkClearValues(field: BulkField): Record<string, unknown> {
  return fieldValues(field, null);
}

/**
 * CT-28 (`explicitClear`, Contacts and Companies): what Update does. `off` until a property and a
 * value are chosen; `clear` when "Clear this property" is ticked (it asks first); `set` otherwise.
 * A value the field's own rule refuses is `set`, so Update shows the rule's error as before.
 */
export function bulkEditReady(
  field: BulkField | undefined,
  raw: string,
  clear: boolean,
): 'off' | 'set' | 'clear' {
  if (!field) return 'off';
  if (clear) return 'clear';
  if (field.clean) {
    const cleaned = field.clean(raw);
    if ('error' in cleaned) return 'set';
    return cleaned.value === null || cleaned.value === '' ? 'off' : 'set';
  }
  return raw.trim() === '' ? 'off' : 'set';
}

type Dialog =
  | 'owner'
  | 'edit'
  /** CT-28: "Clear <property>?" before an edit that clears it (`explicitClear`). */
  | 'edit-clear'
  | 'list'
  | 'segment-new'
  | 'segment-done'
  | 'sequence'
  | 'workflow'
  | 'delete'
  | 'result'
  | null;

/** The segment records are going into: `isNew` when "Create new segment" just made it. */
type SegmentTarget = { name: string; isNew: boolean };

const ACTION_DONE: Record<BulkOperation['action'], string> = {
  // G9: made by Bulk edit history, never by this bar; listed so every action has a word.
  undo: 'put back',
  update: 'updated',
  assign_owner: 'assigned',
  delete: 'deleted',
  restore: 'restored',
  add_to_list: 'added to the list',
  remove_from_list: 'removed from the list',
  enroll_sequence: 'enrolled',
  enroll_workflow: 'enrolled',
  share: 'shared',
  // Its toast is `subscriptionsDoneMessage`'s.
  set_subscriptions: 'updated',
};

/**
 * The toast when a bulk action is done. Deleted contacts are "records", as in the design. B6:
 * with `editLabel` (Companies), an edit names its property as the design's (list-page.js:2778):
 * "Company domain name updated on 2 companies".
 */
export function bulkDoneMessage(
  op: Pick<BulkOperation, 'action' | 'succeeded' | 'failed' | 'skipped' | 'skipReasons'>,
  objectType: BulkObject,
  noun: string,
  editLabel?: string | null,
  /** The object's name for a number of records ("1 company", "2 companies"); default `noun`. */
  nounOf?: (n: number) => string,
  /**
   * B10, point 29 (the design's Assign, list-page.js:2743): who the records went to, or `null`
   * for "No owner": "2 records assigned to Dev Admin", "2 records unassigned".
   */
  assign?: { to: string | null },
): string {
  // IDB7: the design's subscriptions toast (list-page.js:3548), with decision C's skips.
  if (op.action === 'set_subscriptions') return subscriptionsDoneMessage(op).text;
  if (assign && op.action === 'assign_owner') {
    const failed = op.failed ? `, ${op.failed.toLocaleString()} could not be changed` : '';
    return `${recordsText(op.succeeded)} ${assign.to ? `assigned to ${assign.to}` : 'unassigned'}${failed}`;
  }
  if (editLabel && op.action === 'update') {
    const failed = op.failed ? `, ${op.failed.toLocaleString()} could not be changed` : '';
    const name = nounOf ? nounOf(op.succeeded) : noun;
    return `${editLabel} updated on ${op.succeeded.toLocaleString()} ${name}${failed}`;
  }
  const contactDelete = op.action === 'delete' && objectType === 'contact';
  const done = contactDelete
    ? recordsText(op.succeeded)
    : `${op.succeeded.toLocaleString()} ${noun}`;
  const failed = op.failed
    ? `, ${op.failed.toLocaleString()} could not be ${contactDelete ? 'deleted' : 'changed'}`
    : '';
  // Sequences: contacts over the sender's daily send limit were skipped (HubSpot: "won't enroll").
  const overLimit = op.action === 'enroll_sequence' ? (op.skipReasons?.send_limit ?? 0) : 0;
  const skipped = overLimit
    ? `, ${overLimit.toLocaleString()} skipped: over your daily send limit`
    : '';
  return `${done} ${ACTION_DONE[op.action]}${failed}${skipped}`;
}

/**
 * G9 (issue 708): the options of the toast when a bulk action is done. With `onEditUndo` (Contacts
 * only), an edit or owner change that changed records gets an Undo button and stays 12 s; every
 * other toast keeps master's 8 s and no button.
 */
export function doneToastOptions(
  op: BulkOperation,
  onEditUndo?: (op: BulkOperation) => void,
): ToastOptions {
  const undoable =
    onEditUndo &&
    op.status === 'done' &&
    (op.action === 'update' || op.action === 'assign_owner') &&
    op.succeeded > 0;
  return undoable
    ? { durationMs: 12000, action: { label: 'Undo', onClick: () => onEditUndo(op) } }
    : { durationMs: 8000 };
}

/** A dialog or panel another page's own buttons ask the bar to open (`request`). */
// IDB4b: Import details also asks for `workflow`; its dialog already renders in design mode.
export type BulkRequest = 'owner' | 'edit' | 'delete' | 'sequence' | 'workflow' | 'tasks';

/**
 * What a request opens: the dialog of the same name, or the design's Create tasks panel (coming
 * soon without `panels`, as the bar's own button).
 */
export function bulkRequestTarget(
  request: BulkRequest,
  hasPanels: boolean,
): { dialog: Exclude<BulkRequest, 'tasks'> } | { panel: 'tasks' } | { soon: string } {
  if (request === 'tasks') return hasPanels ? { panel: 'tasks' } : { soon: 'Create tasks' };
  return { dialog: request };
}

/** A toast to show once the bulk action's own toast is up. */
type TaskNote = { text: string; tone: 'info' | 'success' | 'danger' } | null;

/** No contacts listed: a bulk enroll's review shows the selection's count. */
const NO_CONTACTS: readonly EnrollContact[] = [];

/**
 * SEQ-R-B3: the bulk "Enroll in sequence" dialog's body and footer. It takes the same review as
 * every other enroll (sender, start step, time zone, send time, the sender's daily send limit
 * and pace); the
 * contacts are a selection, not listed. Mounted only while the dialog is open.
 */
function BulkEnrollBody({
  objectType,
  count,
  error,
  sequences,
  sequenceRows,
  sequenceId,
  onSequence,
  footer,
  onEnroll,
}: {
  objectType: BulkObject;
  count: number;
  error: string | null;
  sequences: CustomSelectOption[];
  sequenceRows: readonly Sequence[];
  sequenceId: string;
  onSequence: (id: string) => void;
  footer: (label: string, onConfirm: () => void, disabled?: boolean) => React.ReactNode;
  onEnroll: (
    senderMailboxId: string,
    choices: NonNullable<ReturnType<EnrollReviewState['requestOptions']>>,
  ) => void;
}) {
  const { sender } = useMySender(true);
  const picked = sequenceRows.find((s) => s.id === sequenceId) ?? null;
  const review = useEnrollReview({ open: true, sequence: picked, contacts: NO_CONTACTS, sender });
  const blocked = review.block;
  return (
    <>
      {/* Sequences QA BUG-01: open-list (overflow visible) only while the body is the short
          picker. With the review it scrolls between the header and footer, as the other enroll
          dialogs; the picker's list then opens over the review below it. */}
      <div className={cn('modal__body', !picked && 'modal__body--open-list')}>
        {error ? <Alert tone="danger">{error}</Alert> : null}
        {!sender.ready ? <Alert tone="info">{NO_MAILBOX_TEXT}</Alert> : null}
        <div className="field">
          <label className="field__label">Sequence</label>
          <CustomSelect
            placeholder="Select sequence"
            value={sequenceId}
            options={sequences}
            onChange={onSequence}
          />
        </div>
        {blocked && picked ? (
          <SequenceBlockAlert sequence={picked} text={blocked} problems={review.problems} />
        ) : null}
        {picked ? (
          <EnrollReview
            idPrefix={`bulk-${objectType}-enrol`}
            sequence={picked}
            contacts={NO_CONTACTS}
            count={count}
            sender={sender}
            review={review}
          />
        ) : null}
      </div>
      {footer(
        enrollButtonText(count),
        () => {
          const choices = review.requestOptions();
          if (sender.mailboxId && choices) onEnroll(sender.mailboxId, choices);
        },
        !picked || Boolean(blocked) || !sender.ready,
      )}
    </>
  );
}

/**
 * HUB-372: the bulk action buttons of the contacts, companies and deals lists (HubSpot's
 * selection bar): Assign owner, Edit property, Add to static list, Enroll in sequence
 * (contacts) or workflow, Delete. Each runs as a background operation (HUB-371); a progress
 * strip shows while it runs, then a toast with the counts and a link to the failures.
 */

export function BulkActionsBar({
  objectType,
  noun,
  selection,
  count,
  ownerOptions,
  fields,
  customDefs,
  canDelete,
  canShare = true,
  onDone,
  design = false,
  panels,
  editToast = false,
  flipMore = false,
  keepPrimaryActions = false,
  headless = false,
  request = null,
  onStarted,
  onEditUndo,
  noAccessHints = false,
  explicitClear = false,
  onExport,
  canExport = true,
}: {
  objectType: BulkObject;
  /** Plural, lower case ("contacts"). */
  noun: string;
  selection: BulkSelection;
  /** Records selected (all matching: the list total). */
  count: number;
  ownerOptions: CustomSelectOption[];
  fields: BulkField[];
  customDefs: CustomPropertyDefinition[];
  canDelete: boolean;
  /** S5: off for people who can't edit these records, who can't share them either. */
  canShare?: boolean;
  /**
   * CT-11 (design bar): disabled buttons look disabled, and Delete without the delete right says
   * why on hover (Contacts, Companies). Off: master's bar.
   */
  noAccessHints?: boolean;
  /**
   * CQS1 #264 (Companies, design bar): Export first in More, opening the list's export with the
   * selected rows. Without it there is no Export here (the design's bar has none).
   */
  onExport?: () => void;
  /** CQS1 #264: off without the export right: Export shows disabled and says why. */
  canExport?: boolean;
  /** After an operation finished: reload the list and clear the selection. */
  onDone: () => void;
  /**
   * The 28 Oct design's bulk bar (list-page.js BULK_LAYOUT): Enrich records, Fill smart
   * properties, Assign, Share, Edit, Delete and More, with the design's dialogs. Actions the CRM
   * doesn't have yet say so.
   */
  design?: boolean;
  /**
   * The design's bulk panels (Enrich, Fill smart properties, Share, Review Associations, Create
   * tasks, Create leads, Enrichment coverage, Subscriptions); without it they say "coming soon".
   */
  panels?: {
    singular: string;
    /** "companies", whatever the count (the prospecting agent's text). */
    plural?: string;
    loadRecords: () => Promise<BxRecord[]>;
    teams: CustomSelectOption[];
    meId: string;
    linkTypes: Array<{ type: string; singular: string; plural: string }>;
    coverageProps: string[];
  };
  /** B6 (Companies): an edit's toast names the property, as the design's (`bulkDoneMessage`). */
  editToast?: boolean;
  /** B9, point 30 (Companies, Contacts): the More menu opens above as the design's (`bulkMorePopover`). */
  flipMore?: boolean;
  /** GLB5 (Contacts, Companies): Assign, Share, Edit and Delete are the last to move into More. */
  keepPrimaryActions?: boolean;
  /**
   * The contact segment page (design mode only): the bar draws none of its own buttons, so the
   * page keeps its design's bulk bar and opens these dialogs with `request`. Off for every other
   * caller.
   */
  headless?: boolean;
  /** Opens a dialog or panel; a new `seq` opens it again. */
  request?: { dialog: BulkRequest; seq: number } | null;
  /** G9 (Contacts): each operation once started, e.g. for the list's enrollment badge. */
  onStarted?: (op: BulkOperation) => void;
  /** G9 (Contacts): an Undo on the done toast of an edit or owner change (`doneToastOptions`). */
  onEditUndo?: (op: BulkOperation) => void;
  /**
   * CT-28 (Contacts, Companies; the design's Bulk edit dialog only): Update stays off until a
   * value is chosen, and clearing the property takes the "Clear this property" box and a
   * confirmation. Off: an empty value clears the property at once, as the design.
   */
  explicitClear?: boolean;
}) {
  const toast = useToast();
  const me = useCurrentUser();
  const [panel, setPanel] = useState<BulkPanel | null>(null);
  const [dialog, setDialog] = useState<Dialog>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [running, setRunning] = useState<BulkOperation | null>(null);
  const [result, setResult] = useState<BulkOperation | null>(null);
  const pollRef = useRef<number | null>(null);
  /** False once the bar is gone: a poll in flight then stops instead of scheduling another. */
  const aliveRef = useRef(true);
  /** Assign > "Reassign all incomplete tasks": its result, shown after the bulk action's toast. */
  const taskNoteRef = useRef<Promise<TaskNote> | null>(null);
  const flushTaskNote = () => {
    const note = taskNoteRef.current;
    taskNoteRef.current = null;
    void note?.then((n) => {
      if (n) toast(n.text, n.tone, { durationMs: 8000 });
    });
  };

  // The pickers' choices, loaded when their dialog opens.
  const [ownerId, setOwnerId] = useState('');
  const [field, setField] = useState('');
  const [value, setValue] = useState('');
  /** CT-28: "Clear this property" is ticked (only with `explicitClear`). */
  const [clearValue, setClearValue] = useState(false);
  const [lists, setLists] = useState<CustomSelectOption[]>([]);
  const [listsLoading, setListsLoading] = useState(false);
  /** Not until a load worked: a segment created after a failed one is not the whole list. */
  const listsLoadedRef = useRef(false);
  const [listId, setListId] = useState('');
  const [segmentName, setSegmentName] = useState('');
  const [creatingSegment, setCreatingSegment] = useState(false);
  const [segmentDone, setSegmentDone] = useState<(SegmentTarget & { count: number }) | null>(null);
  /** The segment of the add_to_list being run: its result shows the design's Success dialog. */
  const segmentRef = useRef<SegmentTarget | null>(null);
  /** B6: the property of the edit being run, for its toast (only with `editToast`). */
  const editLabelRef = useRef<string | null>(null);
  const [sequences, setSequences] = useState<CustomSelectOption[]>([]);
  const [sequenceId, setSequenceId] = useState('');
  /** #58: the sequences themselves, for the enroll review of the one picked. */
  const [sequenceRows, setSequenceRows] = useState<Sequence[]>([]);
  const [workflows, setWorkflows] = useState<CustomSelectOption[]>([]);
  const [workflowId, setWorkflowId] = useState('');

  useEffect(() => {
    aliveRef.current = true;
    return () => {
      aliveRef.current = false;
      if (pollRef.current) window.clearTimeout(pollRef.current);
    };
  }, []);

  const editable = useMemo<BulkField[]>(
    () => [
      ...fields,
      ...customDefs
        // The editor sends one text, number or date value: checkboxes, true/false and date-time
        // fields need their own control, so they aren't offered here.
        .filter(
          (d) =>
            !d.archived &&
            !d.readOnly &&
            d.type !== 'multiselect' &&
            d.type !== 'boolean' &&
            d.type !== 'datetime',
        )
        .map((d) => ({
          key: `custom.${d.name}`,
          label: d.label,
          ...(d.options?.length
            ? {
                options: d.options
                  .filter((o) => !o.archived)
                  .map((o) => ({ value: o.value, label: o.label })),
              }
            : {}),
          type:
            d.type === 'number'
              ? ('number' as const)
              : d.type === 'date'
                ? ('date' as const)
                : ('text' as const),
        })),
    ],
    [fields, customDefs],
  );
  const pickedField = editable.find((f) => f.key === field);
  const editReady = bulkEditReady(pickedField, value, explicitClear && clearValue);

  const open = (next: Dialog) => {
    if (running && next !== 'result') {
      toast('Wait for the bulk action that is running to finish', 'info');
      return;
    }
    setError(null);
    setDialog(next);
    // CT-28: the box is never ticked when Bulk edit opens.
    if (next === 'edit') setClearValue(false);
    if (next === 'list' && design) setListId('');
    // B10, point 29: the design's Assign opens on "No owner" (list-page.js:2733, :2747), set
    // before the dialog draws so it never shows the last pick first.
    if (next === 'owner' && design) setOwnerId(ASSIGN_NONE);
    if (next === 'list' && (lists.length === 0 || !listsLoadedRef.current)) {
      setListsLoading(true);
      listAllLists()
        .then(
          ({ lists: all }) => {
            listsLoadedRef.current = true;
            const loaded = all
              .filter((l) => l.objectType === objectType && l.listType === 'static')
              .map((l) => ({ value: l.id, label: l.name }));
            // A segment created while this was loading isn't in the answer.
            setLists((cur) => [
              ...cur.filter((l) => !loaded.some((x) => x.value === l.value)),
              ...loaded,
            ]);
          },
          (err: unknown) => setError(errorText(err)),
        )
        .finally(() => setListsLoading(false));
    }
    if (next === 'sequence') {
      listSequences({ status: 'active', limit: 100 }).then(
        (page) => {
          setSequences(page.data.map((s) => ({ value: s.id, label: s.name })));
          setSequenceRows(page.data);
        },
        (err: unknown) => setError(errorText(err)),
      );
    }
    if (next === 'workflow') {
      listWorkflows({
        objectType: [objectType as WorkflowObject],
        status: ['on'],
        limit: 100,
      } as never).then(
        (page) => setWorkflows(page.data.map((w) => ({ value: w.id, label: w.name }))),
        (err: unknown) => setError(errorText(err)),
      );
    }
  };

  // `request` (the segment page): open what was asked, once per `seq`.
  const requestSeq = request?.seq;
  useEffect(() => {
    if (!request) return;
    const target = bulkRequestTarget(request.dialog, Boolean(panels));
    if ('dialog' in target) open(target.dialog);
    else if ('panel' in target) setPanel(target.panel);
    else toast(`${target.soon} is coming soon`, 'info');
    // Only a new request opens it; the dialog's own state changes must not reopen it.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [requestSeq]);

  /** `answered`: the operation as the API returned it, when it is finished already. */
  const poll = (id: string, answered?: BulkOperation) => {
    (answered ? Promise.resolve(answered) : getBulkOperation(id)).then(
      (op) => {
        if (!aliveRef.current) return;
        if (op.status === 'done' || op.status === 'failed') {
          setRunning(null);
          setResult(op);
          const segment = segmentRef.current;
          segmentRef.current = null;
          // The design keeps the selection after adding to a segment, so the bar stays and the
          // dialog with it.
          if (segment && op.status === 'done' && op.succeeded > 0) {
            setSegmentDone({ ...segment, count: op.succeeded });
            setDialog('segment-done');
            if (op.failed) {
              toast(bulkDoneMessage(op, objectType, noun), 'info', { durationMs: 8000 });
            }
            return;
          }
          if (op.status === 'failed') {
            toast(op.error ?? 'The bulk action failed', 'danger', { durationMs: 9000 });
          } else {
            toast(
              bulkDoneMessage(
                op,
                objectType,
                noun,
                editLabelRef.current,
                panels ? (n) => (n === 1 ? panels.singular : (panels.plural ?? noun)) : undefined,
                op.action === 'assign_owner' ? (assignRef.current ?? undefined) : undefined,
              ),
              op.action === 'set_subscriptions'
                ? subscriptionsDoneMessage(op).tone
                : op.failed
                  ? 'info'
                  : 'success',
              doneToastOptions(op, onEditUndo),
            );
          }
          flushTaskNote();
          onDone();
          return;
        }
        setRunning(op);
        pollRef.current = window.setTimeout(() => poll(id), 1500);
      },
      () => {
        if (!aliveRef.current) return;
        pollRef.current = window.setTimeout(() => poll(id), 4000);
      },
    );
  };

  /** False when the action could not start: `error` says why. */
  const run = async (action: BulkAction): Promise<boolean> => {
    setBusy(true);
    setError(null);
    try {
      const op = await startBulk(objectType, { ...action, selection });
      onStarted?.(op);
      setDialog(null);
      setResult(null);
      // A small delete is done already, so the progress strip would only flash.
      if (op.status === 'done' || op.status === 'failed') {
        poll(op.id, op);
      } else {
        setRunning(op);
        poll(op.id);
      }
      return true;
    } catch (err) {
      setError(errorText(err));
      flushTaskNote();
      return false;
    } finally {
      setBusy(false);
    }
  };

  // Once sent, a create or an add can't be called back, so don't look as if it can.
  const closeSegment = () => {
    if (!creatingSegment && !busy) setDialog(null);
  };

  const addToSegment = async (id: string, target: SegmentTarget): Promise<boolean> => {
    segmentRef.current = target;
    const started = await run({ action: 'add_to_list', listId: id });
    if (!started) segmentRef.current = null;
    return started;
  };

  /** "Create new segment": a static list of this object, then the selection goes into it. */
  const createSegment = async () => {
    const name = segmentName.trim();
    if (!name || creatingSegment || busy) return;
    const taken = () => toast('A segment with this name already exists', 'danger');
    if (lists.some((l) => l.label.toLowerCase() === name.toLowerCase())) {
      taken();
      return;
    }
    setCreatingSegment(true);
    setError(null);
    try {
      const list = await createList({ name, objectType, listType: 'static' });
      setLists((cur) => [{ value: list.id, label: list.name }, ...cur]);
      setListId(list.id);
      // The list exists now: if the add can't start, trying again from the picker can't clash.
      if (!(await addToSegment(list.id, { name: list.name, isNew: true }))) setDialog('list');
    } catch (err) {
      if (isApiError(err) && err.isConflict) taken();
      else setError(errorText(err));
    } finally {
      setCreatingSegment(false);
    }
  };

  const editValue = (): Record<string, unknown> | null => {
    if (!pickedField) return null;
    const out = bulkEditValues(pickedField, value);
    if ('error' in out) {
      setError(out.error);
      return null;
    }
    // B6: the toast names the property (Companies).
    editLabelRef.current = editToast ? pickedField.label : null;
    return out.values;
  };

  /**
   * Assign > "Reassign all incomplete tasks": the records' tasks that aren't completed go to the
   * new owner. There is no bulk API for it, so the browser updates them one by one (the first
   * 200 records). It starts with the owner change, while the selection still matches its filter.
   */
  const reassignOpenTasks = async (assigneeId: string | null): Promise<TaskNote> => {
    if (objectType !== 'contact' && objectType !== 'company' && objectType !== 'deal') return null;
    try {
      const ids =
        'ids' in selection
          ? selection.ids
          : panels
            ? (await panels.loadRecords()).map((r) => r.id)
            : [];
      if (!ids.length) {
        return {
          text: 'Incomplete tasks can be reassigned for the records on this page only.',
          tone: 'info',
        };
      }
      let moved = 0;
      let failed = 0;
      for (const id of ids.slice(0, 200)) {
        const page = await listTasks({
          linkedType: objectType,
          linkedId: id,
          assignee: 'any',
          view: 'all',
          limit: 100,
        });
        const open = page.data.filter(
          (t) => t.status !== 'completed' && (t.assignee?.id ?? null) !== assigneeId,
        );
        for (const t of open) {
          try {
            await updateTask(t.id, { assigneeId });
            moved += 1;
          } catch {
            failed += 1;
          }
        }
      }
      return {
        text: `${moved.toLocaleString()} incomplete ${moved === 1 ? 'task' : 'tasks'} reassigned${failed ? `, ${failed} failed` : ''}${ids.length > 200 ? ' (first 200 records)' : ''}`,
        tone: failed ? 'info' : 'success',
      };
    } catch (err) {
      return { text: errorText(err), tone: 'danger' };
    }
  };

  const countText = `${count.toLocaleString()} ${noun}`;
  const recs = recordsText(count);
  const [reassignTasks, setReassignTasks] = useState(false);
  /** B10, point 29: who the design's Assign gave the records to, for its toast. */
  const assignRef = useRef<{ to: string | null } | null>(null);
  useEffect(() => {
    if (dialog === 'owner') setReassignTasks(false);
  }, [dialog]);
  const footer = (label: string, onConfirm: () => void, disabled = false, danger = false) => (
    <div className="modal__footer">
      <button
        type="button"
        className={cn(
          'btn-crm',
          danger ? 'btn-crm--danger' : 'btn-crm--primary',
          busy && 'is-loading',
        )}
        disabled={busy || disabled}
        onClick={onConfirm}
      >
        {label}
      </button>
      <button type="button" className="btn-crm btn-crm--outline" onClick={() => setDialog(null)}>
        Cancel
      </button>
    </div>
  );

  if (design) {
    const soon = (label: string) => () => toast(`${label} is coming soon`, 'info');
    /** Opens the design's panel for an action, or says it is coming soon. */
    const side = (p: BulkPanel, label: string) => (panels ? () => setPanel(p) : soon(label));
    const acts: Record<string, DesignAct> = {
      enrich: { label: 'Enrich records', icon: 'sparkle', run: side('enrich', 'Enrich records') },
      smart: {
        label: 'Fill smart properties',
        icon: 'sparkle',
        run: side('smart', 'Fill smart properties'),
      },
      // B10, point 29: the design's arrow (list-page.js:2919).
      assign: { label: 'Assign', icon: 'arrowRight', run: () => open('owner') },
      share: {
        label: 'Share',
        icon: 'share',
        run: () => {
          setError(null);
          side('share', 'Sharing records')();
        },
        off: !canShare,
        // DL6: deals keep the design's Share, turned off (the API shares contacts and companies).
        title: objectType === 'deal' && !canShare ? "Sharing deals isn't available yet" : undefined,
      },
      edit: { label: 'Edit', icon: 'pencil', run: () => open('edit') },
      del: {
        label: 'Delete',
        icon: 'trash',
        run: () => open('delete'),
        off: !canDelete,
        // CT-11: plural from the object, as `noun` is singular for one row.
        title:
          noAccessHints && !canDelete
            ? `You do not have permission to delete ${objectType === 'company' ? 'companies' : `${objectType}s`}`
            : undefined,
      },
      assoc: {
        label: 'Review Associations',
        icon: 'assoc',
        run: side('assoc', 'Review Associations'),
      },
      tasks: { label: 'Create tasks', icon: 'plus', run: side('tasks', 'Create tasks') },
      sequence: { label: 'Enroll in sequence', icon: 'sequence', run: () => open('sequence') },
      leads: { label: 'Create leads', icon: 'plus', run: side('leads', 'Create leads') },
      // The design offers the prospecting agent for companies only (contacts show it disabled).
      agent: {
        label: 'Enroll to agent',
        icon: 'sparkles',
        run: side('agent', 'The prospecting agent'),
        off: objectType !== 'company',
      },
      coverage: {
        label: 'Check enrichment coverage',
        icon: 'sparkle',
        run: side('coverage', 'Enrichment coverage'),
      },
      segment: { label: 'Add to static segment', icon: 'segment', run: () => open('list') },
      workflow: { label: 'Enroll in workflow', icon: 'workflow', run: () => open('workflow') },
      dialer: { label: 'Add to Power Dialer', icon: 'dialer', run: soon('Power Dialer') },
      legal: { label: 'Add legal basis for processing contact data', plain: true, off: true },
      subs: {
        label: 'Edit communication subscriptions',
        icon: 'plus',
        // IDB7: a reason left from another dialog doesn't show in the panel.
        run: panels
          ? () => {
              setError(null);
              setPanel('subs');
            }
          : soon('Communication subscriptions'),
      },
      optin: { label: 'Update double opt-in status', plain: true, off: true },
      intent: {
        label: 'Track intent signals',
        icon: 'sparkle',
        run: side('intent', 'Intent signals'),
      },
      export: {
        label: 'Export',
        icon: 'upload',
        run: onExport,
        off: !canExport,
        title: canExport ? undefined : 'You do not have export access',
      },
    };
    const base = DESIGN_BULK[objectType] ?? DESIGN_BULK.contact!;
    const layout = onExport ? { ...base, more: ['export', ...base.more] } : base;
    return (
      <>
        {headless ? null : (
          <DesignBulkButtons
            acts={acts}
            bar={layout.bar}
            more={layout.more}
            flipMore={flipMore}
            keepPrimaryActions={keepPrimaryActions}
            dim={noAccessHints}
          />
        )}
        {panels ? (
          <DesignBulkPanels
            panel={panel}
            onClose={() => setPanel(null)}
            objectType={
              objectType === 'company' ? 'company' : objectType === 'deal' ? 'deal' : 'contact'
            }
            singular={panels.singular}
            plural={noun}
            pluralName={panels.plural ?? noun}
            count={count}
            loadRecords={panels.loadRecords}
            owners={ownerOptions}
            teams={panels.teams}
            meId={panels.meId}
            linkTypes={panels.linkTypes}
            coverageProps={panels.coverageProps}
            onDone={onDone}
            onShare={(input) => run({ action: 'share', ...input })}
            shareError={panel === 'share' ? error : null}
            // IDB7: contacts only (the API refuses other objects).
            onSubscriptions={
              objectType === 'contact'
                ? async (input) => {
                    // The panel opens without `open()`'s check: a second job would lose the
                    // first one's progress.
                    if (running) {
                      setError('Wait for the bulk action that is running to finish');
                      return false;
                    }
                    return run({ action: 'set_subscriptions', ...input });
                  }
                : undefined
            }
            subscriptionsError={panel === 'subs' ? error : null}
          />
        ) : null}
        {running ? (
          <div className="bulk-bar__progress" role="status" style={{ flexBasis: '100%' }}>
            <span>
              Working on{' '}
              {running.total
                ? `${running.processed.toLocaleString()} of ${running.total.toLocaleString()}`
                : countText}
              …
            </span>
            <span className="bulk-bar__meter" aria-hidden>
              <span
                style={{
                  width: `${running.total ? Math.round((running.processed / running.total) * 100) : 5}%`,
                }}
              />
            </span>
          </div>
        ) : null}

        <LpModal
          open={dialog === 'owner'}
          title={`Bulk assign ${recs}`}
          onClose={() => setDialog(null)}
          className="lp-modal--pick lp-modal--bulk lp-modal--open-list"
          footer={
            <div className="lp-modal__acts lp-modal__acts--start">
              <button
                type="button"
                className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
                disabled={busy || !ownerId}
                onClick={() => {
                  const target = assignTarget(ownerId, ownerOptions);
                  assignRef.current = assignToastOf(target);
                  taskNoteRef.current = reassignTasks ? reassignOpenTasks(target.ownerId) : null;
                  void run({ action: 'assign_owner', ownerId: target.ownerId });
                }}
              >
                Update
              </button>
              <button
                type="button"
                className="lp-btn lp-btn--outline"
                onClick={() => setDialog(null)}
              >
                Cancel
              </button>
            </div>
          }
        >
          {error ? <Alert tone="danger">{error}</Alert> : null}
          <p>
            Assign the user responsible for managing{' '}
            {count === 1 ? 'this record as its owner' : 'these records as their owner'}.{' '}
            <a
              className="lp-bx__a"
              href="#"
              onClick={(e) => {
                e.preventDefault();
                toast('Owners help is coming soon', 'info');
              }}
            >
              Learn more about owners.
              <LpIcon name="external" className="lp-i--xs" />
            </a>
          </p>
          <div className="lp-field">
            <label>{ownerLabel(objectType)}</label>
            <CustomSelect
              className="lp-bx__select"
              placeholder="Select"
              value={ownerId}
              // B10, point 29: the design's list, with search and "(me)" (list-page.js:2747).
              options={assignOptions(ownerOptions, me.user.id)}
              onChange={setOwnerId}
              searchable
              searchPlaceholder="Search"
            />
          </div>
          <label className="lp-check">
            <input
              type="checkbox"
              checked={reassignTasks}
              onChange={(e) => setReassignTasks(e.target.checked)}
            />
            <span>Reassign all incomplete tasks</span>
          </label>
        </LpModal>

        <LpModal
          open={dialog === 'edit'}
          title={`Bulk edit ${recs}`}
          onClose={() => setDialog(null)}
          className="lp-modal--bulk lp-modal--open-list"
          footer={
            <div className="lp-modal__acts lp-modal__acts--start">
              <button
                type="button"
                className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
                disabled={busy || (explicitClear ? editReady === 'off' : !pickedField)}
                onClick={() => {
                  // CT-28: clearing asks first; the confirmation sends it.
                  if (explicitClear && editReady === 'clear') {
                    setError(null);
                    setDialog('edit-clear');
                    return;
                  }
                  const values = editValue();
                  if (values) void run({ action: 'update', values });
                }}
              >
                Update
              </button>
              <button
                type="button"
                className="lp-btn lp-btn--outline"
                onClick={() => setDialog(null)}
              >
                Cancel
              </button>
            </div>
          }
        >
          {error ? <Alert tone="danger">{error}</Alert> : null}
          <div className="lp-field">
            <label>Property to update</label>
            <CustomSelect
              className="lp-bx__select"
              placeholder="Select a property to edit"
              value={field}
              options={editable.map((f) => ({ value: f.key, label: f.label }))}
              onChange={(v) => {
                setField(v);
                setValue('');
                setClearValue(false);
              }}
            />
          </div>
          {pickedField ? (
            <div className="lp-field">
              <label htmlFor={`bulk-${objectType}-value`}>{pickedField.label}</label>
              {pickedField.options ? (
                <CustomSelect
                  id={`bulk-${objectType}-value`}
                  className="lp-bx__select"
                  placeholder="--"
                  value={value}
                  options={pickedField.options}
                  onChange={setValue}
                  disabled={explicitClear && clearValue}
                />
              ) : (
                <input
                  id={`bulk-${objectType}-value`}
                  className="lp-input"
                  type={
                    pickedField.type === 'number'
                      ? 'number'
                      : pickedField.type === 'date'
                        ? 'date'
                        : 'text'
                  }
                  value={value}
                  onChange={(e) => setValue(e.target.value)}
                  disabled={explicitClear && clearValue}
                />
              )}
            </div>
          ) : null}
          {explicitClear && pickedField ? (
            <label className="lp-check">
              <input
                type="checkbox"
                checked={clearValue}
                onChange={(e) => {
                  setClearValue(e.target.checked);
                  // A cleared property has no value: the box empties the control.
                  if (e.target.checked) setValue('');
                }}
              />
              <span>Clear this property</span>
            </label>
          ) : null}
        </LpModal>

        <LpModal
          open={dialog === 'edit-clear'}
          title={`Clear ${pickedField?.label ?? 'property'}?`}
          // Back to Bulk edit with its picks, as Cancel.
          onClose={() => {
            if (busy) return;
            // The clear's error belongs to this dialog, not to Bulk edit.
            setError(null);
            setDialog('edit');
          }}
          className="lp-modal--pick lp-modal--del"
          footer={
            <div className="lp-modal__acts lp-modal__acts--start">
              <button
                type="button"
                className={cn('lp-btn lp-btn--danger', busy && 'is-loading')}
                disabled={busy || !pickedField}
                onClick={() => {
                  if (!pickedField) return;
                  editLabelRef.current = editToast ? pickedField.label : null;
                  void run({ action: 'update', values: bulkClearValues(pickedField) });
                }}
              >
                Clear property
              </button>
              <button
                type="button"
                className="lp-btn lp-btn--outline"
                disabled={busy}
                onClick={() => {
                  setError(null);
                  setDialog('edit');
                }}
              >
                Cancel
              </button>
            </div>
          }
        >
          {error ? <Alert tone="danger">{error}</Alert> : null}
          <p>
            <strong>{pickedField?.label}</strong> will be emptied on {recs}. Their current values
            are removed.
          </p>
        </LpModal>

        <DeleteRecordsDialog
          open={dialog === 'delete'}
          count={count}
          error={error}
          onClose={() => setDialog(null)}
          onConfirm={async () => {
            await run({ action: 'delete' });
          }}
        />

        <LpModal
          open={dialog === 'list'}
          title={`Add ${recs} to a segment`}
          onClose={closeSegment}
          className="lp-modal--pick lp-modal--open-list"
          footer={
            <div className="lp-modal__acts lp-modal__acts--start">
              <button
                type="button"
                className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
                disabled={busy || !listId}
                onClick={() =>
                  void addToSegment(listId, {
                    name: lists.find((l) => l.value === listId)?.label ?? '',
                    isNew: false,
                  })
                }
              >
                Add
              </button>
              <button
                type="button"
                className="lp-btn lp-btn--outline"
                disabled={busy}
                onClick={closeSegment}
              >
                Cancel
              </button>
            </div>
          }
        >
          {error ? <Alert tone="danger">{error}</Alert> : null}
          <div className="lp-field">
            <label>Add {recs} to this segment:</label>
            <CustomSelect
              className="lp-bx__select"
              placeholder="Search"
              searchPlaceholder="Search"
              emptyText={listsLoading ? 'Loading…' : 'No results'}
              value={listId}
              options={lists}
              onChange={setListId}
              footerAction={
                // As the API: a read-only user can't create lists.
                me.role !== 'read_only'
                  ? {
                      label: 'Create new segment',
                      onSelect: () => {
                        setError(null);
                        setSegmentName('');
                        setDialog('segment-new');
                      },
                    }
                  : undefined
              }
            />
          </div>
        </LpModal>

        <LpModal
          open={dialog === 'segment-new'}
          title="Create a new segment"
          onClose={closeSegment}
          className="lp-modal--pick"
          footer={
            <div className="lp-modal__acts lp-modal__acts--start">
              <button
                type="button"
                className={cn('lp-btn lp-btn--primary', (creatingSegment || busy) && 'is-loading')}
                disabled={creatingSegment || busy || !segmentName.trim()}
                onClick={() => void createSegment()}
              >
                Create segment
              </button>
              <button
                type="button"
                className="lp-btn lp-btn--outline"
                disabled={creatingSegment || busy}
                onClick={closeSegment}
              >
                Cancel
              </button>
            </div>
          }
        >
          {error ? <Alert tone="danger">{error}</Alert> : null}
          <div className="lp-field">
            <label htmlFor={`bulk-${objectType}-segment`}>
              Enter a name for your new segment *
            </label>
            <input
              id={`bulk-${objectType}-segment`}
              className="lp-input"
              autoComplete="off"
              maxLength={120}
              value={segmentName}
              onChange={(e) => setSegmentName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') void createSegment();
              }}
            />
          </div>
        </LpModal>

        <LpModal
          open={dialog === 'segment-done'}
          title="Success"
          onClose={() => setDialog(null)}
          className="lp-modal--pick lp-modal--ok"
          footer={
            <div className="lp-modal__acts lp-modal__acts--start">
              <button
                type="button"
                className="lp-btn lp-btn--outline"
                data-autofocus
                onClick={() => setDialog(null)}
              >
                Got it
              </button>
            </div>
          }
        >
          {segmentDone ? (
            <>
              <p>
                <strong>
                  {segmentDone.count.toLocaleString()}{' '}
                  {segmentDone.count === 1 ? (panels?.singular ?? noun) : noun}{' '}
                  {segmentDone.count === 1 ? 'was' : 'were'} added to the{' '}
                  {segmentDone.isNew ? 'new ' : ''}segment:
                </strong>
              </p>
              <ul className="lp-bx__ul lp-seg__ok">
                <li>
                  <a className="lp-bx__a" href="/lists" target="_blank" rel="noopener noreferrer">
                    {segmentDone.name}
                    <LpIcon name="external" className="lp-i--xs" />
                  </a>
                </li>
              </ul>
            </>
          ) : null}
        </LpModal>
        {classicDialogs(['sequence', 'workflow', 'result'])}
      </>
    );
  }

  return (
    <>
      <button
        type="button"
        className="btn-crm btn-crm--outline btn-crm--sm"
        onClick={() => open('owner')}
      >
        Assign
      </button>
      <button
        type="button"
        className="btn-crm btn-crm--outline btn-crm--sm"
        onClick={() => open('edit')}
      >
        Edit
      </button>
      <button
        type="button"
        className="btn-crm btn-crm--outline btn-crm--sm"
        onClick={() => open('list')}
      >
        Add to static list
      </button>
      {objectType === 'contact' ? (
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm"
          onClick={() => open('sequence')}
        >
          Enroll in sequence
        </button>
      ) : null}
      <button
        type="button"
        className="btn-crm btn-crm--outline btn-crm--sm"
        onClick={() => open('workflow')}
      >
        Enroll in workflow
      </button>
      {canDelete ? (
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm crm-text-danger"
          onClick={() => open('delete')}
        >
          Delete
        </button>
      ) : null}
      {result && result.failed > 0 ? (
        <button
          type="button"
          className="btn-crm btn-crm--ghost btn-crm--sm"
          onClick={() => setDialog('result')}
        >
          View last result
        </button>
      ) : null}

      {running ? (
        <div className="bulk-bar__progress" role="status" style={{ flexBasis: '100%' }}>
          <span>
            Working on{' '}
            {running.total
              ? `${running.processed.toLocaleString()} of ${running.total.toLocaleString()}`
              : countText}
            …
          </span>
          <span className="bulk-bar__meter" aria-hidden>
            <span
              style={{
                width: `${running.total ? Math.round((running.processed / running.total) * 100) : 5}%`,
              }}
            />
          </span>
        </div>
      ) : null}

      {classicDialogs(['owner', 'edit', 'list', 'sequence', 'workflow', 'delete', 'result'])}
    </>
  );

  function classicDialogs(which: Dialog[]) {
    const on = (d: Dialog) => which.includes(d);
    return (
      <>
        {on('owner') ? (
          <CrmModal
            id={`bulk-${objectType}-owner`}
            open={dialog === 'owner'}
            onClose={() => setDialog(null)}
          >
            <ModalHeader
              id={`bulk-${objectType}-owner`}
              title={`Assign ${countText}`}
              onClose={() => setDialog(null)}
            />
            <div className="modal__body modal__body--open-list">
              {error ? <Alert tone="danger">{error}</Alert> : null}
              <div className="field">
                <label className="field__label">Owner</label>
                <CustomSelect
                  placeholder="Select owner"
                  value={ownerId}
                  options={[{ value: '__none', label: 'No owner' }, ...ownerOptions]}
                  onChange={setOwnerId}
                />
              </div>
            </div>
            {footer(
              'Assign',
              () =>
                void run({
                  action: 'assign_owner',
                  ownerId: ownerId === '__none' ? null : ownerId,
                }),
              !ownerId,
            )}
          </CrmModal>
        ) : null}

        {on('edit') ? (
          <CrmModal
            id={`bulk-${objectType}-edit`}
            open={dialog === 'edit'}
            onClose={() => setDialog(null)}
          >
            <ModalHeader
              id={`bulk-${objectType}-edit`}
              title={`Edit ${countText}`}
              onClose={() => setDialog(null)}
            />
            <div className="modal__body modal__body--open-list crm-d-grid crm-gap-3">
              {error ? <Alert tone="danger">{error}</Alert> : null}
              <div className="field">
                <label className="field__label">Property to update</label>
                <CustomSelect
                  placeholder="Select property"
                  value={field}
                  options={editable.map((f) => ({ value: f.key, label: f.label }))}
                  onChange={(v) => {
                    setField(v);
                    setValue('');
                  }}
                  menuMinWidth={260}
                />
              </div>
              {pickedField ? (
                <div className="field">
                  <label className="field__label">New value</label>
                  {pickedField.options ? (
                    <CustomSelect
                      placeholder="Select value"
                      value={value}
                      options={pickedField.options}
                      onChange={setValue}
                    />
                  ) : (
                    <input
                      className="input"
                      type={
                        pickedField.type === 'number'
                          ? 'number'
                          : pickedField.type === 'date'
                            ? 'date'
                            : 'text'
                      }
                      value={value}
                      placeholder="Leave empty to clear"
                      onChange={(e) => setValue(e.target.value)}
                    />
                  )}
                </div>
              ) : null}
            </div>
            {footer(
              'Update',
              () => {
                const values = editValue();
                if (values) void run({ action: 'update', values });
              },
              !pickedField,
            )}
          </CrmModal>
        ) : null}

        {on('list') ? (
          <CrmModal
            id={`bulk-${objectType}-list`}
            open={dialog === 'list'}
            onClose={() => setDialog(null)}
          >
            <ModalHeader
              id={`bulk-${objectType}-list`}
              title={`Add ${countText} to a static list`}
              onClose={() => setDialog(null)}
            />
            {/* QA #625: open-list lets the list picker's menu show outside the body. */}
            <div className="modal__body modal__body--open-list">
              {error ? <Alert tone="danger">{error}</Alert> : null}
              <div className="field">
                <label className="field__label">Static list</label>
                <CustomSelect
                  placeholder="Select list"
                  value={listId}
                  options={lists}
                  onChange={setListId}
                />
              </div>
              {lists.length === 0 ? (
                <p className="crm-fs-8 crm-text-muted">No static lists of {noun} yet.</p>
              ) : null}
            </div>
            {footer('Add to list', () => void run({ action: 'add_to_list', listId }), !listId)}
          </CrmModal>
        ) : null}

        {on('sequence') ? (
          <CrmModal
            id={`bulk-${objectType}-sequence`}
            open={dialog === 'sequence'}
            onClose={() => setDialog(null)}
          >
            <ModalHeader
              id={`bulk-${objectType}-sequence`}
              title={`Enroll ${countText} in a sequence`}
              onClose={() => setDialog(null)}
            />
            {dialog === 'sequence' ? (
              <BulkEnrollBody
                objectType={objectType}
                count={count}
                error={error}
                sequences={sequences}
                sequenceRows={sequenceRows}
                sequenceId={sequenceId}
                onSequence={setSequenceId}
                footer={footer}
                onEnroll={(senderMailboxId, choices) =>
                  void run({ action: 'enroll_sequence', sequenceId, senderMailboxId, ...choices })
                }
              />
            ) : null}
          </CrmModal>
        ) : null}

        {on('workflow') ? (
          <CrmModal
            id={`bulk-${objectType}-workflow`}
            open={dialog === 'workflow'}
            onClose={() => setDialog(null)}
          >
            <ModalHeader
              id={`bulk-${objectType}-workflow`}
              title={`Enroll ${countText} in a workflow`}
              onClose={() => setDialog(null)}
            />
            <div className="modal__body modal__body--open-list">
              {error ? <Alert tone="danger">{error}</Alert> : null}
              <div className="field">
                <label className="field__label">Workflow (turned on)</label>
                <CustomSelect
                  placeholder="Select workflow"
                  value={workflowId}
                  options={workflows}
                  onChange={setWorkflowId}
                />
              </div>
            </div>
            {footer(
              'Enroll',
              () => void run({ action: 'enroll_workflow', workflowId }),
              !workflowId,
            )}
          </CrmModal>
        ) : null}

        {on('delete') ? (
          <CrmModal
            id={`bulk-${objectType}-delete`}
            open={dialog === 'delete'}
            onClose={() => setDialog(null)}
          >
            <ModalHeader
              id={`bulk-${objectType}-delete`}
              title={`Delete ${countText}?`}
              onClose={() => setDialog(null)}
            />
            <div className="modal__body">
              {error ? <Alert tone="danger">{error}</Alert> : null}
              <p>They go to the recycle bin and can be restored for 90 days.</p>
            </div>
            {footer('Delete', () => void run({ action: 'delete' }), false, true)}
          </CrmModal>
        ) : null}

        {on('result') ? (
          <CrmModal
            id={`bulk-${objectType}-result`}
            open={dialog === 'result'}
            onClose={() => setDialog(null)}
          >
            <ModalHeader
              id={`bulk-${objectType}-result`}
              title="Bulk action result"
              onClose={() => setDialog(null)}
            />
            <div className="modal__body">
              {result ? (
                <>
                  <p>
                    {result.succeeded.toLocaleString()} changed, {result.failed.toLocaleString()}{' '}
                    could not be changed.
                  </p>
                  <ul className="bulk-result__list">
                    {result.errors.map((e) => (
                      <li key={e.recordId}>
                        <code>{e.recordId.slice(0, 8)}</code> — {e.message}
                      </li>
                    ))}
                  </ul>
                </>
              ) : null}
            </div>
          </CrmModal>
        ) : null}
      </>
    );
  }
}

export type DesignAct = {
  label: string;
  icon?: LpIconName;
  run?: () => void;
  /** Shown disabled. */
  off?: boolean;
  /** No icon (the design's long, disabled items). */
  plain?: boolean;
  /** CT-11: hover text (why the action is disabled), in the bar and in More. */
  title?: string;
};

/** The design's bar per object: buttons in the bar, then the More menu. */
const DESIGN_BULK: Record<string, { bar: string[]; more: string[] }> = {
  contact: {
    bar: ['enrich', 'smart', 'assign', 'share', 'edit', 'del'],
    more: [
      'assoc',
      'tasks',
      'sequence',
      'leads',
      'agent',
      'coverage',
      'segment',
      'workflow',
      'dialer',
      'legal',
      'subs',
      'optin',
    ],
  },
  company: {
    bar: ['enrich', 'smart', 'assign', 'share', 'edit', 'del'],
    more: [
      'assoc',
      'tasks',
      'segment',
      'workflow',
      'dialer',
      'leads',
      'agent',
      'coverage',
      'intent',
    ],
  },
  deal: {
    bar: ['assign', 'smart', 'share', 'edit', 'del', 'assoc'],
    more: ['segment', 'tasks', 'workflow', 'dialer'],
  },
};

function ownerLabel(objectType: string): string {
  return objectType === 'company'
    ? 'Company owner'
    : objectType === 'deal'
      ? 'Deal owner'
      : 'Contact owner';
}

/**
 * B9, point 30: how the More menu opens. With `flipMore`, as the design's `menu()` (list-page.js
 * :651, `place()` :572-582): a menu's 4 px gap and its flip. Without it, master's popover.
 */
export function bulkMorePopover(flipMore = false): {
  align: 'end';
  flip?: boolean;
  gap?: number;
} {
  return flipMore ? { align: 'end', flip: true, gap: 4 } : { align: 'end' };
}

/** GLB5: the everyday bulk actions, kept on the bar with `keepPrimaryActions`. */
export const PRIMARY_BULK_ACTS: readonly string[] = ['assign', 'share', 'edit', 'del'];

/**
 * The order the bar's buttons move into "More" when they don't fit: as the design's `fitBulk`
 * (list-page.js:2957-2967), the last one first. With `keepPrimary` (GLB5) the other buttons go
 * first (right to left), then the primary ones (right to left).
 */
export function bulkHideOrder(bar: readonly string[], keepPrimary = false): number[] {
  const order = bar.map((_, i) => i).reverse();
  if (!keepPrimary) return order;
  const primary = (i: number) => PRIMARY_BULK_ACTS.includes(bar[i]!);
  return [...order.filter((i) => !primary(i)), ...order.filter(primary)];
}

/**
 * The bar's buttons; those that don't fit move to the top of "More" (list-page.js `fitBulk`).
 */
export function DesignBulkButtons({
  acts,
  bar,
  more,
  flipMore = false,
  keepPrimaryActions = false,
  dim = false,
}: {
  acts: Record<string, DesignAct>;
  bar: string[];
  more: string[];
  /** B9, point 30: the design's flip for the More menu (Companies, Contacts). */
  flipMore?: boolean;
  /** GLB5 (Contacts, Companies): move the other buttons into More before Assign/Share/Edit/Delete. */
  keepPrimaryActions?: boolean;
  /** CT-11: disabled bar buttons look disabled (`lp-bulk__acts--dim`; Contacts, Companies). */
  dim?: boolean;
}) {
  const boxRef = useRef<HTMLDivElement>(null);
  const moreRef = useRef<HTMLButtonElement>(null);
  /** The bar's buttons that moved into More, by key. */
  const [hidden, setHidden] = useState<string[]>([]);
  const [open, setOpen] = useState(false);
  const barKey = bar.join(',');
  const fit = useCallback(() => {
    const box = boxRef.current;
    const wrap = box?.closest('.lp-bulk');
    if (!box || !wrap) return;
    const btns = Array.from(box.querySelectorAll<HTMLElement>('[data-bulk-act]'));
    btns.forEach((b) => (b.hidden = false));
    const left = wrap.querySelector<HTMLElement>('.lp-bulk__left');
    const x = wrap.querySelector<HTMLElement>('.lp-bulk__x');
    const room = wrap.clientWidth - (left?.offsetWidth ?? 0) - (x?.offsetWidth ?? 0) - 64;
    const used = () =>
      Array.from(box.children).reduce(
        (w, c) => w + ((c as HTMLElement).hidden ? 0 : (c as HTMLElement).offsetWidth + 4),
        0,
      );
    const gone: string[] = [];
    for (const i of bulkHideOrder(
      btns.map((b) => b.dataset.bulkAct ?? ''),
      keepPrimaryActions,
    )) {
      if (used() <= room) break;
      btns[i]!.hidden = true;
      gone.push(btns[i]!.dataset.bulkAct ?? '');
    }
    const next = barKey.split(',').filter((k) => gone.includes(k));
    setHidden((cur) => (cur.join(',') === next.join(',') ? cur : next));
  }, [keepPrimaryActions, barKey]);
  useLayoutEffect(fit);
  useEffect(() => {
    const wrap = boxRef.current?.closest('.lp-bulk');
    if (!wrap || typeof ResizeObserver === 'undefined') return;
    const ro = new ResizeObserver(() => fit());
    ro.observe(wrap);
    return () => ro.disconnect();
  }, [fit]);
  const item = (k: string): LpMenuItem => {
    const a = acts[k]!;
    return {
      key: k,
      label: a.label,
      icon: a.plain ? undefined : a.icon,
      disabled: Boolean(a.off),
      onSelect: a.run,
      title: a.title,
    };
  };
  const overflow = bar.filter((k) => hidden.includes(k));
  return (
    <div className={cn('lp-bulk__acts', dim && 'lp-bulk__acts--dim')} ref={boxRef}>
      {bar.map((k) => {
        const a = acts[k]!;
        return (
          <button
            key={k}
            type="button"
            className="lp-bulkbtn"
            data-bulk-act={k}
            disabled={a.off}
            title={a.title}
            onClick={a.run}
          >
            {a.icon ? <LpIcon name={a.icon} /> : null}
            {a.label}
          </button>
        );
      })}
      <button
        ref={moreRef}
        type="button"
        className={cn('lp-bulkbtn', open && 'is-open')}
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}
      >
        More
        <LpIcon name="caret" />
      </button>
      <LpPopover
        pop="menu"
        open={open}
        anchorRef={moreRef}
        onClose={() => setOpen(false)}
        label="More bulk actions"
        className="lp-pop--menu lp-menu--bulk"
        {...bulkMorePopover(flipMore)}
      >
        <LpMenu
          label="More bulk actions"
          onClose={() => setOpen(false)}
          items={[...overflow, ...more].map(item)}
        />
      </LpPopover>
    </div>
  );
}

/**
 * B10, point 29: the design's Assign list (list-page.js:2747): "No owner" first, then the owners,
 * the person's own name marked "(me)".
 */
/** "No owner" in the Assign list. */
export const ASSIGN_NONE = '__none';

/**
 * B10, point 29: what Update sends, and the name for the design's toast (list-page.js:2741-2743):
 * "No owner" clears the owner (`null`).
 */
export function assignTarget(
  picked: string,
  owners: CustomSelectOption[],
): { ownerId: string | null; to: string | null } {
  if (picked === ASSIGN_NONE) return { ownerId: null, to: null };
  return { ownerId: picked, to: owners.find((o) => o.value === picked)?.label ?? null };
}

export function assignOptions(
  owners: CustomSelectOption[],
  meId: string | undefined,
): CustomSelectOption[] {
  return [
    { value: ASSIGN_NONE, label: 'No owner' },
    ...owners.map((o) => (o.value === meId ? { ...o, label: `${o.label} (me)` } : o)),
  ];
}

/**
 * B10, point 29: what the design's toast names after Update: the owner, or "unassigned" for "No
 * owner". An owner whose name isn't in the list (it reloaded since the pick) gets the generic toast.
 */
export function assignToastOf(target: {
  ownerId: string | null;
  to: string | null;
}): { to: string | null } | null {
  return target.ownerId && !target.to ? null : { to: target.to };
}
