'use client';

/**
 * DI-3: the contact segment page, one contact list (`view-contact-segment.php`). Header, tabs,
 * filter pane and the Overview tab are here; Performance, Activity, Settings and the contact
 * preview drawer have their own files. Design paths: PHP = `view-contact-segment.php`,
 * JS = `assets/js/view-contact-segment.js` in `assetsUI/data-integration-06-11-2026/data-integration-06-11-2026/`.
 */
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmIcon } from '@/components/crm/CrmIcon';
import type { CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { BulkActionsBar, type BulkRequest } from '@/features/bulk/ui/BulkActionsBar';
import type { BxRecord } from '@/features/bulk/ui/DesignBulkPanels';
import { listContacts } from '@/features/contacts/api.client';
import type { ContactListItem } from '@/features/contacts/types';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { ExportButton } from '@/features/exports/ui/ExportButton';
import { getFilterFields, type FilterFieldInfo } from '@/features/filters/api.client';
import { useListNames, useListNameState } from '@/features/filters/useListNames';
import {
  deleteList,
  getList,
  convertListToStatic,
  rebuildList,
  updateList,
  type CrmList,
  type ListMember,
} from '@/features/lists/api.client';
import { canDeleteSegment } from '@/features/lists/segmentsIndex';
import { shownProblems, type FilterApiProblems } from '@/features/lists/segmentSize';
import { AddToListModal } from '@/features/objects/ui/AddToListModal';
import { listAllOwners, type Owner } from '@/features/owners/api.client';
import { ownerAssignOptions } from '@/features/owners/labels';
import { useFieldAccess } from '@/features/permission-sets/field-access';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { listPicklistOptions } from '@/features/picklists/api.client';
import type { Filter } from '@/features/views/types';
import { FilterEditor } from '@/features/workflows/ui/FilterEditor';
import { problemsFromError } from '@/features/workflows/ui/shared';
import {
  filterPathLabel,
  filterProblems,
  SEGMENT_MAX_CONDITIONS,
} from '@/features/filters/filterProblems';
import {
  loadValueOptionSources,
  NO_SOURCES,
  type ValueOptionSources,
} from '@/features/workflows/ui/filterValueOptions';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  allMatchingRows,
  selectAllApplies,
  bulkRoute,
  deleteListErrorText,
  disabledBulkActs,
  disabledHeaderActions,
  isMissingList,
  oneRemovedText,
  removeMembersInChunks,
  segmentAccess,
  segmentAllExportColumns,
  segmentExportColumns,
  segmentExportFilters,
  selectedRows,
} from '../actions';
import { weekChange, weekChangeQuery, weekChangeText } from '../history';
import {
  ACTION_ITEMS,
  buildPollDelay,
  byText,
  isProcessing,
  PROCESSED_NOTICE,
  PROCESSING_NOTICE,
  PROCESSING_POLL_MS,
  dropColumn,
  BULK_BUTTONS,
  BULK_MORE,
  COLUMN_GROUPS,
  DEFAULT_COLUMNS,
  DEFAULT_PAGE_SIZE,
  NO_VALUE,
  PAGE_SIZES,
  SEGMENT_COLUMNS,
  cellText,
  columnOf,
  contactName,
  createdOnText,
  filterLineItems,
  filterValueLabel,
  longDateText,
  moveColumn,
  nextSort,
  pageCount,
  pagerItems,
  SWITCH_TOASTS,
  filterPaneAfterResize,
  filterPaneClosesOnClick,
  pageSizeToast,
  pageToast,
  percentOfDatabase,
  segmentContactsFilter,
  segmentSizeBadge,
  segmentSubtitle,
  segmentTypeLabel,
  selectedText,
  sortGlyph,
  toggleColumn,
  type SegmentColumnKey,
} from '../segment';
import { ActivityPane } from './ActivityPane';
import { CloneSegmentModal } from './CloneSegmentModal';
import { useSizes } from './SizeCharts';
import { ContactPreviewDrawer } from './ContactPreviewDrawer';
import { PerformancePane, type PerfSubview } from './PerformancePane';
import { RecordSegmentView } from './RecordSegmentView';
import { AddContactsModal } from './AddContactsModal';
import { SegDrawer, SegDropdown, SegModal } from './primitives';
import { SettingsPane } from './SettingsPane';

export type SegmentTab = 'overview' | 'performance' | 'activity' | 'settings';
type Sort = { key: SegmentColumnKey; dir: 'asc' | 'desc' };
type Option = { value: string; label: string; archived?: boolean };

const TABS: readonly { id: SegmentTab; label: string }[] = [
  { id: 'overview', label: 'Overview' },
  { id: 'performance', label: 'Performance' },
  { id: 'activity', label: 'Activity' },
  { id: 'settings', label: 'Settings' },
];

/** Clipboard copy that reports only what happened (the design toasts success either way, JS:4352-4372). */
async function copyText(value: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(value);
    return true;
  } catch {
    return false;
  }
}

// ---------------------------------------------------------------------------
// Header (PHP:35-114)
// ---------------------------------------------------------------------------

export function SegmentHeader({
  list,
  onAction,
  disabled,
  onRename,
}: {
  list: CrmList;
  /** A `data-vcs-action` of the header (clone, details, remix, channels, share, compare, …). */
  onAction: (action: string, label: string) => void;
  /** Actions items the user has no right to (`disabledHeaderActions`), shown disabled. */
  disabled?: ReadonlySet<string>;
  /**
   * QA #637: renames the segment (resolves true when saved). Left out when the caller may not
   * rename it (QA #644: its creator and Super Admins only): the title is then plain text.
   */
  onRename?: (name: string) => Promise<boolean>;
}) {
  return (
    <>
      <Link href="/lists" className="vcs-breadcrumb">
        <CrmIcon name="chevron-left" className="iconSize-14" />
        <span>Back to segments</span>
      </Link>

      <div className="vcs-header">
        <div className="vcs-header__main">
          <div className="vcs-header__title-row">
            {onRename ? (
              <SegmentTitle name={list.name} onRename={onRename} />
            ) : (
              <h1 className="vcs-title">{list.name}</h1>
            )}
            <span className="vcs-badge">Contacts</span>
            <span className="vcs-badge vcs-badge--static">{segmentSizeBadge(list)}</span>
          </div>
          <p className="vcs-subtitle">{segmentSubtitle(list)}</p>
        </div>

        <div className="vcs-header__actions">
          <button
            type="button"
            className="lp-btn lp-btn--outline"
            data-vcs-action="clone"
            onClick={() => onAction('clone', 'Clone')}
          >
            Clone
          </button>
          <button
            type="button"
            className="lp-btn lp-btn--outline"
            id="vcsDetailsBtn"
            data-vcs-action="details"
            onClick={() => onAction('details', 'Details')}
          >
            Details
          </button>

          <SegDropdown
            toggleClassName="lp-btn lp-btn--outline"
            toggleId="vcsUseInBtn"
            // S-08: HubSpot disables Use in and Actions while the segment processes.
            toggleDisabled={isProcessing(list)}
            toggle={
              <>
                <span>Use in</span>
                <CrmIcon name="chevron-down" className="iconSize-14" />
              </>
            }
          >
            <Link
              href={`/contacts?segment=${encodeURIComponent(list.id)}`}
              className="dropdown__item vcs-usein-item"
              id="vcsUseInContacts"
            >
              <span>Contacts view</span>
              <CrmIcon name="external" className="iconSize-14" />
            </Link>
            <Link
              // 997: open a new workflow that enrolls this segment's members.
              href={`/workflows?new=1&trigger=segment&listId=${encodeURIComponent(list.id)}&objectType=${encodeURIComponent(list.objectType)}`}
              className="dropdown__item vcs-usein-item"
              id="vcsUseInWorkflows"
            >
              <span>Workflows</span>
              <CrmIcon name="external" className="iconSize-14" />
            </Link>
            <Link href="/reports" className="dropdown__item vcs-usein-item" id="vcsUseInReports">
              <span>Custom report builder</span>
              <CrmIcon name="external" className="iconSize-14" />
            </Link>
            <div className="dropdown__divider" />
            <button
              type="button"
              className="dropdown__item"
              data-vcs-action="channels"
              onClick={() => onAction('channels', 'See more channels')}
            >
              See more channels
            </button>
          </SegDropdown>

          <SegDropdown
            toggleClassName="lp-btn lp-btn--primary"
            toggleId="vcsActionsBtn"
            toggleDisabled={isProcessing(list)}
            toggle={
              <>
                <span>Actions</span>
                <CrmIcon name="chevron-down" className="iconSize-14" />
              </>
            }
          >
            {ACTION_ITEMS.filter(
              (item) =>
                (item.action !== 'convert-static' || list.listType === 'active') &&
                (item.action !== 'add-contacts' || list.listType === 'static'),
            ).map((item) => (
              <ActionItem
                key={item.action}
                item={item}
                onAction={onAction}
                disabled={disabled?.has(item.action) ?? false}
              />
            ))}
          </SegDropdown>
        </div>
      </div>
    </>
  );
}

/**
 * QA #637 (design PHP:731-737): click the title (or its pencil) to rename; Enter or leaving the
 * box saves, Escape cancels. An empty or unchanged name is not sent.
 */
export function SegmentTitle({
  name,
  onRename,
}: {
  name: string;
  onRename: (name: string) => Promise<boolean>;
}) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(name);
  const [saving, setSaving] = useState(false);
  const start = () => {
    setDraft(name);
    setEditing(true);
  };
  const commit = async () => {
    const next = draft.trim();
    if (saving) return;
    if (!next || next === name) {
      setEditing(false);
      return;
    }
    setSaving(true);
    const ok = await onRename(next);
    setSaving(false);
    if (ok) setEditing(false);
  };
  return (
    <div className="vcs-title-wrap" id="vcsTitleWrap">
      {editing ? (
        <input
          type="text"
          className="vcs-title-input"
          id="vcsTitleInput"
          maxLength={191}
          value={draft}
          aria-label="Edit segment name"
          autoComplete="off"
          autoFocus
          disabled={saving}
          onChange={(e) => setDraft(e.target.value)}
          onBlur={() => void commit()}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              e.preventDefault();
              void commit();
            } else if (e.key === 'Escape') {
              e.preventDefault();
              e.stopPropagation();
              setEditing(false);
            }
          }}
        />
      ) : (
        <>
          <h1
            className="vcs-title"
            id="vcsTitle"
            tabIndex={0}
            role="button"
            aria-label="Edit segment name"
            title="Click to edit segment name"
            onClick={start}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                start();
              }
            }}
          >
            {name}
          </h1>
          <button
            type="button"
            className="lp-icon-btn lp-icon-btn--sm vcs-title-edit-btn"
            id="vcsTitleEditBtn"
            aria-label="Edit segment name"
            title="Edit segment name"
            onClick={start}
          >
            <CrmIcon name="pencil" className="iconSize-14" />
          </button>
        </>
      )}
    </div>
  );
}

function ActionItem({
  item,
  onAction,
  disabled,
}: {
  item: (typeof ACTION_ITEMS)[number];
  onAction: (action: string, label: string) => void;
  disabled: boolean;
}) {
  return (
    <>
      {item.danger ? <div className="dropdown__divider" /> : null}
      <button
        type="button"
        className={cn('dropdown__item', item.danger && 'is-danger')}
        data-vcs-action={item.action}
        disabled={disabled}
        onClick={() => onAction(item.action, item.label)}
      >
        {item.label}
      </button>
    </>
  );
}

// ---------------------------------------------------------------------------
// Tabs (PHP:117-122)
// ---------------------------------------------------------------------------

export function SegmentTabs({ tab, onTab }: { tab: SegmentTab; onTab: (t: SegmentTab) => void }) {
  return (
    <nav className="vcs-tabs" aria-label="Segment tabs">
      {TABS.map((t) => (
        <button
          key={t.id}
          type="button"
          className={cn('vcs-tab', tab === t.id && 'is-active')}
          data-vcs-tab={t.id}
          onClick={() => onTab(t.id)}
        >
          {t.label}
        </button>
      ))}
    </nav>
  );
}

// ---------------------------------------------------------------------------
// Filter pane (PHP:128-143)
// ---------------------------------------------------------------------------

/**
 * The filter text's value labels ("Client - Active", not "client_active"): the object's field
 * types and the filter editor's choices (both loaded once a page). Until they load, or when
 * they fail, values show as stored.
 */
function useFilterValueLabel(objectType: string, enabled: boolean) {
  const [fields, setFields] = useState<FilterFieldInfo[] | null>(null);
  const [sources, setSources] = useState<ValueOptionSources>(NO_SOURCES);
  useEffect(() => {
    if (!enabled) return;
    let alive = true;
    getFilterFields(objectType).then(
      (res) => alive && setFields(res.fields),
      () => undefined,
    );
    loadValueOptionSources(objectType).then(
      (found) => alive && setSources(found),
      () => undefined,
    );
    return () => {
      alive = false;
    };
  }, [objectType, enabled]);
  return useMemo(() => filterValueLabel(fields, sources), [fields, sources]);
}

export function FilterPane({
  list,
  collapsed,
  hidden,
  onCollapse,
  onEdit,
  readOnly = false,
}: {
  list: CrmList;
  collapsed: boolean;
  /** Not on Overview (JS:2205-2209). */
  hidden: boolean;
  onCollapse: () => void;
  onEdit?: () => void;
  /** A static segment's filters are shown only: no Edit. */
  readOnly?: boolean;
}) {
  const valueLabel = useFilterValueLabel(list.objectType, list.filter !== null);
  const segments = useListNameState(list.objectType, list.filter);
  const lines = filterLineItems(
    list.filter,
    valueLabel,
    (id) => segments.names.get(id),
    segments.loaded,
  );
  return (
    <aside
      className={cn(
        'vcs-filter-pane',
        collapsed && 'is-collapsed',
        hidden && 'vcs-filter-pane--hidden',
      )}
      id="vcsFilterPane"
      aria-label="Filters"
    >
      <div className="vcs-filter-pane__head">
        <div className="vcs-filter-pane__title-wrap">
          <h2 className="vcs-filter-pane__title">Filters</h2>
          {!readOnly ? (
            <button
              type="button"
              className="vcs-filter-pane__edit"
              data-vcs-action="edit-filters"
              // S-08: no editing until the last edit's members are worked out.
              disabled={isProcessing(list)}
              onClick={onEdit}
            >
              Edit
            </button>
          ) : null}
        </div>
        <button
          type="button"
          className="vcs-filter-pane__collapse-btn"
          id="vcsCollapseFilters"
          aria-label="Collapse filters panel"
          title="Collapse filters"
          onClick={onCollapse}
        >
          <CrmIcon name="chevrons-left" className="iconSize-16" />
        </button>
      </div>
      <div className="vcs-filter-pane__body">
        {lines.length === 0 ? (
          <p className="crm-mb-0">This segment doesn&apos;t have any filters.</p>
        ) : (
          lines.map((line, i) => (
            <Fragment key={i}>
              <p className={cn('crm-mb-0', line.text === 'or' && 'crm-text-muted')}>{line.text}</p>
              {line.error ? <p className="crm-mb-0 crm-text-danger">{line.error}</p> : null}
            </Fragment>
          ))
        )}
      </div>
    </aside>
  );
}

// ---------------------------------------------------------------------------
// Metrics bar (PHP:150-190)
// ---------------------------------------------------------------------------

export function MetricsBar({
  list,
  allContacts,
  hidden,
  weekChange = null,
  onPerformance,
  onDetails,
}: {
  list: CrmList;
  /** Every contact the user can see (GET /contacts total); null until known. */
  allContacts: number | null;
  hidden: boolean;
  /** Size now minus a week ago (the size history); null until known or when it failed. */
  weekChange?: number | null;
  onPerformance: () => void;
  onDetails: () => void;
}) {
  const { timeZone } = useUserPrefs();
  return (
    <div className={cn('vcs-metrics-bar crm-mb-3', hidden && 'is-hidden')} id="vcsMetricsBar">
      <div className="vcs-metric-cell">
        <span className="vcs-metric-label">SIZE</span>
        {/* S-08: HubSpot leaves SIZE and % OF DATABASE blank while it processes. */}
        <span className="vcs-metric-val">{isProcessing(list) ? '' : list.memberCount}</span>
        <a
          href="#"
          className="vcs-metric-sub"
          data-vcs-tab-switch="performance"
          onClick={(e) => {
            e.preventDefault();
            onPerformance();
          }}
        >
          View performance
        </a>
      </div>

      <div className="vcs-metric-cell">
        <span className="vcs-metric-label">% OF DATABASE</span>
        <span className="vcs-metric-val">
          {isProcessing(list) ? '' : percentOfDatabase(list.memberCount, allContacts)}
        </span>
        <span className="vcs-metric-sub vcs-metric-sub--muted">All contacts</span>
      </div>

      <div className="vcs-metric-cell">
        <span className="vcs-metric-label vcs-metric-label--wrap">
          PREDICTED EMAIL ENGAGEMENT{' '}
          <span
            title="Predicted email engagement score based on contact behavior"
            className="crm-cursor-help"
          >
            <CrmIcon name="info" className="iconSize-14" />
          </span>
        </span>
        <span className="vcs-metric-val">{NO_VALUE}</span>
      </div>

      <div className="vcs-metric-cell">
        <span className="vcs-metric-label">7-DAY CHANGE</span>
        <span className="vcs-metric-val">
          {isProcessing(list) ? NO_VALUE : weekChangeText(weekChange)}
        </span>
      </div>

      <div className="vcs-metric-cell">
        <span className="vcs-metric-label">CREATED ON</span>
        <span className="vcs-metric-val">{createdOnText(list.createdAt, timeZone)}</span>
        <button
          type="button"
          className="vcs-metric-sub"
          data-vcs-action="view-details"
          onClick={onDetails}
        >
          View details
        </button>
      </div>

      <div className="vcs-metric-cell">
        <span className="vcs-metric-label">TYPE</span>
        <span className="vcs-metric-val crm-d-flex crm-align-items-center crm-gap-1">
          <span className="crm-text-muted">+</span> {segmentTypeLabel(list)}
        </span>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Toolbar (PHP:193-241)
// ---------------------------------------------------------------------------

export function SegmentToolbar({
  search,
  onSearch,
  onEditColumns,
  onExport,
  filtersOpen,
  onToggleFilters,
  metricsOpen,
  onToggleMetrics,
  exportDisabled = false,
}: {
  search: string;
  onSearch: (q: string) => void;
  onEditColumns: () => void;
  onExport: () => void;
  filtersOpen: boolean;
  onToggleFilters: () => void;
  metricsOpen: boolean;
  onToggleMetrics: () => void;
  /** No export right (`rules.app.export`). */
  exportDisabled?: boolean;
}) {
  return (
    <div className="vcs-toolbar crm-mb-3">
      <div className="vcs-toolbar__left">
        <div className="vcs-search-input">
          <CrmIcon name="search" className="iconSize-16" />
          <input
            type="search"
            id="vcsSearchInput"
            placeholder="Search in segment"
            autoComplete="off"
            value={search}
            onChange={(e) => onSearch(e.target.value)}
          />
        </div>
      </div>

      <div className="vcs-toolbar__right">
        <SegDropdown
          toggleClassName="lp-btn lp-btn--outline"
          toggle={
            <>
              <span>Personal view</span>
              <CrmIcon name="chevron-down" className="iconSize-14" />
            </>
          }
        >
          <button
            type="button"
            className="dropdown__item crm-d-flex crm-align-items-center crm-justify-content-between"
          >
            <span>Personal view</span>
            <CrmIcon name="check" className="iconSize-14" />
          </button>
        </SegDropdown>

        <button
          type="button"
          className="lp-btn lp-btn--outline"
          id="vcsOpenColsModal"
          onClick={onEditColumns}
        >
          Edit columns
        </button>

        <button
          type="button"
          className="lp-btn lp-btn--outline"
          data-vcs-action="export"
          disabled={exportDisabled}
          onClick={onExport}
        >
          Export segment
        </button>

        <button
          type="button"
          className={cn('lp-btn lp-btn--outline', filtersOpen && 'is-active')}
          id="vcsToggleFilters"
          title="Toggle filters panel"
          onClick={onToggleFilters}
        >
          <CrmIcon name="funnel" className="iconSize-14" />
          <span>Filters</span>
        </button>

        <button
          type="button"
          className={cn('lp-btn lp-btn--outline', metricsOpen && 'is-active')}
          id="vcsToggleMetrics"
          title="Toggle metrics panel"
          onClick={onToggleMetrics}
        >
          <CrmIcon name="chart" className="iconSize-14" />
          <span>Metrics</span>
        </button>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Bulk bar (PHP:244-309)
// ---------------------------------------------------------------------------

export function BulkBar({
  count,
  onAct,
  onClear,
  disabled,
}: {
  count: number;
  onAct: (act: string, label: string) => void;
  onClear: () => void;
  /** Acts shown disabled (`disabledBulkActs`: list type and rights). */
  disabled?: ReadonlySet<string>;
}) {
  return (
    <div
      className="lp-bulk vcs-bulk-toolbar"
      id="vcsBulkBar"
      role="region"
      aria-label="Bulk actions"
      hidden={count === 0}
    >
      <div className="lp-bulk__left">
        <strong id="vcsBulkCount">{selectedText(count)}</strong>
      </div>
      <div className="lp-bulk__acts">
        {BULK_BUTTONS.map((b) => {
          const button = (
            <button
              key={b.act}
              type="button"
              className="lp-bulkbtn"
              data-vcs-bulk-act={b.act}
              disabled={disabled?.has(b.act) ?? false}
              onClick={() => onAct(b.act, b.label)}
            >
              <CrmIcon name={b.icon} className="iconSize-14" />
              <span>{b.label}</span>
            </button>
          );
          return b.tooltip ? (
            <div key={b.act} className="vcs-tooltip-trigger" data-tooltip={b.tooltip}>
              {button}
            </div>
          ) : (
            button
          );
        })}

        <SegDropdown
          toggleClassName="lp-bulkbtn"
          toggle={
            <>
              <span>More</span>
              <CrmIcon name="chevron-down" className="iconSize-12" />
            </>
          }
        >
          {BULK_MORE.map((m) => (
            <button
              key={m.act}
              type="button"
              className={cn('dropdown__item', m.danger && 'is-danger')}
              data-vcs-bulk-act={m.act}
              disabled={disabled?.has(m.act) ?? false}
              onClick={() => onAct(m.act, m.label)}
            >
              {m.label}
            </button>
          ))}
        </SegDropdown>
      </div>
      <button
        type="button"
        className="lp-icon-btn lp-bulk__x"
        id="vcsClearSelection"
        aria-label="Clear selection"
        title="Clear selection"
        onClick={onClear}
      >
        <CrmIcon name="x" className="iconSize-14" />
      </button>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Table (JS:2339-2527)
// ---------------------------------------------------------------------------

function Cell({
  row,
  col,
  labelOf,
  onPreview,
}: {
  row: ContactListItem;
  col: SegmentColumnKey;
  labelOf: (field: 'leadStatus' | 'lifecycleStage', value: string) => string;
  onPreview: (id: string) => void;
}) {
  const { timeZone } = useUserPrefs();
  switch (col) {
    case 'name':
      return (
        <td className="vcs-td vcs-td--sticky-name">
          <div className="vcs-name-cell">
            <div className="vcs-name-main">
              <Link href={`/contacts/${row.id}`} className="vcs-contact-name">
                {contactName(row)}
              </Link>
            </div>
            <button
              type="button"
              className="vcs-preview-btn"
              data-open-preview={row.id}
              onClick={(e) => {
                e.preventDefault();
                onPreview(row.id);
              }}
            >
              Preview
            </button>
          </div>
        </td>
      );
    case 'email':
      return row.email ? (
        <td className="vcs-td">
          <a
            href={`mailto:${row.email}`}
            className="crm-text-brand"
            style={{ color: 'var(--brand)', textDecoration: 'none' }}
          >
            {row.email}
          </a>
        </td>
      ) : (
        <td className="vcs-td crm-text-muted">{NO_VALUE}</td>
      );
    case 'phone':
      return <td className="vcs-td crm-text-muted">{cellText(row, 'phone')}</td>;
    case 'owner':
      return row.owner?.name ? (
        <td className="vcs-td">
          <div className="vcs-owner-cell">
            <span className="vcs-owner-avatar">{row.owner.name.charAt(0)}</span>
            <span>{row.owner.name}</span>
          </div>
        </td>
      ) : (
        <td className="vcs-td crm-text-muted">No owner</td>
      );
    case 'company':
      return row.company?.name ? (
        <td className="vcs-td">
          <div className="vcs-company-badge">
            <span className="vcs-co-icon">{row.company.name.charAt(0)}</span>
            <span>{row.company.name}</span>
          </div>
        </td>
      ) : (
        <td className="vcs-td crm-text-muted">{NO_VALUE}</td>
      );
    case 'leadStatus':
      return row.leadStatus ? (
        <td className="vcs-td">
          <span className="badge badge--solid-info">{labelOf('leadStatus', row.leadStatus)}</span>
        </td>
      ) : (
        <td className="vcs-td crm-text-muted">{NO_VALUE}</td>
      );
    case 'lifecycle':
      return (
        <td className="vcs-td">
          {row.lifecycleStage ? labelOf('lifecycleStage', row.lifecycleStage) : NO_VALUE}
        </td>
      );
    case 'lastActivity':
    case 'marketableStatus':
    case 'createDate':
      return <td className="vcs-td crm-text-muted">{cellText(row, col, timeZone)}</td>;
    default:
      return <td className="vcs-td">{cellText(row, col, timeZone)}</td>;
  }
}

export function SegmentTable({
  rows,
  cols,
  sort,
  onSort,
  selected,
  onToggle,
  onToggleAll,
  onPreview,
  searching,
  loading,
  failed = false,
  labelOf = (_f, v) => v,
  selectAllBusy = false,
  building = false,
  processing = false,
}: {
  rows: ContactListItem[];
  cols: SegmentColumnKey[];
  sort: Sort;
  onSort: (key: SegmentColumnKey) => void;
  selected: Set<string>;
  onToggle: (id: string, on: boolean) => void;
  /** SEG2b C9: check selects every row matching the search (all pages); uncheck clears all. */
  onToggleAll: (on: boolean) => void;
  /** Select all's rows are loading: the checkbox waits. */
  selectAllBusy?: boolean;
  onPreview: (id: string) => void;
  searching: boolean;
  loading: boolean;
  /** SEG1 A1: the members didn't load (the toast says why): no "empty segment" text. */
  failed?: boolean;
  labelOf?: (field: 'leadStatus' | 'lifecycleStage', value: string) => string;
  /** The segment's first build is still running: its members aren't known yet. */
  building?: boolean;
  /** S-08: the members are being worked out again: a spinner, no rows (as HubSpot). */
  processing?: boolean;
}) {
  const allOn = rows.length > 0 && rows.every((r) => selected.has(r.id));
  return (
    <div className="vcs-table-wrap">
      <table className="vcs-table">
        <thead>
          <tr id="vcsTableHeader">
            <th scope="col" className="vcs-th vcs-th--sticky-cb">
              <input
                type="checkbox"
                id="vcsSelectAll"
                aria-label="Select all rows"
                checked={allOn}
                disabled={selectAllBusy}
                onChange={(e) => onToggleAll(e.target.checked)}
              />
            </th>
            {cols.map((key) => {
              const col = columnOf(key);
              const sortable = col.sortField !== null;
              return (
                <th
                  key={key}
                  scope="col"
                  className={cn(
                    'vcs-th',
                    sortable && 'vcs-th--sortable',
                    key === 'name' && 'vcs-th--sticky-name',
                  )}
                  data-sort-key={key}
                  onClick={sortable ? () => onSort(key) : undefined}
                >
                  <div className="vcs-th__inner">
                    <span>{col.label}</span>
                    <span className="vcs-th-sort-icon" style={{ fontSize: 10 }}>
                      {sortable ? sortGlyph(sort, key) : ''}
                    </span>
                  </div>
                </th>
              );
            })}
          </tr>
        </thead>
        <tbody id="vcsTableBody">
          {processing ? (
            <tr>
              <td colSpan={cols.length + 1} className="crm-text-center crm-p-5">
                <span
                  className="vcs-processing-spinner"
                  role="status"
                  aria-label="Processing the segment"
                />
              </td>
            </tr>
          ) : failed ? null : !loading && rows.length === 0 ? (
            <tr>
              <td colSpan={cols.length + 1} className="crm-text-center crm-p-5 crm-text-muted">
                <div style={{ padding: '30px 0' }}>
                  <p className="crm-fw-semibold crm-fs-6">
                    {searching
                      ? 'No contacts match your search'
                      : building
                        ? 'Processing the segment…'
                        : 'No contacts in this segment'}
                  </p>
                  {searching ? (
                    <p className="crm-text-subtle crm-fs-8">Try clearing your search term</p>
                  ) : null}
                </div>
              </td>
            </tr>
          ) : (
            rows.map((r) => (
              <tr key={r.id} className="vcs-row" data-contact-id={r.id}>
                <td className="vcs-td vcs-td--sticky-cb">
                  <input
                    type="checkbox"
                    className="vcs-row-cb"
                    data-id={r.id}
                    aria-label={`Select ${contactName(r)}`}
                    checked={selected.has(r.id)}
                    onChange={(e) => onToggle(r.id, e.target.checked)}
                  />
                </td>
                {cols.map((key) => (
                  <Cell key={key} row={r} col={key} labelOf={labelOf} onPreview={onPreview} />
                ))}
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Pager (PHP:324-349)
// ---------------------------------------------------------------------------

export function SegmentPager({
  page,
  pages,
  size,
  onPage,
  onSize,
}: {
  page: number;
  pages: number;
  size: number;
  onPage: (p: number) => void;
  onSize: (s: number) => void;
}) {
  return (
    <nav className="lp-pager vcs-pagination-bar" id="vcsPager" aria-label="Pagination">
      <button
        type="button"
        className="lp-pg"
        id="vcsPagerPrev"
        disabled={page <= 1}
        aria-label="Previous page"
        onClick={() => onPage(page - 1)}
      >
        <CrmIcon name="chevron-left" className="iconSize-14" /> <span>Prev</span>
      </button>
      <div className="vcs-pager-nums" id="vcsPagerNums">
        {pagerItems(page, pages).map((p, i) =>
          p === 'gap' ? (
            <span key={`gap-${i}`} className="lp-pg__gap" aria-hidden="true">
              …
            </span>
          ) : (
            <button
              key={p}
              type="button"
              className="lp-pg lp-pg--n"
              aria-current={p === page ? 'page' : undefined}
              data-page={p}
              aria-label={`Page ${p}`}
              onClick={() => onPage(p)}
            >
              {p}
            </button>
          ),
        )}
      </div>
      <button
        type="button"
        className="lp-pg"
        id="vcsPagerNext"
        disabled={page >= pages}
        aria-label="Next page"
        onClick={() => onPage(page + 1)}
      >
        <span>Next</span> <CrmIcon name="chevron-right" className="iconSize-14" />
      </button>

      <SegDropdown
        toggleClassName="lp-pg lp-pg--per"
        toggleId="vcsRowsPerPageBtn"
        menuClassName="dropdown__menu--up dropdown__menu--right"
        // Drawn on the body and placed against the button, so it flips to the side with room.
        portal
        toggle={
          <>
            <span id="vcsRowsPerPageLabel">{size} per page</span>
            <CrmIcon name="chevron-down" className="iconSize-12" />
          </>
        }
      >
        {PAGE_SIZES.map((n) => (
          <button
            key={n}
            type="button"
            className={cn('dropdown__item', n === size && 'is-selected')}
            data-page-size={n}
            onClick={() => onSize(n)}
          >
            {n} per page
          </button>
        ))}
      </SegDropdown>
    </nav>
  );
}

// ---------------------------------------------------------------------------
// Edit columns (PHP:2284-2406, JS:2674-2889)
// ---------------------------------------------------------------------------

export function EditColumnsModal({
  open,
  cols,
  onApply,
  onClose,
}: {
  open: boolean;
  cols: SegmentColumnKey[];
  onApply: (cols: SegmentColumnKey[]) => void;
  onClose: () => void;
}) {
  const [editing, setEditing] = useState<SegmentColumnKey[]>(cols);
  const [q, setQ] = useState('');
  const [dragKey, setDragKey] = useState<SegmentColumnKey | null>(null);
  const search = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!open) return;
    setEditing(cols);
    setQ('');
    const t = window.setTimeout(() => search.current?.focus(), 80);
    return () => window.clearTimeout(t);
  }, [open, cols]);

  const needle = q.trim().toLowerCase();
  const drop = (target: SegmentColumnKey) => {
    if (dragKey) setEditing((cur) => dropColumn(cur, dragKey, target));
  };

  return (
    <SegModal
      open={open}
      onClose={onClose}
      labelledBy="vcsColsModalTitle"
      id="vcsEditColsModal"
      className="lp-modal--wide"
    >
      <header className="lp-modal__head">
        <h2 id="vcsColsModalTitle">Choose which columns you see</h2>
        <button type="button" className="lp-icon-btn" aria-label="Close" onClick={onClose}>
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>

      <div className="lp-modal__body">
        <div className="lp-cols">
          <div className="lp-cols__left">
            <label className="lp-search lp-search--sm">
              <CrmIcon name="search" className="lp-i" />
              <input
                ref={search}
                type="search"
                id="vcsColsSearch"
                placeholder="Search properties"
                aria-label="Search properties"
                value={q}
                onChange={(e) => setQ(e.target.value)}
              />
            </label>
            <div className="lp-cols__groups" id="vcsColsGroups">
              {COLUMN_GROUPS.map((group) => {
                const items = SEGMENT_COLUMNS.filter(
                  (c) =>
                    c.group === group && (!needle || c.optionLabel.toLowerCase().includes(needle)),
                );
                if (items.length === 0) return null;
                return (
                  <fieldset key={group} className="lp-cols__group">
                    <legend>{group}</legend>
                    {items.map((c) => (
                      <label key={c.key} className="lp-check">
                        <input
                          type="checkbox"
                          data-vcs-col-opt={c.key}
                          checked={editing.includes(c.key)}
                          disabled={c.key === 'name'}
                          onChange={() => setEditing((cur) => toggleColumn(cur, c.key))}
                        />
                        <span>{c.optionLabel}</span>
                      </label>
                    ))}
                  </fieldset>
                );
              })}
            </div>
          </div>

          <div className="lp-cols__right">
            <div className="lp-cols__rh">
              Selected columns (<span id="vcsSelColsCount">{editing.length}</span>)
            </div>
            <ol className="lp-cols__sel" id="vcsSelectedColsList">
              {editing.map((key, idx) => {
                const label = columnOf(key).label;
                const locked = key === 'name';
                return (
                  <li
                    key={key}
                    className={cn(
                      'lp-cols__item',
                      locked && 'is-locked',
                      dragKey === key && 'is-dragging',
                    )}
                    draggable={!locked}
                    data-k={key}
                    onDragStart={() => setDragKey(key)}
                    onDragEnd={() => setDragKey(null)}
                    onDragOver={(e) => e.preventDefault()}
                    onDrop={() => drop(key)}
                  >
                    <span className="lp-cols__drag" aria-hidden>
                      <svg width="10" height="14" viewBox="0 0 10 14" fill="currentColor">
                        <circle cx="2" cy="2" r="1.3" />
                        <circle cx="8" cy="2" r="1.3" />
                        <circle cx="2" cy="7" r="1.3" />
                        <circle cx="8" cy="7" r="1.3" />
                        <circle cx="2" cy="12" r="1.3" />
                        <circle cx="8" cy="12" r="1.3" />
                      </svg>
                    </span>
                    <span className="lp-cols__lbl">{label}</span>
                    {locked ? (
                      <span className="lp-muted lp-cols__lock">Locked</span>
                    ) : (
                      <>
                        <button
                          type="button"
                          className="lp-icon-btn"
                          data-c="up"
                          aria-label={`Move ${label} up`}
                          title="Move up"
                          disabled={idx <= 1}
                          onClick={() => setEditing((cur) => moveColumn(cur, key, 'up'))}
                        >
                          ↑
                        </button>
                        <button
                          type="button"
                          className="lp-icon-btn"
                          data-c="down"
                          aria-label={`Move ${label} down`}
                          title="Move down"
                          disabled={idx === editing.length - 1}
                          onClick={() => setEditing((cur) => moveColumn(cur, key, 'down'))}
                        >
                          ↓
                        </button>
                        <button
                          type="button"
                          className="lp-icon-btn"
                          data-c="rm"
                          aria-label={`Remove ${label}`}
                          title="Remove"
                          onClick={() => setEditing((cur) => toggleColumn(cur, key))}
                        >
                          <CrmIcon name="x" className="iconSize-14" />
                        </button>
                      </>
                    )}
                  </li>
                );
              })}
            </ol>
          </div>
        </div>
      </div>

      <footer className="lp-modal__foot">
        <div className="lp-modal__left">
          <button
            type="button"
            className="lp-btn lp-btn--text lp-btn--sm"
            id="vcsResetDefaultCols"
            onClick={() => setEditing([...DEFAULT_COLUMNS])}
          >
            Reset to default
          </button>
        </div>
        <div className="lp-modal__acts">
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="lp-btn lp-btn--primary"
            id="vcsApplyColsBtn"
            onClick={() => onApply(editing)}
          >
            Apply
          </button>
        </div>
      </footer>
    </SegModal>
  );
}

// ---------------------------------------------------------------------------
// Edit filters (filter pane "Edit", PHP:133). The design has no handler or modal for it, so this
// uses the page's modal shell (as Edit columns) around the FilterEditor of Lists' Create list.
// ---------------------------------------------------------------------------

const EMPTY_FILTER: Filter = { version: 1, groups: [] };

export function EditFilterModal({
  open,
  list,
  canSave,
  onClose,
  onSaved,
  onStale,
}: {
  open: boolean;
  /** An active list: its filter is the starting point. */
  list: CrmList;
  /** List writes are admin and standard only (the API answers 403 to read_only). */
  canSave: boolean;
  onClose: () => void;
  /** PATCH /lists/:id worked: the list as saved (its members are worked out again). */
  onSaved: (list: CrmList) => void;
  /** A 409 (the list changed since it was read): reload it, so the next Save sends its `updatedAt`. */
  onStale?: () => void;
}) {
  const toast = useToast();
  const [filter, setFilter] = useState<Filter>(list.filter ?? EMPTY_FILTER);
  const [busy, setBusy] = useState(false);
  // HUB-733 / HUB-734: what keeps the filter from saving (a segment not chosen, an association
  // without conditions…), as in Create segment (QA #621). QA final BUG-13: as there since round 1
  // BUG-07, worked out live once Save was pressed, so a fixed problem goes; the API's go when the
  // filter changes.
  const [tried, setTried] = useState(false);
  const [apiProblems, setApiProblems] = useState<FilterApiProblems | null>(null);
  // D-35: no visible per-group cap in segments.
  const live = filterProblems(filter, { maxConditions: SEGMENT_MAX_CONDITIONS });
  const problems = shownProblems(tried, live, apiProblems, filter);
  // QA final BUG-12: the saved filter's segment names, for the membership picker until it loads.
  const listNames = useListNames(list.objectType, list.filter);

  // Starts from the saved filter each time it opens; a reload while open keeps the edits.
  useEffect(() => {
    if (open) {
      setFilter(list.filter ?? EMPTY_FILTER);
      setTried(false);
      setApiProblems(null);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- only when it opens
  }, [open]);

  const hasCondition = filter.groups.some((g) => g.conditions.length > 0);
  const save = async () => {
    if (!canSave || busy || !hasCondition) return;
    setTried(true);
    setApiProblems(null);
    if (live.length) return;
    setBusy(true);
    try {
      // `updatedAt` as last read: a 409 means someone changed the list since.
      const saved = await updateList(list.id, { filter, updatedAt: list.updatedAt });
      toast('Filters saved.', 'success');
      onSaved(saved);
    } catch (err) {
      const fromApi = problemsFromError(err);
      if (fromApi) {
        setApiProblems({
          filter,
          list: fromApi.map((p) => `${filterPathLabel(filter, p.path)}: ${p.message}`),
        });
      } else {
        toast(errorText(err), 'danger');
      }
      if (isApiError(err) && err.isConflict) onStale?.();
    } finally {
      setBusy(false);
    }
  };

  return (
    <SegModal
      open={open}
      onClose={onClose}
      labelledBy="vcsFilterModalTitle"
      id="vcsEditFilterModal"
    >
      <header className="lp-modal__head">
        <h2 id="vcsFilterModalTitle">Edit filters</h2>
        <button type="button" className="lp-icon-btn" aria-label="Close" onClick={onClose}>
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>
      <div className="lp-modal__body">
        <FilterEditor
          idPrefix="vcs-edit-filter"
          objectType={list.objectType}
          value={filter}
          onChange={setFilter}
          disabled={!canSave}
          emptyText="Add a condition: the segment keeps the contacts that match."
          listConditions
          excludeListId={list.id}
          linkedConditions
          listNames={listNames}
          variant="segment"
          objectNames={{ singular: 'Contact', plural: 'Contacts' }}
        />
        {problems.length ? (
          <ul className="crm-text-danger crm-fs-8 crm-mb-0 crm-mt-2 crm-ps-3" role="alert">
            {problems.map((p) => (
              <li key={p}>{p}</li>
            ))}
          </ul>
        ) : null}
      </div>
      <footer className="lp-modal__foot">
        <div className="lp-modal__acts">
          <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
            id="vcsSaveFilterBtn"
            disabled={!canSave || busy || !hasCondition}
            onClick={() => void save()}
          >
            Save
          </button>
        </div>
      </footer>
    </SegModal>
  );
}

// ---------------------------------------------------------------------------
// Share (PHP:2411-2432, JS:4352-4372)
// ---------------------------------------------------------------------------

export function ShareModal({ open, onClose }: { open: boolean; onClose: () => void }) {
  const toast = useToast();
  const [copied, setCopied] = useState(false);
  const closeTimer = useRef<number | undefined>(undefined);
  useEffect(() => {
    if (!open) setCopied(false);
    return () => window.clearTimeout(closeTimer.current);
  }, [open]);
  const copy = async () => {
    if (await copyText(window.location.href)) {
      setCopied(true);
      toast('Link copied to clipboard.', 'success');
      closeTimer.current = window.setTimeout(onClose, 900);
    } else {
      toast("Couldn't copy the link. Copy it from the address bar.", 'danger');
    }
  };
  return (
    <SegModal
      open={open}
      onClose={onClose}
      labelledBy="vcsShareModalTitle"
      id="vcsShareModal"
      className="vcs-share-modal"
    >
      <header className="lp-modal__head">
        <h2 id="vcsShareModalTitle">Share this segment</h2>
        <button type="button" className="lp-icon-btn" aria-label="Close" onClick={onClose}>
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>
      <div className="lp-modal__body">
        <p className="crm-text-muted">
          This share link includes the segment and its table column configuration. Anyone who opens
          it will see the same columns you do.
        </p>
        <div className="vcs-modal-btn-row">
          <button
            type="button"
            className="lp-btn lp-btn--primary"
            id="vcsShareCopyBtn"
            onClick={() => void copy()}
          >
            <span id="vcsShareCopyBtnText">{copied ? 'Copied!' : 'Copy link'}</span>
          </button>
        </div>
      </div>
    </SegModal>
  );
}

// ---------------------------------------------------------------------------
// Segment details drawer (PHP:3618-3749, JS:3026-3086)
// ---------------------------------------------------------------------------

type DetailsTab = 'segTabDetails' | 'segTabFilters' | 'segTabUsedIn';

export function SegmentDetailsDrawer({
  open,
  list,
  weekChange = null,
  onClose,
  onPerformance,
}: {
  open: boolean;
  list: CrmList;
  /** As the metrics bar's. */
  weekChange?: number | null;
  onClose: () => void;
  onPerformance: () => void;
}) {
  const toast = useToast();
  const { timeZone } = useUserPrefs();
  const [tab, setTab] = useState<DetailsTab>('segTabDetails');
  const [idsOpen, setIdsOpen] = useState(true);
  const valueLabel = useFilterValueLabel(list.objectType, list.filter !== null);
  const segments = useListNameState(list.objectType, list.filter);
  const listName = (id: string) => segments.names.get(id);
  const lines = filterLineItems(list.filter, valueLabel, listName, segments.loaded);
  const conditions = lines.filter((l) => l.text !== 'or');

  const copy = async (value: string) => {
    if (await copyText(value)) toast(`Copied to clipboard: ${value}`, 'success');
    else toast("Couldn't copy to the clipboard.", 'danger');
  };

  const tabs: { id: DetailsTab; label: string }[] = [
    { id: 'segTabDetails', label: 'Details' },
    { id: 'segTabFilters', label: `Filters (${conditions.length})` },
    // No API says where a list is used, so no count (the design's "(1)" is sample data).
    { id: 'segTabUsedIn', label: 'Used in' },
  ];

  return (
    <SegDrawer open={open} onClose={onClose} label="Segment details" id="vcsSegmentDetailsDrawer">
      <header className="lp-side__head">
        <span className="lp-side__kicker">Segment details</span>
        <div className="lp-side__tools">
          <button
            type="button"
            className="lp-icon-btn"
            id="vcsSegmentDetailsClose"
            aria-label="Close details"
            onClick={onClose}
          >
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </div>
      </header>

      <div className="vcs-drawer-tabs" role="tablist">
        {tabs.map((t) => (
          <button
            key={t.id}
            type="button"
            className={cn('vcs-drawer-tab', tab === t.id && 'is-active')}
            role="tab"
            aria-selected={tab === t.id}
            data-tab-target={t.id}
            onClick={() => setTab(t.id)}
          >
            {t.label}
          </button>
        ))}
      </div>

      <div className="lp-side__body">
        <div
          className={cn('vcs-drawer-tab-content', tab === 'segTabDetails' && 'is-active')}
          id="segTabDetails"
          hidden={tab !== 'segTabDetails'}
        >
          <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-2 crm-mb-3">
            <h3 className="crm-fs-6 crm-fw-700 crm-mb-0">{list.name}</h3>
            <button
              type="button"
              className="lp-icon-btn lp-icon-btn--sm"
              data-copy-val={list.name}
              title="Copy segment name"
              onClick={() => void copy(list.name)}
            >
              <CrmIcon name="file" className="iconSize-14" />
            </button>
          </div>

          <div className="lp-pv__fields">
            <div className="lp-pv__field">
              <span className="lp-pv__label">Description</span>
              <textarea
                className="input crm-w-100 vcs-drawer-textarea"
                rows={3}
                readOnly
                value={list.description ?? ''}
              />
            </div>

            <div className="lp-pv__field">
              <span className="lp-pv__label">Segment type</span>
              <div className="lp-pv__val">
                <strong>{segmentTypeLabel(list)}</strong> &bull;{' '}
                <span className="crm-text-muted">Contacts</span>
              </div>
            </div>

            <div className="lp-pv__field">
              <span className="lp-pv__label">Size</span>
              <div className="lp-pv__val">{list.memberCount} contacts</div>
            </div>

            <div className="lp-pv__field">
              <span className="lp-pv__label">7-day change</span>
              <div className="lp-pv__val">
                {weekChangeText(weekChange)} &bull;{' '}
                <a
                  href="#"
                  className="vcs-link-action"
                  onClick={(e) => {
                    e.preventDefault();
                    onPerformance();
                  }}
                >
                  View segment performance
                </a>
              </div>
            </div>

            <div className="lp-pv__field">
              <span className="lp-pv__label">Created</span>
              <div className="lp-pv__val">
                {longDateText(list.createdAt, timeZone)}
                {byText(list.createdBy)}
              </div>
            </div>

            <div className="lp-pv__field">
              <span className="lp-pv__label">Last updated</span>
              <div className="lp-pv__val">
                {longDateText(list.updatedAt, timeZone)}
                {byText(list.updatedBy)}
              </div>
            </div>

            <section className="lp-pv__sec crm-mt-2">
              <h3>
                <button
                  type="button"
                  className="lp-pv__sh crm-justify-content-start"
                  aria-expanded={idsOpen}
                  onClick={() => setIdsOpen((v) => !v)}
                >
                  <CrmIcon name="chevron-down" className="iconSize-14" />
                  <span>Segment IDs for API integrations</span>
                </button>
              </h3>
              <div className="lp-pv__fields">
                <div className="lp-pv__assoc">
                  <span>
                    <strong>Legacy V1 list ID: {list.hubspotId || NO_VALUE}</strong>
                  </span>
                  {list.hubspotId ? (
                    <button
                      type="button"
                      className="lp-btn lp-btn--outline lp-btn--sm crm-ms-auto"
                      data-copy-val={list.hubspotId}
                      onClick={() => void copy(list.hubspotId!)}
                    >
                      Copy
                    </button>
                  ) : null}
                </div>
                <div className="lp-pv__assoc">
                  <span>
                    <strong>ILS Segment ID: {list.id}</strong>
                  </span>
                  <button
                    type="button"
                    className="lp-btn lp-btn--outline lp-btn--sm crm-ms-auto"
                    data-copy-val={list.id}
                    onClick={() => void copy(list.id)}
                  >
                    Copy
                  </button>
                </div>
              </div>
            </section>
          </div>

          <p className="crm-text-muted crm-fs-8 crm-mt-4">
            Refer to the CRM Knowledge Base to learn more about segment IDs.
          </p>
        </div>

        <div
          className={cn('vcs-drawer-tab-content', tab === 'segTabFilters' && 'is-active')}
          id="segTabFilters"
          hidden={tab !== 'segTabFilters'}
        >
          <div className="vcs-empty-state">
            {conditions.length === 0 ? (
              <p className="crm-text-muted crm-fs-8 crm-mb-0">
                This segment doesn&apos;t have any filters.
              </p>
            ) : (
              lines.map((line, i) => (
                <Fragment key={i}>
                  <p className="crm-fs-8 crm-mb-0">{line.text}</p>
                  {line.error ? (
                    <p className="crm-fs-8 crm-mb-0 crm-text-danger">{line.error}</p>
                  ) : null}
                </Fragment>
              ))
            )}
          </div>
        </div>

        <div
          className={cn('vcs-drawer-tab-content', tab === 'segTabUsedIn' && 'is-active')}
          id="segTabUsedIn"
          hidden={tab !== 'segTabUsedIn'}
        >
          <div className="lp-pv__fields">
            <span className="lp-pv__label">Assets using {list.name}</span>
          </div>
        </div>
      </div>
    </SegDrawer>
  );
}

// ---------------------------------------------------------------------------
// The page
// ---------------------------------------------------------------------------

export function SegmentView({ listId }: { listId: string }) {
  const toast = useToast();
  const me = useCurrentUser();
  const [list, setList] = useState<CrmList | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  // QA #643: no segment has the id in the address (unknown, deleted, or not an id at all).
  const [notFound, setNotFound] = useState(false);
  const [allContacts, setAllContacts] = useState<number | null>(null);

  const [tab, setTab] = useState<SegmentTab>('overview');
  // QA #342: the Segments index opens Compare / View performance with `?tab=performance`.
  useEffect(() => {
    const asked = new URLSearchParams(window.location.search).get('tab');
    if (asked && TABS.some((t) => t.id === asked)) setTab(asked as SegmentTab);
  }, []);
  const [perfView, setPerfView] = useState<PerfSubview>('breakdown');
  const [filtersCollapsed, setFiltersCollapsed] = useState(false);
  const [metricsHidden, setMetricsHidden] = useState(false);
  const [detailsOpen, setDetailsOpen] = useState(false);
  const [shareOpen, setShareOpen] = useState(false);
  const [colsOpen, setColsOpen] = useState(false);
  const [previewId, setPreviewId] = useState<string | null>(null);

  const [cols, setCols] = useState<SegmentColumnKey[]>([...DEFAULT_COLUMNS]);
  const [sort, setSort] = useState<Sort>({ key: 'name', dir: 'asc' });
  const [search, setSearch] = useState('');
  const [query, setQuery] = useState('');
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(DEFAULT_PAGE_SIZE);
  const [rows, setRows] = useState<ContactListItem[]>([]);
  /** Every row loaded, by id: Create tasks names the selected contacts of other pages too. */
  const seenRows = useRef(new Map<string, ContactListItem>());
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  /** SEG1 A1: the last load of the members failed. */
  const [loadFailed, setLoadFailed] = useState(false);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  /** SEG2b C9: Select all's rows are loading; the list and search they were asked for. */
  const [selectAllBusy, setSelectAllBusy] = useState(false);
  const shownQueryRef = useRef('');
  shownQueryRef.current = `${list?.id ?? ''}|${query}`;
  /** Bumped each time the selection empties (Clear, after a bulk action): a late answer drops. */
  const clearEpochRef = useRef(0);
  useEffect(() => {
    if (selected.size === 0) clearEpochRef.current += 1;
  }, [selected]);
  const [reload, setReload] = useState(0);
  const [picklists, setPicklists] = useState<Record<'leadStatus' | 'lifecycleStage', Option[]>>({
    leadStatus: [],
    lifecycleStage: [],
  });

  const router = useRouter();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const access = useMemo(() => segmentAccess(me), [me]);
  // The 7-day change (size history, API #229): the metrics bar, the drawer, the compare card.
  const { timeZone: userZone } = useUserPrefs();
  const weekQuery = useMemo(() => weekChangeQuery(userZone), [userZone]);
  const weekDays = useSizes(list?.id ?? null, weekQuery, Boolean(list), list?.memberCount);
  const listWeekChange = weekChange(weekDays);
  const fieldAccess = useFieldAccess('contact');
  // QA #639: the export's "All properties" headers, without fields hidden from this user.
  const exportAllColumns = useMemo(
    () => fieldAccess.visible(segmentAllExportColumns()),
    [fieldAccess],
  );
  const [filterOpen, setFilterOpen] = useState(false);
  const [addOpen, setAddOpen] = useState(false);
  // S-04: Actions › Add contacts (static segments).
  const [addContactsOpen, setAddContactsOpen] = useState(false);
  const [removing, setRemoving] = useState(false);
  // QA #628: Clone asks the copy's name first.
  const [cloning, setCloning] = useState<CrmList | null>(null);
  const [bulkRequest, setBulkRequest] = useState<{ dialog: BulkRequest; seq: number } | null>(null);
  const [exportSignal, setExportSignal] = useState(0);
  const [bulkExportSignal, setBulkExportSignal] = useState(0);
  const [owners, setOwners] = useState<Owner[]>([]);
  const [customDefs, setCustomDefs] = useState<CustomPropertyDefinition[]>([]);

  // Bulk Assign's owners and Edit's custom fields, as the Contacts page loads them
  // (ContactsListView.tsx:470-505). On failure the pickers are empty.
  useEffect(() => {
    listAllOwners(true).then(
      (all) => setOwners(all.slice().sort((a, b) => a.name.localeCompare(b.name))),
      () => setOwners([]),
    );
    listCustomProperties({ objectType: 'contact' }).then(
      (defs) =>
        setCustomDefs(
          defs.filter((d) => !d.archived).sort((a, b) => a.displayOrder - b.displayOrder),
        ),
      () => setCustomDefs([]),
    );
  }, []);

  // The list itself. A failed first load replaces the page; a failed reload (after an edit in
  // the preview) keeps what is shown and only toasts.
  const hasList = list !== null;
  useEffect(() => {
    let live = true;
    getList(listId)
      .then((l) => {
        if (!live) return;
        setList(l);
        setLoadError(null);
      })
      .catch((err: unknown) => {
        if (!live) return;
        if (hasList) toast(errorText(err), 'danger');
        else if (isMissingList(err)) setNotFound(true);
        else setLoadError(errorText(err));
      });
    return () => {
      live = false;
    };
    // `hasList` is read, not watched: it must not refetch on its own.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [listId, reload]);

  // Every contact I can see, for "% OF DATABASE"; on failure it stays `--`.
  useEffect(() => {
    listContacts({ limit: 1 })
      .then((res) => setAllContacts(typeof res.total === 'number' ? res.total : null))
      .catch(() => setAllContacts(null));
  }, []);

  // Lead status and lifecycle labels (the API sends keys).
  useEffect(() => {
    // Archived values too, so a row that still holds one shows its label, not its key.
    const load = (field: 'leadStatus' | 'lifecycleStage') =>
      listPicklistOptions({ objectType: 'contact', field, includeArchived: true })
        .then((options) => setPicklists((cur) => ({ ...cur, [field]: options })))
        .catch(() => undefined);
    void load('leadStatus');
    void load('lifecycleStage');
  }, []);

  // The filter pane starts collapsed on small screens (PHP:129, JS:2254).
  useEffect(() => {
    if (window.innerWidth <= 991) setFiltersCollapsed(true);
  }, []);

  // SEG1 B2: on a narrow window a click outside the pane closes it, and narrowing the window
  // collapses it (JS:2271-2290).
  useEffect(() => {
    let wasNarrow = window.innerWidth <= 991;
    const onClick = (e: MouseEvent) => {
      const t = e.target as Element | null;
      setFiltersCollapsed((collapsed) =>
        filterPaneClosesOnClick({
          width: window.innerWidth,
          collapsed,
          inPane: Boolean(t?.closest?.('#vcsFilterPane')),
          onToggle: Boolean(t?.closest?.('#vcsToggleFilters')),
        })
          ? true
          : collapsed,
      );
    };
    const onResize = () => {
      const r = filterPaneAfterResize(wasNarrow, window.innerWidth);
      if (r.collapse) setFiltersCollapsed(true);
      wasNarrow = r.narrow;
    };
    document.addEventListener('click', onClick);
    window.addEventListener('resize', onResize);
    return () => {
      document.removeEventListener('click', onClick);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  // SEG1 A7: a search or sort keeps the selection, as the design (JS:2311-2315, 2389-2399).

  // Search waits for typing to pause.
  useEffect(() => {
    const t = window.setTimeout(() => {
      setQuery(search.trim());
      setPage(1);
    }, 300);
    return () => window.clearTimeout(t);
  }, [search]);

  // The members, as full contact rows (field hiding and record access applied by the API).
  const isContactList = list?.objectType === 'contact';
  const loadedId = list?.id ?? null;
  // Read again when the first build ends (see the build poll below).
  const listStatus = list?.status;
  useEffect(() => {
    if (!loadedId || !isContactList) return;
    let live = true;
    setLoading(true);
    const field = columnOf(sort.key).sortField ?? 'name';
    listContacts({
      filter: segmentContactsFilter(loadedId),
      search: query || undefined,
      searchMode: query ? 'contains' : undefined,
      sort: field,
      direction: sort.dir,
      limit: size,
      page,
    })
      .then((res) => {
        if (!live) return;
        const count = typeof res.total === 'number' ? res.total : res.data.length;
        setLoadFailed(false);
        setRows(res.data);
        for (const r of res.data) seenRows.current.set(r.id, r);
        setTotal(count);
        // Fewer members than before (an edit moved one out): stay on a page that exists.
        if (page > pageCount(count, size)) setPage(pageCount(count, size));
      })
      .catch((err: unknown) => {
        if (!live) return;
        setLoadFailed(true);
        setRows([]);
        setTotal(0);
        toast(errorText(err), 'danger');
      })
      .finally(() => live && setLoading(false));
    return () => {
      live = false;
    };
    // `listStatus` is watched, not read: the table loads again when the segment is built.
  }, [loadedId, isContactList, listStatus, query, sort, size, page, reload, toast]);

  // An active segment is built by the API's worker after it is made: until then it is
  // "building", with size 0 and no members. Re-read it (and so its table) every 2 s while it
  // builds, at most 15 times; each answer sets `list`, which schedules the next read. Only
  // here: a company, deal or custom object segment (RecordSegmentView) loads its own members.
  const buildPolls = useRef(0);
  useEffect(() => {
    // A processing segment (S-08) is re-read by the poll below instead.
    if (!isContactList || isProcessing(list)) return;
    const delay = buildPollDelay(list?.status, buildPolls.current);
    if (delay === null) return;
    const t = window.setTimeout(() => {
      buildPolls.current += 1;
      setReload((n) => n + 1);
    }, delay);
    return () => window.clearTimeout(t);
  }, [list, isContactList]);

  // S-08 (SG-2): while the members are worked out again after a filter change, the page shows
  // HubSpot's processing state and re-reads the segment every 3 s until it is done; then the
  // members, size and metrics load again and the "Processing is complete." banner shows.
  const processing = isProcessing(list);
  const [processedNotice, setProcessedNotice] = useState(false);
  useEffect(() => {
    if (!processing) return;
    setProcessedNotice(false);
    let live = true;
    const t = window.setTimeout(() => {
      getList(listId)
        .then((l) => {
          if (!live) return;
          setList(l);
          if (!isProcessing(l)) {
            setProcessedNotice(true);
            setReload((n) => n + 1);
          }
        })
        // A failed read tries again on the next tick (the list object is replaced to rearm it).
        .catch(() => live && setList((cur) => (cur ? { ...cur } : cur)));
    }, PROCESSING_POLL_MS);
    return () => {
      live = false;
      window.clearTimeout(t);
    };
  }, [processing, list, listId]);

  const labelOf = useCallback(
    (field: 'leadStatus' | 'lifecycleStage', value: string) =>
      picklists[field].find((o) => o.value === value)?.label ?? value,
    [picklists],
  );

  const assignOwnerOptions: CustomSelectOption[] = useMemo(
    () => ownerAssignOptions(owners),
    [owners],
  );
  const picklistOptions = (field: 'leadStatus' | 'lifecycleStage'): CustomSelectOption[] =>
    picklists[field].filter((o) => !o.archived).map((o) => ({ value: o.value, label: o.label }));
  const afterBulk = () => {
    setSelected(new Set());
    setReload((n) => n + 1);
  };

  /** QA #637: the title renames the segment (PATCH /lists/:id, refused when changed since). */
  const renameSegment = async (name: string): Promise<boolean> => {
    if (!list) return false;
    try {
      setList(await updateList(list.id, { name, updatedAt: list.updatedAt }));
      toast('Segment renamed', 'success');
      return true;
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  /** Header Actions > Delete: confirm, DELETE /lists/:id, then back to the lists. */
  const deleteSegment = async (target: CrmList) => {
    const ok = await confirm({
      title: 'Delete segment?',
      message: `${target.name} is deleted. Its contacts stay; only the segment goes.`,
      confirmLabel: 'Delete',
      danger: true,
    });
    if (!ok) return;
    try {
      await deleteList(target.id);
      toast('Segment deleted', 'success');
      router.push('/lists');
    } catch (err) {
      toast(deleteListErrorText(err), 'danger');
    }
  };

  /**
   * QA #342 Clone: the same filter (active) or members (static), then opens the copy. QA #628:
   * the Clone dialog asks its name ("Copy of <name>" to start with) and makes it.
   */
  const cloneThis = (source: CrmList) => {
    if (!access.canWriteList) {
      toast("You don't have permission to create segments", 'danger');
      return;
    }
    setCloning(source);
  };

  const afterClone = (
    { list: copy, copied }: { list: CrmList; copied: number },
    source: CrmList,
  ) => {
    toast(
      source.listType === 'static'
        ? `${copy.name} created with ${copied.toLocaleString()} ${copied === 1 ? 'contact' : 'contacts'}`
        : `${copy.name} created`,
      'success',
    );
    setCloning(null);
    router.push(`/lists/${copy.id}`);
  };

  /** QA #342 Actions > Resync segment: an active list's members worked out again now. */
  const resync = async (target: CrmList) => {
    try {
      setList(await rebuildList(target.id));
      toast('Resync started: the segment updates in a moment', 'success');
      setReload((n) => n + 1);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  /** Actions > Convert to static: confirm, then the members stay and the filter goes. */
  const convertToStatic = async (target: CrmList) => {
    const ok = await confirm({
      title: 'Convert to static segment?',
      message: `${target.name} keeps its current ${target.memberCount.toLocaleString('en-US')} ${target.memberCount === 1 ? 'contact' : 'contacts'} but stops updating from its filters. This can't be undone.`,
      confirmLabel: 'Convert to static',
    });
    if (!ok) return;
    try {
      setList(await convertListToStatic(target.id));
      toast('Segment converted to static', 'success');
      setReload((n) => n + 1);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  /** Bulk > Remove from static segment: the selected contacts, 100 a call. */
  const removeSelected = async (target: CrmList) => {
    if (removing) return;
    const ids = [...selected];
    setRemoving(true);
    try {
      const res = await removeMembersInChunks(target.id, ids);
      toast(
        `${res.changed.toLocaleString()} ${res.changed === 1 ? 'contact' : 'contacts'} removed from the segment`,
        'success',
      );
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      // Earlier calls may have removed contacts even when a later one failed.
      setRemoving(false);
      afterBulk();
    }
  };

  /** Activity > Contact memberships > Remove contact: one contact. */
  const removeOne = async (
    target: CrmList,
    member: Pick<ListMember, 'recordId'>,
  ): Promise<boolean> => {
    try {
      const res = await removeMembersInChunks(target.id, [member.recordId]);
      const done = oneRemovedText(res.changed);
      if (!done) return false;
      toast(done, 'success');
      setReload((n) => n + 1);
      return true;
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  const onBulkAct = (act: string) => {
    if (!list || disabledBulkActs(list, access).has(act)) return;
    const route = bulkRoute(act);
    switch (route.to) {
      case 'bulk':
        setBulkRequest((cur) => ({ dialog: route.dialog, seq: (cur?.seq ?? 0) + 1 }));
        return;
      case 'add-to-list':
        setAddOpen(true);
        return;
      case 'remove':
        void removeSelected(list);
        return;
      case 'export':
        setBulkExportSignal((n) => n + 1);
        return;
      default:
        return;
    }
  };

  const goPerformance = (view: PerfSubview = 'breakdown') => {
    setDetailsOpen(false);
    setPerfView(view);
    setTab('performance');
  };

  const onHeaderAction = (action: string) => {
    switch (action) {
      case 'details':
        setPreviewId(null);
        setDetailsOpen(true);
        return;
      case 'share':
        setShareOpen(true);
        return;
      case 'compare':
        goPerformance('comparison');
        toast(SWITCH_TOASTS.comparison, 'info');
        return;
      case 'channels':
        goPerformance('available-channels');
        toast(SWITCH_TOASTS['available-channels'], 'info');
        return;
      case 'delete':
        if (list && access.canWriteList && canDeleteSegment(list)) void deleteSegment(list);
        return;
      case 'clone':
        if (list) void cloneThis(list);
        return;
      case 'resync':
        if (list && !disabledHeaderActions(access, list).has('resync')) void resync(list);
        return;
      case 'convert-static':
        if (list && !disabledHeaderActions(access, list).has('convert-static')) {
          void convertToStatic(list);
        }
        return;
      case 'export':
        if (access.canExport) setExportSignal((n) => n + 1);
        return;
      case 'add-contacts':
        if (
          list?.listType === 'static' &&
          !disabledHeaderActions(access, list).has('add-contacts')
        ) {
          setAddContactsOpen(true);
        }
        return;
      default:
        return;
    }
  };

  if (notFound || loadError) {
    return (
      <div className="lp vcs-page" id="viewContactSegment" style={{ fontFamily: 'inherit' }}>
        <header className="vcs-header-wrap">
          <Link href="/lists" className="vcs-breadcrumb">
            <CrmIcon name="chevron-left" className="iconSize-14" />
            <span>Back to segments</span>
          </Link>
          <div className="vcs-header">
            {/* QA #643: as the other record pages' not-found (Workflows, Tasks). */}
            {notFound ? (
              <Alert tone="warning">This segment doesn&apos;t exist or was deleted.</Alert>
            ) : (
              <p className="vcs-subtitle">{loadError}</p>
            )}
          </div>
        </header>
      </div>
    );
  }

  if (!list) {
    return (
      <div className="lp vcs-page" id="viewContactSegment" style={{ fontFamily: 'inherit' }} />
    );
  }

  // QA #342: company, deal and custom object segments open too (header and members).
  if (!isContactList) return <RecordSegmentView list={list} />;

  const pages = pageCount(total, size);
  const toggleOne = (id: string, on: boolean) =>
    setSelected((cur) => {
      const next = new Set(cur);
      if (on) next.add(id);
      else next.delete(id);
      return next;
    });

  /**
   * SEG2b C9 (JS:2377-2385): check selects every row matching the search, on all pages; uncheck
   * clears the whole selection. An answer for another list or search is dropped; a failed load
   * toasts and keeps the selection.
   */
  const toggleAll = (on: boolean) => {
    if (!on) {
      setSelected(new Set());
      return;
    }
    if (!loadedId || selectAllBusy) return;
    const asked = { key: `${loadedId}|${query}`, epoch: clearEpochRef.current };
    setSelectAllBusy(true);
    allMatchingRows<ContactListItem>(loadedId, query)
      .then((found) => {
        const now = { key: shownQueryRef.current, epoch: clearEpochRef.current };
        if (!selectAllApplies(asked, now)) return;
        // The bulk panels build their records from the rows seen (`selectedRows`).
        for (const r of found) seenRows.current.set(r.id, r);
        setSelected((cur) => new Set([...cur, ...found.map((r) => r.id)]));
      })
      .catch((err: unknown) => toast(errorText(err), 'danger'))
      .finally(() => setSelectAllBusy(false));
  };

  return (
    <div className="lp vcs-page" id="viewContactSegment" style={{ fontFamily: 'inherit' }}>
      <header className="vcs-header-wrap">
        <SegmentHeader
          list={list}
          onAction={onHeaderAction}
          disabled={disabledHeaderActions(access, list)}
          onRename={access.canWriteList && list.canEdit !== false ? renameSegment : undefined}
        />
        <SegmentTabs tab={tab} onTab={setTab} />
      </header>

      <div className="vcs-layout">
        <FilterPane
          list={list}
          collapsed={filtersCollapsed}
          hidden={tab !== 'overview'}
          onCollapse={() => setFiltersCollapsed(true)}
          // A static list has no filter (the API refuses one): its filters are read-only, no Edit.
          onEdit={() => setFilterOpen(true)}
          readOnly={list.listType !== 'active'}
        />

        <div className="vcs-main">
          <section
            className={cn('vcs-tab-pane', tab === 'overview' && 'is-active')}
            data-vcs-tab-pane="overview"
          >
            {processing ? (
              <div className="alert alert--info vcs-processing-alert" role="status">
                <span>
                  <strong>{PROCESSING_NOTICE.title}</strong> {PROCESSING_NOTICE.text}
                </span>
              </div>
            ) : processedNotice ? (
              <div className="alert alert--success vcs-processing-alert" role="status">
                <span>
                  <strong>{PROCESSED_NOTICE.title}</strong> {PROCESSED_NOTICE.text}
                </span>
                <button
                  type="button"
                  className="vcs-processing-alert__close"
                  aria-label="Dismiss"
                  onClick={() => setProcessedNotice(false)}
                >
                  <CrmIcon name="x" className="iconSize-14" />
                </button>
              </div>
            ) : null}
            <MetricsBar
              list={list}
              allContacts={allContacts}
              hidden={metricsHidden}
              weekChange={listWeekChange}
              // SEG1 B3: the design's tab switch keeps the Performance sub-view (JS:2238-2244).
              onPerformance={() => goPerformance(perfView)}
              onDetails={() => setDetailsOpen(true)}
            />
            <SegmentToolbar
              search={search}
              onSearch={setSearch}
              onEditColumns={() => setColsOpen(true)}
              onExport={() => {
                if (access.canExport) setExportSignal((n) => n + 1);
              }}
              exportDisabled={!access.canExport || processing}
              filtersOpen={!filtersCollapsed}
              onToggleFilters={() => setFiltersCollapsed((v) => !v)}
              metricsOpen={!metricsHidden}
              onToggleMetrics={() => setMetricsHidden((v) => !v)}
            />
            <BulkBar
              count={selected.size}
              onAct={onBulkAct}
              onClear={() => setSelected(new Set())}
              disabled={disabledBulkActs(list, access)}
            />
            <div className="vcs-table-card" data-dropdown-inline="">
              <SegmentTable
                rows={rows}
                cols={cols}
                sort={sort}
                onSort={(key) => {
                  setSort((cur) => nextSort(cur, key));
                  setPage(1);
                }}
                selected={selected}
                onToggle={toggleOne}
                onToggleAll={toggleAll}
                selectAllBusy={selectAllBusy}
                onPreview={(id) => {
                  setDetailsOpen(false);
                  setPreviewId(id);
                }}
                searching={query !== ''}
                loading={loading}
                failed={loadFailed}
                labelOf={labelOf}
                building={list.status === 'building'}
                processing={processing}
              />
              <SegmentPager
                page={page}
                pages={pages}
                size={size}
                onPage={(p) => {
                  const next = Math.min(Math.max(1, p), pages);
                  if (next === page) return;
                  setPage(next);
                  // SEG1 B1: back to the table's top, and the design's toast (JS:2569-2606).
                  document
                    .querySelector('[data-vcs-tab-pane="overview"] .vcs-table-wrap')
                    ?.scrollTo?.({ top: 0 });
                  toast(pageToast(next), 'info');
                }}
                onSize={(s) => {
                  setSize(s);
                  setPage(1);
                  toast(pageSizeToast(s), 'info');
                }}
              />
            </div>
          </section>

          {tab === 'performance' ? (
            <section className="vcs-tab-pane is-active" data-vcs-tab-pane="performance">
              <PerformancePane
                list={list}
                subview={perfView}
                onSubview={setPerfView}
                weekChange={listWeekChange}
              />
            </section>
          ) : null}

          {tab === 'activity' ? (
            <section className="vcs-tab-pane is-active" data-vcs-tab-pane="activity">
              <ActivityPane
                list={list}
                canViewAudit={Boolean(me.permissionSet.rules.app.manage_users)}
                onRemoveMember={
                  list.listType === 'static' && access.canWriteList
                    ? (m) => removeOne(list, m)
                    : undefined
                }
                onExport={access.canExport ? () => setExportSignal((n) => n + 1) : undefined}
              />
            </section>
          ) : null}

          {tab === 'settings' ? (
            <section className="vcs-tab-pane is-active" data-vcs-tab-pane="settings">
              {/* QA #624: saving settings moves the segment's updatedAt (the rename's 409 check). */}
              <SettingsPane
                list={list}
                onSaved={(updatedAt) => setList((l) => (l ? { ...l, updatedAt } : l))}
              />
            </section>
          ) : null}
        </div>
      </div>

      <EditColumnsModal
        open={colsOpen}
        cols={cols}
        onClose={() => setColsOpen(false)}
        onApply={(next) => {
          setCols(next);
          setColsOpen(false);
          toast('Columns updated successfully.', 'success');
        }}
      />
      <ShareModal open={shareOpen} onClose={() => setShareOpen(false)} />
      <CloneSegmentModal source={cloning} onClose={() => setCloning(null)} onCloned={afterClone} />
      {list.listType === 'active' ? (
        <EditFilterModal
          open={filterOpen}
          list={list}
          canSave={access.canWriteList}
          onClose={() => setFilterOpen(false)}
          onStale={() => setReload((n) => n + 1)}
          onSaved={(saved) => {
            setList(saved);
            setFilterOpen(false);
            // The API works the members out again in the background: reload list and table.
            setReload((n) => n + 1);
          }}
        />
      ) : null}
      {/* The Contacts page's bulk flows (Assign, Edit, Delete, Enroll in sequence, Create
          tasks), opened by the design's own buttons above; on the selected ids only. */}
      <BulkActionsBar
        design
        headless
        request={bulkRequest}
        objectType="contact"
        noun={selected.size === 1 ? 'contact' : 'contacts'}
        count={selected.size}
        selection={{ ids: [...selected] }}
        ownerOptions={assignOwnerOptions}
        fields={[
          { key: 'jobTitle', label: 'Job title' },
          { key: 'phone', label: 'Phone number' },
          {
            key: 'lifecycleStage',
            label: 'Lifecycle stage',
            options: picklistOptions('lifecycleStage'),
          },
          { key: 'leadStatus', label: 'Lead status', options: picklistOptions('leadStatus') },
        ].filter((f) => !fieldAccess.locked(f.key))}
        customDefs={customDefs}
        canDelete={access.canDeleteContacts}
        canShare={access.canEditContacts}
        onDone={afterBulk}
        panels={{
          singular: 'contact',
          plural: 'contacts',
          meId: me.user.id,
          teams: [],
          linkTypes: [],
          coverageProps: [],
          // The selection outlives a page change, so read every selected row seen, not this page.
          loadRecords: async (): Promise<BxRecord[]> =>
            selectedRows(selected, seenRows.current).map((r) => ({
              id: r.id,
              name: contactName(r),
              href: `/contacts/${r.id}`,
              eligible: Boolean(r.email),
              filled: {},
            })),
        }}
      />
      <AddContactsModal
        open={addContactsOpen}
        listId={list.id}
        onClose={() => setAddContactsOpen(false)}
        // The new members, size and activity load again.
        onAdded={() => setReload((n) => n + 1)}
      />
      <AddToListModal
        open={addOpen}
        objectKey="contact"
        noun={`${selected.size.toLocaleString()} ${selected.size === 1 ? 'contact' : 'contacts'}`}
        loadIds={async () => [...selected]}
        onClose={() => setAddOpen(false)}
        onDone={afterBulk}
      />
      {/* Export segment (header, toolbar): the contacts the table matches. QA #638: with its
          search, and the table's count of them (not the segment's size). */}
      <ExportButton
        objectType="contact"
        columns={segmentExportColumns(cols)}
        allColumns={exportAllColumns}
        search={query}
        filters={segmentExportFilters(list.id, query)}
        total={loadFailed ? null : total}
        dialog
        designText
        viewName={list.name}
        openSignal={exportSignal}
        hideTrigger
      />
      {/* Bulk > Export: the selected contacts, ticked under any search (SEG1 A7). */}
      <ExportButton
        objectType="contact"
        columns={segmentExportColumns(cols)}
        allColumns={exportAllColumns}
        search={query}
        filters={segmentExportFilters(list.id, query)}
        selectedIds={[...selected]}
        selectionIgnoresSearch
        total={loadFailed ? null : total}
        dialog
        designText
        viewName={list.name}
        openSignal={bulkExportSignal}
        hideTrigger
      />
      {confirmDialog}
      <SegmentDetailsDrawer
        open={detailsOpen}
        list={list}
        weekChange={listWeekChange}
        onClose={() => setDetailsOpen(false)}
        onPerformance={() => goPerformance()}
      />
      <ContactPreviewDrawer
        contactId={previewId}
        onClose={() => setPreviewId(null)}
        onChanged={() => setReload((n) => n + 1)}
      />
    </div>
  );
}
