'use client';

/**
 * Data integration › Import details (DI-2b), the 6 Nov design's `import-details.php` and
 * `assets/js/import-details.js`, on one import run. Three views, as the design: rows with errors
 * (`?view=rows`), an import with failed rows, and the rest with tabs. Classes as the design, so
 * its CSS applies as written (`public/crm/assets/css/import-details.css`, under `.idt-page`).
 * Decisions: `batches/DI2b-import-details.md`.
 */
import Link from 'next/link';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { deletesAny } from '@/features/auth/record-access';
import { useToast } from '@/components/crm/ToastProvider';
import { listCustomProperties } from '@/features/custom-properties/api.client';
import { downloadFileAt, downloadImportFile } from '@/features/imports/download';
import { fetchImportRecords } from '../importRecords';
import { listPicklistOptions } from '@/features/picklists/api.client';
import { getImportFormatting, getImportRun, listImportErrors } from '@/features/imports/api.client';
import { isBuiltInImportType, objectLabels, type ObjectLabels } from '@/features/imports/fields';
import type { ImportErrorRow, ImportObjectType, ImportRun } from '@/features/imports/types';
import { useObjectLabels } from '@/features/imports/ui/useObjectLabels';
import { listObjectDefinitions } from '@/features/objects/api.client';
import type { ObjectDefinition } from '@/features/objects/types';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  COMPANIES_TAB,
  TROUBLESHOOT_SECTIONS,
  activeTab,
  companiesTabShown,
  companyColumns,
  companyFields,
  detailsTabs,
  extraColumns,
  extraFields,
  extraTabCount,
  extraTabId,
  extraTabObjects,
  knownTotal,
  importInProgress,
  pollImportRun,
  detailsView,
  errorCellId,
  errorColumns,
  errorGroups,
  errorObjectText,
  labelsByObject,
  errorRowView,
  errorsPaneState,
  formattingCards,
  headerDateText,
  importDetailsHref,
  importSegmentTarget,
  objectMeta,
  originalFileAction,
  errorsFileHref,
  IMPORT_ERRORS_NOT_YOURS_TEXT,
  popoverPlace,
  numberedPages,
  recordColumns,
  recordFields,
  recordRow,
  recordsPager,
  recordsQuery,
  type RecordRowView,
  remapCards,
  viewRecordsItems,
  remapCount,
  rowsWithErrorsHref,
  summaryMetrics,
  type CustomLabel,
  type OptionLabels,
  type PopoverPlace,
} from '../importDetails';
import { importSegmentable, ImportSegmentDialog, openImportSegment } from './ImportSegment';
import { segmentNoun } from '../importSegment';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { GeneralOsTabs } from '@/features/settings/ui/GeneralOsTabs';
import { useFieldAccess } from '@/features/permission-sets/field-access';
import { editProperties, keepOnPage, pageCheck, toggleId, togglePage } from '../importBulk';
import {
  cellDesignEditor,
  cellEditToast,
  inlinePopoverPos,
  textCommit,
  type DesignEdit,
} from '../importCellEdit';
import { ImportBulkControls, InlineSelectPopover, InlineTextInput } from './ImportBulk';
import { ownerOptions, useCellEditContext, useRecordsEditData } from './useRecordsEdit';

const BACK_HREF = '/data-integration';
const NONE = '--';
const capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);

export interface DetailsData {
  id: string;
  run: ImportRun | null;
  loadError: string | null;
  errors: ImportErrorRow[];
  errorsLoaded: boolean;
  errorsError: string | null;
  custom: CustomLabel[];
  /** Dropdown option labels for Remappings; missing ones show the stored value. */
  optionLabels?: OptionLabels;
  labels: ObjectLabels;
  /** B7: the run's custom objects' labels; left out or not loaded, they read "Record". */
  extraLabels?: Record<string, ObjectLabels>;
}

/** Loads the run (with its uploader) and its errors, then draws the page. */
export function ImportDetailsView({
  importId,
  view = null,
  tab = null,
}: {
  importId: string;
  view?: string | null;
  tab?: string | null;
}) {
  const { timeZone } = useUserPrefs();
  const [run, setRun] = useState<ImportRun | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [errors, setErrors] = useState<ImportErrorRow[]>([]);
  const [errorsLoaded, setErrorsLoaded] = useState(false);
  const [errorsError, setErrorsError] = useState<string | null>(null);
  useEffect(() => {
    let live = true;
    getImportRun(importId).then(
      (r) => {
        if (live) setRun(r);
      },
      (err: unknown) => {
        if (live) setLoadError(errorText(err));
      },
    );
    listImportErrors(importId)
      .then(
        (res) => {
          if (live) setErrors(res.data);
        },
        (err: unknown) => {
          if (live) setErrorsError(errorText(err));
        },
      )
      .finally(() => {
        if (live) setErrorsLoaded(true);
      });
    return () => {
      live = false;
    };
  }, [importId]);
  // A queued or running import is loaded again every few seconds until it is done, so its
  // counts keep up with the records it brings in; its errors load once more when it finishes.
  const runInProgress = run ? importInProgress(run.status) : false;
  const [finishedWhileOpen, setFinishedWhileOpen] = useState(0);
  useEffect(() => {
    if (!runInProgress) return;
    return pollImportRun({
      load: () => getImportRun(importId),
      onRun: (r) => {
        setRun(r);
        if (!importInProgress(r.status)) setFinishedWhileOpen((n) => n + 1);
      },
    });
  }, [importId, runInProgress]);
  useEffect(() => {
    if (!finishedWhileOpen) return;
    let live = true;
    listImportErrors(importId).then(
      (res) => {
        if (!live) return;
        setErrors(res.data);
        setErrorsError(null);
      },
      (err: unknown) => {
        if (live) setErrorsError(errorText(err));
      },
    );
    return () => {
      live = false;
    };
  }, [importId, finishedWhileOpen]);

  const objectType = run?.objectType ?? null;
  const { custom, optionLabels } = useFieldLabels(objectType);
  const labels = useObjectLabels(objectType);
  // B7: the custom objects the import also filled, named by their labels. Loaded only when it
  // filled one; if they can't be loaded the generic name stays.
  const objectTypes = run?.objectTypes;
  const customKeys = (objectTypes ?? []).filter((k) => !isBuiltInImportType(k)).join(',');
  const [definitions, setDefinitions] = useState<ObjectDefinition[]>([]);
  useEffect(() => {
    if (!customKeys) return;
    let alive = true;
    listObjectDefinitions().then(
      (d) => {
        if (alive) setDefinitions(d);
      },
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [customKeys]);
  const extraLabels = useMemo(
    () => labelsByObject(objectTypes ?? [], definitions),
    [objectTypes, definitions],
  );
  const data: DetailsData = {
    id: importId,
    run,
    loadError,
    errors,
    errorsLoaded,
    errorsError,
    custom,
    optionLabels,
    labels,
    extraLabels,
  };
  return <ImportDetailsBody data={data} viewParam={view} tabParam={tab} timeZone={timeZone} />;
}

type Menu = 'records' | 'actions' | 'size';

/** The page from loaded data (tested without a browser). */
export function ImportDetailsBody({
  data,
  viewParam,
  tabParam,
  timeZone,
}: {
  data: DetailsData;
  viewParam: string | null;
  tabParam: string | null;
  timeZone?: string;
}) {
  const toast = useToast();
  const soon = useCallback((label: string) => toast(`${label} is coming soon`), [toast]);
  const [menu, setMenu] = useState<Menu | null>(null);
  // `opened` counts opens, so the same section clicked again scrolls again (`import-details.js:1305`).
  const [ts, setTs] = useState<{ open: boolean; section: string | null; opened: number }>({
    open: false,
    section: null,
    opened: 0,
  });
  const [tsPos, setTsPos] = useState<{ top: number; left: number } | null>(null);
  const [segmentOpen, setSegmentOpen] = useState(false);

  // Dropdowns close on a click outside them and on Escape (`import-details.js:892-911`).
  useEffect(() => {
    if (!menu) return;
    const onDown = (e: MouseEvent) => {
      if (!(e.target as Element).closest?.('[data-dropdown]')) setMenu(null);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setMenu(null);
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [menu]);

  const toggle = (m: Menu) => setMenu((cur) => (cur === m ? null : m));
  const troubleshoot = (section: string | null) =>
    setTs((cur) => ({ open: true, section, opened: cur.opened + 1 }));
  const { run } = data;

  const body = !run ? (
    <>
      <Link className="record-header__back" href={BACK_HREF}>
        <CrmIcon name="chevron-left" className="iconSize-14" />
        <span>Back to Import History</span>
      </Link>
      {data.loadError ? <Alert tone="danger">{data.loadError}</Alert> : null}
    </>
  ) : (
    (() => {
      const view = detailsView(run, viewParam);
      if (view === 'rows') return <RowsView data={data} run={run} onTroubleshoot={troubleshoot} />;
      return (
        <>
          <Header
            run={run}
            labels={data.labels}
            timeZone={timeZone}
            full={view === 'full'}
            onSoon={soon}
            onTroubleshoot={() => troubleshoot(null)}
          />
          {view === 'errors' ? (
            <ErrorsView
              data={data}
              run={run}
              menu={menu}
              onToggle={toggle}
              onMessage={toast}
              onTroubleshoot={troubleshoot}
            />
          ) : (
            <FullView
              data={data}
              run={run}
              tabParam={tabParam}
              menu={menu}
              onToggle={toggle}
              onMessage={toast}
              onTroubleshoot={troubleshoot}
              onAddSegment={() => {
                setMenu(null);
                // IDB4c: by the import filter (the bulk job's objects); custom objects not yet.
                if (importSegmentable(run.objectType)) setSegmentOpen(true);
                else soon('Add imported records to segment');
              }}
              onPageSize={(n) => toast(`Showing ${n} records per page`)}
              timeZone={timeZone}
            />
          )}
        </>
      );
    })()
  );

  return (
    <div className="di-page idt-page">
      <div className="crm-container-fluid crm-p-4 crm-p-md-5">{body}</div>
      <TroubleshootPanel
        open={ts.open}
        section={ts.section}
        opened={ts.opened}
        pos={tsPos}
        onPos={setTsPos}
        onClose={() => setTs((cur) => ({ ...cur, open: false, section: null }))}
      />
      {run ? (
        <ImportSegmentDialog
          open={segmentOpen}
          count={run.createdCount + run.updatedCount}
          noun={segmentNoun(run.objectType, data.labels.plural)}
          objectType={run.objectType}
          source={{ kind: 'import', importId: run.id }}
          naming={{ importName: run.name ?? null, fileName: run.fileName }}
          onClose={() => setSegmentOpen(false)}
        />
      ) : null}
    </div>
  );
}

const LEARN_MORE = [
  { label: 'Import records and activities', soon: 'Import records and activities documentation' },
  { label: 'Setup your import files', soon: 'Setup your import files documentation' },
  { label: 'Troubleshoot import errors', soon: 'Troubleshoot import errors documentation' },
] as const;

/** The record header (`import-details.php:563-596`, `:699-735`). */
function Header({
  run,
  labels,
  timeZone,
  full,
  onSoon,
  onTroubleshoot,
}: {
  run: ImportRun;
  labels: ObjectLabels;
  timeZone?: string;
  full: boolean;
  onSoon: (label: string) => void;
  onTroubleshoot: () => void;
}) {
  const uploader = run.uploadedBy ?? null;
  return (
    <header className="record-header">
      <Link className="record-header__back" href={BACK_HREF}>
        <CrmIcon name="chevron-left" className="iconSize-14" />
        <span>Back to Import History</span>
      </Link>
      <div className="record-header__body">
        <div className="record-header__main">
          {/* B2: the import's name when it was given one. */}
          <h1 className="record-header__title">{run.name || run.fileName}</h1>
          <div className="record-header__meta">
            {full ? (
              <span className="record-header__meta-item record-header__meta-item--subtle">
                {objectMeta(labels, run.objectTypes)}
              </span>
            ) : null}
            <span className="record-header__meta-item record-header__meta-item--strong">
              {headerDateText(run.createdAt, timeZone)}
            </span>
            <span className="record-header__meta-item">
              {/* IDB1: from the run; null once the uploader left, missing on an older API. */}
              {uploader ? (
                <>
                  {uploader.name}{' '}
                  {uploader.email ? <span className="crm-text-muted">{uploader.email}</span> : null}
                </>
              ) : (
                NONE
              )}
            </span>
          </div>
        </div>
        <div className="record-header__aside">
          <span className="record-header__aside-label">Learn more about import</span>
          {LEARN_MORE.map((l, i) => (
            <a
              key={l.label}
              href="#"
              className="record-header__link"
              onClick={(e) => {
                e.preventDefault();
                // The errors view's third link opens the troubleshoot panel (`:590`).
                if (!full && i === 2) onTroubleshoot();
                else onSoon(l.soon);
              }}
            >
              <span>{l.label}</span>
              <CrmIcon name="external" className="iconSize-14" />
            </a>
          ))}
        </div>
      </div>
    </header>
  );
}

function Metrics({ items, cols }: { items: { label: string; value: string }[]; cols: 2 | 4 }) {
  return (
    <div className={`metric-items metric-items--cols-${cols}`}>
      {items.map((m) => (
        <div key={m.label} className="metric-item">
          <span className="metric-item__label">{m.label}</span>
          <span className={cn('metric-item__value', cols === 2 && 'metric-item__value--teal')}>
            {m.value}
          </span>
        </div>
      ))}
    </div>
  );
}

/** "Download original file" (IDB2), drawn by both Actions menus. */
export function OriginalFileItem({
  id,
  fileAvailable,
  canManage,
  onDone,
  onMessage,
}: {
  id: string;
  fileAvailable: boolean | undefined;
  /** BL1: false when the caller isn't the uploader or an admin (missing: allowed). */
  canManage?: boolean;
  /** Closes the menu. */
  onDone: () => void;
  onMessage: (text: string) => void;
}) {
  const action = originalFileAction(id, fileAvailable, canManage);
  if (action.kind === 'locked') {
    return (
      <button
        type="button"
        className="dropdown__item"
        disabled
        aria-disabled="true"
        title={action.message}
      >
        Download original file
      </button>
    );
  }
  if (action.kind === 'link') {
    return (
      <a
        href={action.href}
        className="dropdown__item"
        onClick={(e) => {
          // Fetched first, so a file gone since the page loaded shows the API's message.
          e.preventDefault();
          onDone();
          void downloadImportFile(id, onMessage);
        }}
      >
        Download original file
      </a>
    );
  }
  return (
    <button
      type="button"
      className="dropdown__item"
      onClick={() => {
        onDone();
        onMessage(
          action.kind === 'gone' ? action.message : 'Download original file is coming soon',
        );
      }}
    >
      Download original file
    </button>
  );
}

/**
 * BL1: an error-file link, or (null `href`: not the caller's import) the same text, muted and
 * disabled, with the reason as its tooltip.
 */
export function ErrorsFileLink({ href, children }: { href: string | null; children: string }) {
  const toast = useToast();
  if (!href) {
    return (
      <span
        className="crm-text-muted crm-fw-semibold crm-fs-7 crm-d-inline-flex crm-align-items-center crm-gap-1"
        aria-disabled="true"
        title={IMPORT_ERRORS_NOT_YOURS_TEXT}
      >
        <DownloadIcon />
        <span>{children}</span>
      </span>
    );
  }
  return (
    <a
      href={href}
      className="link crm-text-brand crm-fw-semibold crm-fs-7 crm-d-inline-flex crm-align-items-center crm-gap-1"
      onClick={(e) => {
        // #712: fetched, then saved, so a failure says why instead of opening an error page.
        e.preventDefault();
        void downloadFileAt(href, (m) => toast(m, 'danger'));
      }}
    >
      <DownloadIcon />
      <span>{children}</span>
    </a>
  );
}

/**
 * "View contacts segment" in the full view's Actions. IDB4c: a contact import asks the API for its
 * live list (made again when the saved one was deleted or none was made) and opens it; the API's
 * reason when it can't; other objects their message (`importSegmentTarget`).
 */
export function SegmentItem({
  run,
  onDone,
  onMessage,
}: {
  run: Pick<ImportRun, 'id' | 'objectType' | 'listId'>;
  /** Closes the menu. */
  onDone: () => void;
  onMessage: (text: string) => void;
}) {
  const target = importSegmentTarget(run);
  return (
    <button
      type="button"
      className="dropdown__item"
      onClick={() => {
        onDone();
        if (target.kind === 'message') {
          onMessage(target.message);
          return;
        }
        void openImportSegment(run.id).then((message) => {
          if (message) onMessage(message);
        });
      }}
    >
      View contacts segment
    </button>
  );
}

function MenuButton({
  label,
  open,
  onClick,
}: {
  label: string;
  open: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      className={cn('btn-crm btn-crm--ghost btn-crm--sm crm-fw-semibold', open && 'is-open')}
      aria-expanded={open}
      onClick={onClick}
    >
      <span>{label}</span>
      <CrmIcon name="chevron-down" className="iconSize-14" />
    </button>
  );
}

function DownloadIcon() {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="7 10 12 15 17 10" />
      <line x1="12" y1="15" x2="12" y2="3" />
    </svg>
  );
}

function ArrowRight({ size }: { size: number }) {
  return (
    <svg
      className={`iconSize-${size}`}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M5 12h14" />
      <path d="m12 5 7 7-7 7" />
    </svg>
  );
}

/** The errors table: one row per reason (`import-details.php:652-691`). */
function ErrorsTable({
  run,
  errors,
  labels,
  extraLabels,
  onTroubleshoot,
}: {
  run: ImportRun;
  errors: ImportErrorRow[];
  labels: ObjectLabels;
  extraLabels?: Record<string, ObjectLabels>;
  onTroubleshoot: (section: string | null) => void;
}) {
  const heads = ['Import column from file', 'Object type', 'CRM property', 'Error impact'];
  return (
    <div className="lp-tablewrap di-tablewrap">
      <table className="lp-table di-table">
        <thead>
          <tr className="lp-tr lp-tr--head">
            {heads.map((h) => (
              <th key={h} className="lp-th" scope="col">
                <div className="lp-th__in">
                  <span className="lp-th__lbl">{h}</span>
                </div>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {errorGroups(errors, run.failedCount).map((g) => (
            <tr key={g.key} className="lp-tr">
              <td className={cn('lp-td crm-fw-medium', g.column === NONE && 'crm-text-muted')}>
                {g.column}
              </td>
              <td className="lp-td crm-text-muted">{errorObjectText(g, labels, extraLabels)}</td>
              <td className={cn('lp-td', g.property === NONE && 'crm-text-muted')}>{g.property}</td>
              <td className="lp-td">
                <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-4">
                  <div>
                    <a
                      href="#"
                      className="di-troubleshoot-trigger crm-fw-semibold"
                      title={`Click to troubleshoot ${g.reason}`}
                      onClick={(e) => {
                        e.preventDefault();
                        onTroubleshoot(g.section);
                      }}
                    >
                      {g.reason}
                    </a>
                    {/* QA #419: which file rows failed, not only how many. */}
                    <span className="crm-d-block crm-text-muted crm-fs-8 crm-mt-1">
                      {g.rowNumbers}
                    </span>
                  </div>
                  <span className="crm-text-muted crm-fs-7">{g.impact}</span>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/** The import with failed rows (`import-details.php:559-693`). */
function ErrorsView({
  data,
  run,
  menu,
  onToggle,
  onMessage,
  onTroubleshoot,
}: {
  data: DetailsData;
  run: ImportRun;
  menu: Menu | null;
  onToggle: (m: Menu) => void;
  /** A plain message (the original file's "no longer available"). */
  onMessage: (text: string) => void;
  onTroubleshoot: (section: string | null) => void;
}) {
  const csv = errorsFileHref(run);
  return (
    <>
      <section className="card crm-p-4 crm-mb-4" aria-label="Import summary statistics">
        <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-flex-wrap crm-gap-3 crm-mb-4">
          <h2 className="card__title crm-fs-5 crm-fw-bold crm-m-0">Summary</h2>
          <div className="dropdown" data-dropdown="">
            <MenuButton
              label="Actions"
              open={menu === 'actions'}
              onClick={() => onToggle('actions')}
            />
            {menu === 'actions' ? (
              <div className="dropdown__menu dropdown__menu--right">
                <OriginalFileItem
                  id={run.id}
                  fileAvailable={run.fileAvailable}
                  canManage={run.canManage}
                  onDone={() => onToggle('actions')}
                  onMessage={onMessage}
                />
                {csv ? (
                  <a href={csv} className="dropdown__item" onClick={() => onToggle('actions')}>
                    Download error file
                  </a>
                ) : (
                  <button
                    type="button"
                    className="dropdown__item"
                    disabled
                    aria-disabled="true"
                    title={IMPORT_ERRORS_NOT_YOURS_TEXT}
                  >
                    Download error file
                  </button>
                )}
              </div>
            ) : null}
          </div>
        </div>
        <Metrics items={summaryMetrics(run, 'errors')} cols={4} />
      </section>

      <section className="card crm-p-4" aria-labelledby="errors-section-heading">
        <div className="os-tabbar crm-mb-4">
          <nav className="os-tabs" aria-label="Error tabs">
            <button
              type="button"
              className="os-tab is-active"
              aria-current="page"
              id="errors-section-heading"
            >
              Errors (
              {(data.errorsLoaded && !data.errorsError
                ? data.errors.length
                : run.failedCount
              ).toLocaleString('en-US')}
              )
            </button>
          </nav>
          <div className="crm-d-flex crm-align-items-center crm-gap-3 crm-ms-auto crm-pb-2">
            <ErrorsFileLink href={csv}>Download errors as file</ErrorsFileLink>
            {csv ? (
              <a
                href={rowsWithErrorsHref(run.id)}
                target="_blank"
                className="btn-crm btn-crm--outline btn-crm--sm crm-fw-semibold"
              >
                View rows with errors
              </a>
            ) : (
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm crm-fw-semibold"
                disabled
                aria-disabled="true"
                title={IMPORT_ERRORS_NOT_YOURS_TEXT}
              >
                View rows with errors
              </button>
            )}
          </div>
        </div>
        {data.errorsError ? (
          <Alert tone="danger">{data.errorsError}</Alert>
        ) : data.errorsLoaded ? (
          <ErrorsTable
            run={run}
            errors={data.errors}
            labels={data.labels}
            extraLabels={data.extraLabels}
            onTroubleshoot={onTroubleshoot}
          />
        ) : null}
      </section>
    </>
  );
}

const PAGE_SIZES = [10, 25, 50] as const;

/** The full view (`import-details.php:695-1642`). */
function FullView({
  data,
  run,
  tabParam,
  menu,
  onToggle,
  onMessage,
  onTroubleshoot,
  onAddSegment,
  onPageSize,
  timeZone,
}: {
  data: DetailsData;
  run: ImportRun;
  tabParam: string | null;
  menu: Menu | null;
  onToggle: (m: Menu) => void;
  /** A plain message (the original file's "no longer available", no contacts segment). */
  onMessage: (text: string) => void;
  onTroubleshoot: (section: string | null) => void;
  onAddSegment: () => void;
  onPageSize: (n: number) => void;
  timeZone?: string;
}) {
  const toast = useToast();
  // IDB4b: a finished bulk action loads the page and the tab count again.
  const [reload, setReload] = useState(0);
  // IDB6: the import's records with formatting issues ("--" until known, or if a load fails),
  // counted again after a bulk action (`reload`) or an inline save (`edits`; review).
  const [edits, setEdits] = useState(0);
  const formatting = useImportFormatting(run.id, reload + edits);
  const cards = useMemo(
    () => remapCards(run, data.custom, data.labels, data.optionLabels, data.extraLabels),
    [run, data.custom, data.labels, data.optionLabels, data.extraLabels],
  );
  const errorsCount = data.errorsLoaded && !data.errorsError ? data.errors.length : null;
  // IDB4a: the import's records, from the object's list filtered to this import.
  const countQuery = useMemo(
    () =>
      recordsQuery(run.objectType, {
        importId: run.id,
        activity: '',
        search: '',
        page: 1,
        size: 1,
      }),
    [run.id, run.objectType],
  );
  // The tab counts load again with each new load of a running import (its processed rows move),
  // so they keep up with the summary's counts.
  const countsReload = reload + run.processedRows;
  const count = useImportRecords(run.objectType, countQuery, countsReload);
  // IDB8: the companies the import brought in besides its own object (B5 company columns, or a
  // contact's company link), from the companies list filtered to the import.
  const companiesQuery = useMemo(
    () =>
      run.objectType === 'company'
        ? null
        : recordsQuery('company', {
            importId: run.id,
            activity: '',
            search: '',
            page: 1,
            size: 1,
          }),
    [run.id, run.objectType],
  );
  const companiesCount = useImportRecords('company', companiesQuery, countsReload);
  const companiesTotal = knownTotal(companiesCount);
  const companiesShown = companiesTabShown(run, companiesTotal);
  // B8: a tab per other object the import filled (deals, custom objects), each counted from its
  // list filtered to the import.
  const extraObjects = extraTabObjects(run);
  const extraTotals = useExtraTotals(extraObjects, run.id, reload);
  const extraTabs = extraObjects.map((objectType) => ({
    objectType,
    labels: data.extraLabels?.[objectType] ?? objectLabels(objectType),
    count: extraTabCount(extraTotals[objectType] ?? RECORDS_LOADING, run, objectType),
  }));
  const tabs = detailsTabs(
    errorsCount,
    remapCount(cards),
    data.labels,
    // As last known while it loads again (every few seconds while the import runs).
    knownTotal(count),
    companiesShown ? { count: companiesTotal } : null,
    extraTabs,
  );
  // The tab bar measures its tabs again only when one changes (B8: GeneralOsTabs' More overflow).
  const tabsKey = tabs.map((t) => `${t.id}:${t.label}`).join('|');
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const shownTabs = useMemo(() => tabs, [tabsKey]);
  // A custom object's tab id is known once its labels load, Companies once its count is in.
  const [picked, setPicked] = useState<string | null>(null);
  const active = activeTab(picked, tabParam, tabs);
  const pick = (id: string) => {
    setPicked(id);
    // The design keeps ?tab= in the address (`import-details.js:165-171`).
    try {
      const url = new URL(window.location.href);
      url.searchParams.set('tab', id);
      window.history.replaceState(window.history.state, '', url);
    } catch {
      // The tab still switches.
    }
  };
  const [size, setSize] = useState<number>(10);
  const [activity, setActivity] = useState('');
  const [search, setSearch] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [page, setPage] = useState(1);
  // Deals and custom objects page by cursor: the cursor that opens each page seen so far.
  const [cursors, setCursors] = useState<Array<string | null>>([null]);
  useEffect(() => {
    const t = setTimeout(() => setSearchQuery(search), 300);
    return () => clearTimeout(t);
  }, [search]);
  useEffect(() => {
    setPage(1);
    setCursors([null]);
  }, [activity, searchQuery, size]);
  // IDB8: the records pane shows the import's object, or its companies on the Companies tab.
  // Each tab starts with its own filter, search and first page, as the design's separate panes.
  const onCompanies = active === COMPANIES_TAB && companiesShown;
  // B8: an extra object's tab shows its records, labels and columns.
  const extraTab = extraTabs.find((x) => extraTabId(x.objectType) === active) ?? null;
  const paneObject: ImportObjectType = onCompanies
    ? 'company'
    : (extraTab?.objectType ?? run.objectType);
  const companyLabels = useFieldLabels(companiesShown ? 'company' : null);
  const extraFieldLabels = useFieldLabels(extraTab?.objectType ?? null);
  const paneCustom = onCompanies
    ? companyLabels.custom
    : extraTab
      ? extraFieldLabels.custom
      : data.custom;
  const paneOptionLabels = onCompanies
    ? companyLabels.optionLabels
    : extraTab
      ? extraFieldLabels.optionLabels
      : (data.optionLabels ?? {});
  const paneLabels = onCompanies ? objectLabels('company') : (extraTab?.labels ?? data.labels);
  const firstPane = useRef(true);
  useEffect(() => {
    if (firstPane.current) {
      firstPane.current = false;
      return;
    }
    setActivity('');
    setSearch('');
    setSearchQuery('');
    setPage(1);
    setCursors([null]);
  }, [paneObject]);
  const numbered = numberedPages(paneObject);
  const recordsActive = active !== 'errors' && active !== 'remappings';
  const query = recordsActive
    ? recordsQuery(paneObject, {
        importId: run.id,
        activity,
        search: searchQuery,
        page,
        size,
        cursor: cursors[page - 1] ?? null,
      })
    : null;
  const records = useImportRecords(paneObject, query, reload);
  const patchRow = records.patch;
  // An inline save puts the record in its row, and counts the formatting issues again (IDB6).
  const savedRow = useCallback(
    (id: string, values: Record<string, unknown>) => {
      patchRow(id, values);
      setEdits((n) => n + 1);
    },
    [patchRow],
  );
  const fields = onCompanies
    ? companyFields(run, paneCustom)
    : extraTab
      ? extraFields(run, extraTab.objectType, paneCustom)
      : recordFields(run, paneCustom);
  const rows = records.data.map((item) =>
    recordRow(paneObject, item, fields, paneOptionLabels, timeZone),
  );

  // IDB4b: checked rows, this page only (`import-details.js:290-398`). A page, size, filter,
  // search or tab change clears them: rows off the page aren't loaded, so an action must not
  // reach them (batches/IDB4b-import-bulk-edit.md).
  const [selected, setSelected] = useState<string[]>([]);
  const [editing, setEditing] = useState<{
    rowId: string;
    cell: number;
    edit: Exclude<DesignEdit, { kind: 'locked' }>;
    pos: { top: number; left: number; minWidth: number } | null;
  } | null>(null);
  useEffect(() => {
    setSelected([]);
    setEditing(null);
  }, [activity, searchQuery, size, page, active]);
  // An open editor holds the row as it was; a reload (after a bulk action) closes it (review).
  useEffect(() => setEditing(null), [reload]);
  // A delete that emptied the last page: back to the page that is now last (review).
  useEffect(() => {
    const total = records.total ?? 0;
    if (records.state !== 'ready' || page === 1 || records.data.length > 0 || total === 0) return;
    setPage(numbered ? Math.max(1, Math.ceil(total / size)) : 1);
  }, [records.state, records.data.length, records.total, page, numbered, size]);
  const pageIds = records.state === 'ready' ? records.data.map((d) => String(d.id)) : [];
  const pageKey = pageIds.join(',');
  // After a reload, rows still on the page stay checked; deleted ones go (js:637-649).
  useEffect(() => {
    if (records.state !== 'ready') return;
    const ids = pageKey ? pageKey.split(',') : [];
    setSelected((cur) => {
      const next = keepOnPage(cur, ids);
      return next.length === cur.length ? cur : next;
    });
  }, [pageKey, records.state]);

  const me = useCurrentUser();
  const access = useFieldAccess(paneObject);
  const editData = useRecordsEditData(paneObject, recordsActive);
  const editCtx = useCellEditContext({
    objectType: paneObject,
    singular: paneLabels.singular,
    data: editData,
    onSaved: savedRow,
    onGone: records.drop,
    timeZone,
  });
  const objectRules = me.permissionSet.rules.objects;
  // Custom objects follow the company rules, as the API (`ObjectListView.tsx:294-295`).
  const rule =
    paneObject === 'contact'
      ? objectRules.contact
      : paneObject === 'deal'
        ? objectRules.deal
        : paneObject === 'task'
          ? objectRules.task
          : paneObject === 'call'
            ? objectRules.activity
            : objectRules.company;
  const bulkProps = editData.customDefs
    ? editProperties(paneObject, {
        customDefs: editData.customDefs,
        locked: (f) => access.locked(f),
        picklist: (f) =>
          editData.picklists
            .filter((o) => o.field === f && !o.archived)
            .map((o) => ({ value: o.value, label: o.label })),
      })
    : null;
  const editorOf = (item: Record<string, unknown>, field: string) =>
    editCtx ? cellDesignEditor(paneObject, item, field, editCtx) : null;
  const kinds = records.data.map((item) =>
    fields.map((f) => {
      const ed = editorOf(item, f.field);
      return !ed ? null : ed.kind === 'locked' ? ed : { kind: ed.kind, label: ed.label };
    }),
  );
  /** A save from the editor: the design's toast, or the reason it failed. */
  const saveCell = (ed: Exclude<DesignEdit, { kind: 'locked' }>, value: string, shown: string) => {
    ed.save(value).then(
      () => toast(cellEditToast(ed.label, shown), 'success'),
      (err: unknown) => toast(err instanceof Error ? err.message : errorText(err), 'danger'),
    );
  };
  const startEdit = (rowId: string, cell: number, el: HTMLElement) => {
    // The same dropdown cell again closes it (js:1055-1058).
    if (editing?.rowId === rowId && editing.cell === cell) {
      if (editing.edit.kind === 'select') setEditing(null);
      return;
    }
    const item = records.data.find((d) => String(d.id) === rowId);
    const f = fields[cell];
    const ed = item && f ? editorOf(item, f.field) : null;
    if (!ed || ed.kind === 'locked') return;
    setEditing({
      rowId,
      cell,
      edit: ed,
      pos:
        ed.kind === 'select'
          ? inlinePopoverPos(el.getBoundingClientRect(), {
              width: window.innerWidth,
              height: window.innerHeight,
            })
          : null,
    });
  };
  // The dropdown closes on a click outside it and its cell, a resize, or a scroll of the table
  // or page (js:1201-1204, :1222-1225).
  const selectOpen = editing?.edit.kind === 'select';
  useEffect(() => {
    if (!selectOpen) return;
    const close = () => setEditing(null);
    const onDown = (e: MouseEvent) => {
      const t = e.target as Element;
      if (!t.closest?.('[data-inline-popover]') && !t.closest?.('td.is-editing')) close();
    };
    const onScroll = (e: Event) => {
      const t = e.target as Element | Document;
      if (t === document || (t as Element).closest?.('.lp-tablewrap')) close();
    };
    window.addEventListener('resize', close);
    window.addEventListener('scroll', onScroll, true);
    document.addEventListener('mousedown', onDown);
    return () => {
      window.removeEventListener('resize', close);
      window.removeEventListener('scroll', onScroll, true);
      document.removeEventListener('mousedown', onDown);
    };
  }, [selectOpen]);
  const selectedRecords = rows
    .filter((r) => selected.includes(r.id))
    .map((r) => {
      const item = records.data.find((d) => String(d.id) === r.id);
      return {
        id: r.id,
        name: r.name,
        href: r.href,
        eligible: paneObject === 'contact' ? Boolean(item?.email) : true,
        filled: {},
      };
    });
  // No paging while a page loads: the next cursor isn't known until it's in (review).
  const pager = recordsPager({
    total: records.total ?? 0,
    size,
    page,
    numbered,
    loading: records.state === 'loading',
  });
  const goTo = (next: number) => {
    if (!numbered && next > page) {
      setCursors((c) => {
        const copy = [...c];
        copy[page] = records.nextCursor;
        return copy;
      });
    }
    setPage(next);
  };
  const pane = errorsPaneState({
    status: run.status,
    loaded: data.errorsLoaded,
    failed: Boolean(data.errorsError),
    count: data.errors.length,
  });
  const plural = paneLabels.plural;
  // B9: custom objects named by their labels (the run's own, and those it filled besides).
  const viewItems = viewRecordsItems(run, companiesShown, {
    [run.objectType]: data.labels,
    ...data.extraLabels,
  });
  const cols = onCompanies
    ? companyColumns(run, paneCustom)
    : extraTab
      ? extraColumns(run, extraTab.objectType, paneCustom)
      : recordColumns(run, paneCustom);

  const actions: { label: string; run: () => void }[] = [
    { label: 'Add imported contacts to segment', run: onAddSegment },
  ];

  return (
    <>
      <section className="metrics-grid" aria-label="Import summary statistics">
        <div className="card crm-p-4">
          <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-flex-wrap crm-gap-3 crm-mb-4">
            <h2 className="card__title crm-fs-5 crm-fw-bold crm-m-0">Summary</h2>
            <div className="crm-d-flex crm-align-items-center crm-flex-wrap crm-gap-2">
              {/* B8: the import's objects; none to link yet (a deal or custom object import, until
                  B9 filters their lists), no menu. */}
              {viewItems.length ? (
                <div className="dropdown" data-dropdown="">
                  <MenuButton
                    label="View imported records"
                    open={menu === 'records'}
                    onClick={() => onToggle('records')}
                  />
                  {menu === 'records' ? (
                    <div className="dropdown__menu dropdown__menu--right">
                      {viewItems.map((item) => (
                        <Link key={item.href} href={item.href} className="dropdown__item">
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  ) : null}
                </div>
              ) : null}
              <div className="dropdown" data-dropdown="">
                <MenuButton
                  label="Actions"
                  open={menu === 'actions'}
                  onClick={() => onToggle('actions')}
                />
                {menu === 'actions' ? (
                  <div className="dropdown__menu dropdown__menu--right">
                    <SegmentItem
                      run={run}
                      onDone={() => onToggle('actions')}
                      onMessage={onMessage}
                    />
                    {actions.map((a) => (
                      <button
                        key={a.label}
                        type="button"
                        className="dropdown__item"
                        onClick={() => {
                          onToggle('actions');
                          a.run();
                        }}
                      >
                        {a.label}
                      </button>
                    ))}
                    <OriginalFileItem
                      id={run.id}
                      fileAvailable={run.fileAvailable}
                      canManage={run.canManage}
                      onDone={() => onToggle('actions')}
                      onMessage={onMessage}
                    />
                  </div>
                ) : null}
              </div>
            </div>
          </div>
          <Metrics items={summaryMetrics(run, 'full')} cols={4} />
        </div>
        <div className="card crm-p-4">
          <h2 className="card__title crm-fs-5 crm-fw-bold crm-mb-4">Clean up imported data</h2>
          <Metrics items={formattingCards(formatting)} cols={2} />
        </div>
      </section>

      <section className="card crm-p-4" aria-label="Import details">
        <GeneralOsTabs
          label="Import Detail Tabs"
          tabs={shownTabs}
          active={active}
          onSelect={pick}
        />

        {active === 'errors' ? (
          <div className="di-tab-pane is-active" id="pane-errors" role="tabpanel">
            {pane === 'failed' ? (
              <Alert tone="danger">{data.errorsError}</Alert>
            ) : pane === 'list' ? (
              <ErrorsTable
                run={run}
                errors={data.errors}
                labels={data.labels}
                extraLabels={data.extraLabels}
                onTroubleshoot={onTroubleshoot}
              />
            ) : pane === 'none' ? (
              <div className="di-empty-state">
                <div className="di-empty-circle">
                  <CrmIcon name="check" className="iconSize-24" />
                </div>
                <h3 className="crm-fs-5 crm-fw-bold crm-m-0">Import completed with no errors</h3>
              </div>
            ) : pane === 'pending' ? (
              <p className="crm-text-muted crm-m-0">{NONE}</p>
            ) : null}
          </div>
        ) : active === 'remappings' ? (
          <div className="di-tab-pane is-active" id="pane-remappings" role="tabpanel">
            {cards.length === 0 ? (
              <p className="crm-text-muted crm-m-0">{NONE}</p>
            ) : (
              <div className="di-remap-grid">
                {cards.map((card) => (
                  <div key={card.column + card.targetProperty} className="di-remap-card">
                    <div className="di-remap-header">
                      <div className="di-remap-col">
                        <span className="di-remap-label">Column</span>
                        <div className="di-remap-name" title={card.column}>
                          {card.column}
                        </div>
                      </div>
                      <div className="di-remap-arrow" aria-hidden="true">
                        <ArrowRight size={16} />
                      </div>
                      <div className="di-remap-col di-remap-col--right">
                        <span className="di-remap-label">{card.targetLabel}</span>
                        <div className="di-remap-name" title={card.targetProperty}>
                          {card.targetProperty}
                        </div>
                      </div>
                    </div>
                    <div className="di-remap-body">
                      {card.values.map((v) => (
                        <div key={v.from} className="di-remap-row">
                          <div className="di-remap-val" title={v.from}>
                            {v.from}
                          </div>
                          <div className="di-remap-arrow" aria-hidden="true">
                            <ArrowRight size={14} />
                          </div>
                          <div className="di-remap-val di-remap-val--right" title={v.to}>
                            {v.pill ? (
                              <span className="di-remap-pill">{v.to}</span>
                            ) : (
                              <span>{v.to}</span>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        ) : (
          <div className="di-tab-pane is-active" id={`pane-${active}`} role="tabpanel">
            <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-flex-wrap crm-gap-3 crm-mb-3">
              <div className="crm-d-flex crm-align-items-center crm-flex-wrap crm-gap-2">
                <CustomSelect
                  placeholder="All activity types"
                  value={activity}
                  searchable={false}
                  options={[
                    { value: '', label: 'All activity types' },
                    { value: 'Created', label: 'Created' },
                    { value: 'Updated', label: 'Updated' },
                  ]}
                  onChange={setActivity}
                />
                {/* Hidden while the bulk bar shows (`import-details.js:334-351`). */}
                <label className="lp-search lp-search--pill" hidden={selected.length > 0}>
                  <input
                    type="search"
                    placeholder={plural === 'contacts' ? 'Search ( / )' : `Search ${plural} ( / )`}
                    aria-label={`Search ${plural}`}
                    autoComplete="off"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                  />
                  <svg
                    className="lp-i"
                    viewBox="0 0 24 24"
                    aria-hidden="true"
                    focusable="false"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <circle cx="11" cy="11" r="7" />
                    <path d="m21 21-4.3-4.3" />
                  </svg>
                </label>
              </div>
            </div>
            <ImportBulkControls
              // IDB8: each tab's bar starts closed (its dialogs hold the object's choices).
              key={paneObject}
              objectType={paneObject}
              singular={capital(paneLabels.singular)}
              plural={plural}
              ids={selected}
              records={selectedRecords}
              rights={{
                // P2a: contacts, companies and custom objects by the Delete scope; deals as before.
                delete: paneObject === 'deal' ? rule.delete : deletesAny(rule),
                share: rule.edit !== 'none',
              }}
              meId={me.user.id}
              owners={ownerOptions(editData.owners)}
              ownersError={editData.ownersError}
              editProperties={bulkProps}
              linkTypes={editData.linkTypes}
              naming={{ importName: run.name ?? null, fileName: run.fileName }}
              onClear={() => setSelected([])}
              onDone={() => setReload((n) => n + 1)}
            />
            <RecordsTable
              plural={plural}
              columns={cols}
              rows={rows}
              state={records.state}
              error={records.error}
              selection={{
                selected: new Set(selected),
                onToggle: (id) => setSelected((cur) => toggleId(cur, id)),
                onTogglePage: () => setSelected((cur) => togglePage(cur, pageIds)),
              }}
              edit={{
                kinds,
                editing: editing ? { rowId: editing.rowId, cell: editing.cell } : null,
                editor:
                  editing?.edit.kind === 'text' ? (
                    <InlineTextInput
                      label={editing.edit.label}
                      value={editing.edit.value}
                      onCancel={() => setEditing(null)}
                      onCommit={(typed) => {
                        const ed = editing.edit;
                        setEditing(null);
                        // Emptied: back to the old value; unchanged: nothing (js:966-987).
                        if (textCommit(ed.value, typed) === 'save') {
                          saveCell(ed, typed.trim(), typed.trim());
                        }
                      }}
                    />
                  ) : null,
                onStart: startEdit,
              }}
            />
            {editing?.edit.kind === 'select' && editing.pos ? (
              <InlineSelectPopover
                options={editing.edit.options}
                value={editing.edit.value}
                pos={editing.pos}
                onClose={() => setEditing(null)}
                onPick={(value, label) => {
                  const ed = editing.edit;
                  setEditing(null);
                  if (value !== ed.value) saveCell(ed, value, label);
                }}
              />
            ) : null}
            <nav className="wf-pager crm-mt-4" aria-label="Pagination">
              <button
                type="button"
                className="wf-pager__btn"
                disabled={!pager.hasPrev}
                aria-label="Previous page"
                onClick={() => goTo(page - 1)}
              >
                <CrmIcon name="chevron-left" className="iconSize-14" />
                Prev
              </button>
              <span className="wf-pager__nums">
                {pager.numbers.map((n) => (
                  <button
                    key={n}
                    type="button"
                    className={cn('wf-pager__num', n === page && 'is-active')}
                    aria-current={n === page ? 'page' : undefined}
                    onClick={() => goTo(n)}
                  >
                    {n}
                  </button>
                ))}
              </span>
              <button
                type="button"
                className="wf-pager__btn"
                disabled={!pager.hasNext || (!numbered && !records.nextCursor)}
                aria-label="Next page"
                onClick={() => goTo(page + 1)}
              >
                Next
                <CrmIcon name="chevron-right" className="iconSize-14" />
              </button>
              <div className="dropdown" data-dropdown="">
                <button
                  type="button"
                  className="wf-pager__btn wf-pager__size"
                  aria-expanded={menu === 'size'}
                  aria-label="Rows per page"
                  onClick={() => onToggle('size')}
                >
                  <span>{size}</span> per page{' '}
                  <CrmIcon name="chevron-down" className="iconSize-14" />
                </button>
                {menu === 'size' ? (
                  <div className="dropdown__menu dropdown__menu--up dropdown__menu--right">
                    {PAGE_SIZES.map((n) => (
                      <button
                        key={n}
                        type="button"
                        className={cn('dropdown__item', n === size && 'is-selected')}
                        onClick={() => {
                          setSize(n);
                          onToggle('size');
                          onPageSize(n);
                        }}
                      >
                        {n} per page
                      </button>
                    ))}
                  </div>
                ) : null}
              </div>
            </nav>
          </div>
        )}
      </section>
    </>
  );
}

/**
 * Labels for an object's custom fields and dropdown options (null: none); without them the
 * stored name or value shows. IDB8: also loaded for companies on the Companies tab, kept apart
 * from the import object's (a field name can exist on both).
 */
function useFieldLabels(objectType: ImportObjectType | null): {
  custom: CustomLabel[];
  optionLabels: OptionLabels;
} {
  const [custom, setCustom] = useState<CustomLabel[]>([]);
  const [optionLabels, setOptionLabels] = useState<OptionLabels>({});
  useEffect(() => {
    setCustom([]);
    setOptionLabels({});
    if (!objectType || !isBuiltInImportType(objectType)) return;
    let live = true;
    listCustomProperties({ objectType }).then(
      (props) => {
        if (!live) return;
        setCustom(props.map((p) => ({ name: p.name, label: p.label })));
        const byField: OptionLabels = {};
        for (const p of props) {
          if (p.options?.length) {
            byField[`custom.${p.name}`] = Object.fromEntries(
              p.options.map((o) => [o.value, o.label]),
            );
          }
        }
        setOptionLabels((cur) => ({ ...cur, ...byField }));
      },
      () => {},
    );
    // Archived options too: an older import may have mapped to one.
    listPicklistOptions({ objectType, includeArchived: true }).then(
      (options) => {
        if (!live) return;
        const byField: OptionLabels = {};
        for (const o of options) (byField[o.field] ??= {})[o.value] = o.label;
        setOptionLabels((cur) => ({ ...cur, ...byField }));
      },
      () => {},
    );
    return () => {
      live = false;
    };
  }, [objectType]);
  // B8 (review): on a tab switch, the render before the effect runs still holds the other
  // object's labels; they aren't shown under this object's columns.
  const labelsFor = useRef(objectType);
  const fresh = labelsFor.current === objectType;
  useEffect(() => {
    labelsFor.current = objectType;
  }, [objectType]);
  return fresh ? { custom, optionLabels } : { custom: [], optionLabels: {} };
}

/** IDB6: the two "Clean up imported data" counts, each null until loaded (and if it fails). */
function useImportFormatting(
  importId: string,
  refresh = 0,
): { contact: number | null; company: number | null } {
  const [counts, setCounts] = useState<{ contact: number | null; company: number | null }>({
    contact: null,
    company: null,
  });
  const shownFor = useRef(importId);
  useEffect(() => {
    let live = true;
    // Another import starts unknown; a recount keeps the numbers shown until the new ones come.
    if (shownFor.current !== importId) {
      shownFor.current = importId;
      setCounts({ contact: null, company: null });
    }
    for (const objectType of ['contact', 'company'] as const) {
      getImportFormatting(importId, objectType).then(
        (n) => {
          if (live) setCounts((cur) => ({ ...cur, [objectType]: n }));
        },
        () => {},
      );
    }
    return () => {
      live = false;
    };
  }, [importId, refresh]);
  return counts;
}

interface RecordsState {
  state: 'loading' | 'ready' | 'error';
  error: string | null;
  data: Array<Record<string, unknown>>;
  total: number | null;
  nextCursor: string | null;
  /** IDB8: the object the rows belong to, once loaded. */
  of?: string;
}

const RECORDS_LOADING: RecordsState = {
  state: 'loading',
  error: null,
  data: [],
  total: null,
  nextCursor: null,
};

/** B8: each extra object's records total for the import (one row asked for, its total kept). */
function useExtraTotals(
  objectTypes: readonly string[],
  importId: string,
  reload: number,
): Record<string, { state: 'loading' | 'ready' | 'error'; total: number | null }> {
  const key = objectTypes.join(',');
  const [totals, setTotals] = useState<
    Record<string, { state: 'loading' | 'ready' | 'error'; total: number | null }>
  >({});
  useEffect(() => {
    if (!key) return;
    let live = true;
    for (const objectType of key.split(',')) {
      setTotals((t) => ({
        ...t,
        [objectType]: { state: 'loading', total: t[objectType]?.total ?? null },
      }));
      const q = recordsQuery(objectType, { importId, activity: '', search: '', page: 1, size: 1 });
      fetchImportRecords(objectType, q).then(
        (pg) => {
          if (live) setTotals((t) => ({ ...t, [objectType]: { state: 'ready', total: pg.total } }));
        },
        () => {
          if (live) setTotals((t) => ({ ...t, [objectType]: { state: 'error', total: null } }));
        },
      );
    }
    return () => {
      live = false;
    };
  }, [key, importId, reload]);
  return totals;
}

/**
 * IDB4a: one page of the import's records (`query` null: nothing to load). IDB4b: `reload`
 * loads it again (after a bulk action); `patch` puts a saved record into its row; `drop` takes a
 * row deleted elsewhere off the page.
 */
function useImportRecords(
  objectType: string,
  query: Record<string, string | number> | null,
  reload = 0,
): RecordsState & {
  patch: (id: string, values: Record<string, unknown>) => void;
  drop: (id: string) => void;
} {
  const key = query ? JSON.stringify(query) : null;
  const [st, setSt] = useState<RecordsState>(RECORDS_LOADING);
  // IDB8: another object's rows (a tab switch) never show under this object's columns.
  const loadedFor = useRef(objectType);
  useEffect(() => {
    if (!key) return;
    let live = true;
    const same = loadedFor.current === objectType;
    loadedFor.current = objectType;
    setSt((cur) => (same ? { ...cur, state: 'loading', error: null } : RECORDS_LOADING));
    fetchImportRecords(objectType, JSON.parse(key) as Record<string, string | number>).then(
      (p) => {
        if (live) setSt({ state: 'ready', error: null, ...p, of: objectType });
      },
      (err: unknown) => {
        if (live) setSt({ ...RECORDS_LOADING, state: 'error', error: errorText(err) });
      },
    );
    return () => {
      live = false;
    };
  }, [objectType, key, reload]);
  const patch = useCallback((id: string, values: Record<string, unknown>) => {
    setSt((cur) => ({
      ...cur,
      data: cur.data.map((d) => (d.id === id ? { ...d, ...values } : d)),
    }));
  }, []);
  const drop = useCallback((id: string) => {
    setSt((cur) =>
      // Only a row on this page lowers the total (review: a late 404 after a page change).
      cur.data.some((d) => d.id === id)
        ? {
            ...cur,
            data: cur.data.filter((d) => d.id !== id),
            total: cur.total === null ? null : Math.max(0, cur.total - 1),
          }
        : cur,
    );
  }, []);
  // IDB8 (review): until its effect has run, a tab switch's first render still holds the other
  // object's rows; they read as loading, never under this object's columns.
  if (st.of !== undefined && st.of !== objectType) return { ...RECORDS_LOADING, patch, drop };
  return { ...st, patch, drop };
}

/** IDB4b: how a cell is edited in place (the design's `data-editable`), or why it can't be. */
export type CellKind =
  { kind: 'text' | 'select'; label: string } | { kind: 'locked'; title: string } | null;

/** The header box, checked, unchecked or indeterminate (`import-details.js:316-327`). */
function PageCheckbox({
  plural,
  state,
  onChange,
}: {
  plural: string;
  state: 'none' | 'some' | 'all';
  onChange: () => void;
}) {
  const ref = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (ref.current) ref.current.indeterminate = state === 'some';
  }, [state]);
  return (
    <input
      ref={ref}
      type="checkbox"
      className="lp-cb"
      aria-label={`Select all ${plural}`}
      checked={state === 'all'}
      onChange={onChange}
    />
  );
}

/**
 * The records tab's table (`import-details.php:1015-1187`). IDB4b: with `selection`, the row
 * checkboxes work; with `edit`, mapped cells take the design's inline editor. Without them, 4a's
 * table.
 */
export function RecordsTable({
  plural,
  columns,
  rows,
  state,
  error,
  selection = null,
  edit = null,
}: {
  plural: string;
  columns: string[];
  rows: RecordRowView[];
  state: 'loading' | 'ready' | 'error';
  error: string | null;
  selection?: {
    selected: ReadonlySet<string>;
    onToggle: (id: string) => void;
    onTogglePage: () => void;
  } | null;
  edit?: {
    /** Per row, per value cell (the Name cell isn't edited). */
    kinds: CellKind[][];
    editing: { rowId: string; cell: number } | null;
    /** The text box, drawn in the cell being edited. */
    editor: React.ReactNode;
    onStart: (rowId: string, cell: number, el: HTMLElement) => void;
  } | null;
}) {
  if (state === 'error') return <Alert tone="danger">{error}</Alert>;
  const shownIds = state === 'ready' ? rows.map((r) => r.id) : [];
  const pageState = selection ? pageCheck([...selection.selected], shownIds) : 'none';
  const valueCell = (r: RecordRowView, c: string, i: number) => {
    const kind = edit?.kinds[rows.indexOf(r)]?.[i] ?? null;
    const muted = c === NONE && 'crm-text-muted';
    if (!edit || !kind) {
      return (
        <td key={i} className={cn('lp-td', muted)}>
          {c}
        </td>
      );
    }
    if (kind.kind === 'locked') {
      return (
        <td key={i} className={cn('lp-td', muted)} title={kind.title}>
          {c}
        </td>
      );
    }
    const editing = edit.editing?.rowId === r.id && edit.editing.cell === i;
    return (
      <td
        key={i}
        className={cn('lp-td', muted, editing && 'is-editing')}
        data-editable={kind.kind}
        data-field-name={kind.label}
        onClick={(e) => edit.onStart(r.id, i, e.currentTarget)}
      >
        {kind.kind === 'text' ? (
          editing ? (
            edit.editor
          ) : (
            <span className="lp-editable-text" data-cell-value="">
              {c}
            </span>
          )
        ) : (
          <div className="lp-editable-cell lp-editable-cell--select">
            {c === NONE ? (
              <span className="crm-text-muted" data-cell-value="">
                {c}
              </span>
            ) : (
              <span className="badge" data-cell-value="">
                {c}
              </span>
            )}
            <span className="lp-editable-chevron" aria-hidden="true">
              <CrmIcon name="chevron-down" className="iconSize-12" />
            </span>
          </div>
        )}
      </td>
    );
  };
  return (
    <div className="lp-tablewrap di-tablewrap">
      <table className="lp-table di-table" aria-label={`Imported ${plural}`}>
        <thead>
          <tr>
            <th scope="col" className="lp-th lp-th--check">
              {selection ? (
                <PageCheckbox plural={plural} state={pageState} onChange={selection.onTogglePage} />
              ) : (
                <input
                  type="checkbox"
                  className="lp-cb"
                  aria-label={`Select all ${plural}`}
                  disabled
                />
              )}
            </th>
            {columns.map((c, i) => (
              <th key={c} scope="col" className={cn('lp-th', i === 0 && 'lp-th--name')} title={c}>
                <div className="lp-th__in">
                  <span className="lp-th__lbl">{c}</span>
                </div>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {state === 'ready' && rows.length > 0 ? (
            rows.map((r) => (
              <tr
                key={r.id}
                className={cn('lp-tr', selection?.selected.has(r.id) && 'is-selected')}
                data-row=""
              >
                <td className="lp-td lp-td--check">
                  {selection ? (
                    <input
                      type="checkbox"
                      className="lp-cb"
                      aria-label={`Select ${r.name}`}
                      checked={selection.selected.has(r.id)}
                      onChange={() => selection.onToggle(r.id)}
                    />
                  ) : (
                    <input
                      type="checkbox"
                      className="lp-cb"
                      aria-label={`Select ${r.name}`}
                      disabled
                    />
                  )}
                </td>
                <td className="lp-td lp-td--name">
                  <div className="di-name-cell">
                    <div className="lp-name">
                      <span className="avatar avatar--sm" aria-hidden="true">
                        {r.initials}
                      </span>
                      <Link className="di-name-link" title={r.name} href={r.href}>
                        {r.name}
                      </Link>
                    </div>
                  </div>
                </td>
                {r.cells.map((c, i) => valueCell(r, c, i))}
              </tr>
            ))
          ) : (
            <tr className="lp-tr">
              <td className="lp-td crm-text-muted" colSpan={columns.length + 1}>
                {NONE}
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );
}

/** Rows with errors (`import-details.php:412-557`). */
function RowsView({
  data,
  run,
  onTroubleshoot,
}: {
  data: DetailsData;
  run: ImportRun;
  onTroubleshoot: (section: string | null) => void;
}) {
  const toast = useToast();
  const [mappedOnly, setMappedOnly] = useState(false);
  const [copied, setCopied] = useState<number | null>(null);
  const [tip, setTip] = useState<{ text: string; rect: DOMRect; target: string | null } | null>(
    null,
  );
  const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const cols = errorColumns(run);
  const count = data.errorsLoaded && !data.errorsError ? data.errors.length : null;
  const csv = errorsFileHref(run);

  const show = (text: string, el: HTMLElement, target: string | null) => {
    if (hideTimer.current) clearTimeout(hideTimer.current);
    setTip({ text, rect: el.getBoundingClientRect(), target });
  };
  // The design hides it 150ms after the pointer leaves, unless it reaches the popover.
  const hide = () => {
    if (hideTimer.current) clearTimeout(hideTimer.current);
    hideTimer.current = setTimeout(() => setTip(null), 150);
  };
  useEffect(() => {
    if (!tip) return;
    const close = () => setTip(null);
    window.addEventListener('resize', close);
    window.addEventListener('scroll', close, true);
    return () => {
      window.removeEventListener('resize', close);
      window.removeEventListener('scroll', close, true);
    };
  }, [tip]);
  useEffect(
    () => () => {
      if (hideTimer.current) clearTimeout(hideTimer.current);
    },
    [],
  );

  const copy = (rowNumber: number, value: string) => {
    navigator.clipboard?.writeText(value).then(
      () => {
        setCopied(rowNumber);
        setTimeout(() => setCopied((c) => (c === rowNumber ? null : c)), 1500);
        toast(`Copied ${value} to clipboard`);
      },
      () => {},
    );
  };

  return (
    <>
      <header className="record-header">
        <Link className="record-header__back" href={importDetailsHref(run.id)}>
          <CrmIcon name="chevron-left" className="iconSize-14" />
          <span>Import details</span>
        </Link>
        <div className="record-header__body">
          <div className="record-header__main">
            <h1 className="record-header__title">Rows with errors</h1>
            <div className="crm-d-flex crm-align-items-center crm-gap-2 crm-flex-wrap">
              <span className="crm-text-muted crm-fs-7">
                {count === null ? NONE : count} {count === 1 ? 'error' : 'errors'}
              </span>
              <span className="badge badge--subtle">{run.fileName}</span>
            </div>
          </div>
          <div className="record-header__aside">
            <ErrorsFileLink href={csv}>Download rows with errors as file</ErrorsFileLink>
          </div>
        </div>
      </header>

      <div className="crm-d-flex crm-align-items-center crm-justify-content-end crm-mb-3">
        <div className="di-view-filter" role="radiogroup" aria-label="Table columns display mode">
          <span className="di-view-filter__lbl">View</span>
          {(
            [
              ['all', 'All columns'],
              ['mapped', 'Only mapped columns'],
            ] as const
          ).map(([value, label]) => (
            <label key={value} className="di-radio-label">
              <input
                type="radio"
                name="errorColsView"
                value={value}
                className="di-radio-input"
                checked={mappedOnly === (value === 'mapped')}
                onChange={() => setMappedOnly(value === 'mapped')}
              />
              <span className="di-radio-text">{label}</span>
            </label>
          ))}
        </div>
      </div>

      {data.errorsError ? <Alert tone="danger">{data.errorsError}</Alert> : null}

      <div className="lp-tablewrap di-tablewrap di-error-tablewrap crm-mb-4">
        <table
          className={cn('lp-table di-table di-error-table', mappedOnly && 'is-mapped-only')}
          id="rowsWithErrorsTable"
        >
          <thead>
            <tr className="lp-tr lp-tr--head">
              <th className="lp-th" scope="col">
                <div className="lp-th__in">
                  <span className="lp-th__lbl">Import Error</span>
                </div>
              </th>
              {cols.map((c) => (
                <th
                  key={c.name}
                  className="lp-th"
                  scope="col"
                  data-col-unmapped={c.mapped ? undefined : ''}
                >
                  <div className="lp-th__in di-th-in--stacked">
                    <span className="lp-th__lbl">{c.name}</span>
                    <span className="di-th-sub">{c.sub}</span>
                  </div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {data.errors.map((e) => {
              const view = errorRowView(e, run.columns);
              const target = view.scrollColumn
                ? errorCellId(e.rowNumber, run.columns.indexOf(view.scrollColumn))
                : null;
              return (
                <tr key={e.rowNumber} className="lp-tr di-error-tr">
                  <td className="lp-td di-td--error">
                    <div className="di-error-cell">
                      <div className="di-error-primary">
                        <span
                          className="di-error-icon-wrap"
                          role="button"
                          tabIndex={0}
                          aria-label="Error details"
                          onMouseEnter={(ev) => show(view.explanation, ev.currentTarget, target)}
                          onMouseLeave={hide}
                          onFocus={(ev) => show(view.explanation, ev.currentTarget, target)}
                          onBlur={hide}
                        >
                          <svg
                            className="di-error-warning-icon"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            aria-hidden="true"
                          >
                            <circle cx="12" cy="12" r="10" />
                            <line x1="12" y1="8" x2="12" y2="12" />
                            <line x1="12" y1="16" x2="12.01" y2="16" />
                          </svg>
                        </span>
                        <a
                          href="#"
                          className="di-error-title di-troubleshoot-trigger"
                          title={`Click to troubleshoot ${view.title}`}
                          onClick={(ev) => {
                            ev.preventDefault();
                            onTroubleshoot(view.section);
                          }}
                        >
                          {view.title}
                        </a>
                      </div>
                      <div className="di-error-secondary">
                        <span className="di-error-loc">{view.location}</span>
                        <button
                          type="button"
                          className={cn('di-error-copy', copied === e.rowNumber && 'is-copied')}
                          title="Copy location"
                          aria-label="Copy location"
                          onClick={() => copy(e.rowNumber, view.location)}
                        >
                          <CrmIcon name="copy" className="iconSize-12 di-copy-icon" />
                        </button>
                      </div>
                    </div>
                  </td>
                  {cols.map((c, ci) => (
                    <td
                      key={c.name}
                      className="lp-td"
                      data-col-unmapped={c.mapped ? undefined : ''}
                    >
                      {view.badColumns.includes(c.name) ? (
                        // The design's cell with an error (`import-details.php:536-546`).
                        <div className="di-cat-cell" id={errorCellId(e.rowNumber, ci)}>
                          <CellWarningIcon />
                          <span className="di-cat-val">{e.rowData[c.name] || NONE}</span>
                        </div>
                      ) : (
                        e.rowData[c.name] || NONE
                      )}
                    </td>
                  ))}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      {tip ? (
        <ErrorPopover
          text={tip.text}
          rect={tip.rect}
          target={tip.target}
          onScrolled={() => setTip(null)}
          onEnter={() => {
            if (hideTimer.current) clearTimeout(hideTimer.current);
          }}
          onLeave={hide}
        />
      ) : null}
    </>
  );
}

/**
 * The design's floating popover (`import-details.js:1366-1544`). Its "Scroll to edit with error"
 * link shows when the bad cell is known (IDB3), and is hidden otherwise, as the design does.
 */
function ErrorPopover({
  text,
  rect,
  target = null,
  onScrolled,
  onEnter,
  onLeave,
}: {
  text: string;
  rect: DOMRect;
  /** The bad cell's id. */
  target?: string | null;
  onScrolled?: () => void;
  onEnter: () => void;
  onLeave: () => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const [place, setPlace] = useState<PopoverPlace | null>(null);
  useLayoutEffect(() => {
    const height = ref.current?.offsetHeight ?? 0;
    setPlace(
      popoverPlace(rect, height, {
        width: document.documentElement.clientWidth || window.innerWidth,
        height: window.innerHeight,
      }),
    );
  }, [rect, text]);
  return (
    <div
      ref={ref}
      className="di-floating-popover is-visible"
      role="tooltip"
      data-placement={place?.placement}
      style={
        place
          ? { left: place.left, top: place.top, width: place.width }
          : { left: 0, top: 0, visibility: 'hidden' }
      }
      onMouseEnter={onEnter}
      onMouseLeave={onLeave}
    >
      <div
        className="di-floating-popover__arrow"
        style={place ? { left: place.arrowX } : undefined}
      />
      <p className="di-floating-popover__text">{text}</p>
      {target ? (
        <a
          href={`#${target}`}
          className="di-floating-popover__link"
          onClick={(e) => {
            e.preventDefault();
            scrollToCell(target);
            onScrolled?.();
          }}
        >
          <span>Scroll to edit with error</span>
          <svg
            width="12"
            height="12"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="M5 12h14" />
            <path d="m12 5 7 7-7 7" />
          </svg>
        </a>
      ) : null}
    </div>
  );
}

/** The design's scroll and flash on the bad cell (`import-details.js:1528-1538`). */
function scrollToCell(id: string) {
  const el = document.getElementById(id);
  if (!el) return;
  el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
  el.classList.add('crm-highlight-flash');
  setTimeout(() => el.classList.remove('crm-highlight-flash'), 1500);
}

/** The design's warning mark in a bad cell (`import-details.php:544`). */
function CellWarningIcon() {
  return (
    <svg
      aria-hidden="true"
      className="iconSize-18"
      fill="rgb(217, 0, 43)"
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 32 32"
      focusable="false"
    >
      <path d="M26.9 29.29H4.3c-1.23 0-2.34-.63-2.96-1.69a3.38 3.38 0 0 1-.05-3.41L12.58 3.64c.61-1.12 1.74-1.78 3.02-1.78s2.4.67 3.02 1.78l11.3 20.54c.59 1.08.57 2.35-.05 3.41s-1.74 1.69-2.97 1.69ZM3.29 25.28c-.29.52-.08.98.02 1.15s.4.57 1 .57H26.9c.6 0 .9-.4 1-.57s.31-.63.02-1.15L16.62 4.74c-.3-.54-.81-.6-1.01-.6s-.72.06-1.01.6z" />
      <path d="M15.6 19c-.63 0-1.14-.51-1.14-1.14V11a1.14 1.14 0 1 1 2.28 0v6.86c0 .63-.51 1.14-1.14 1.14" />
      <circle cx="15.6" cy="23" r=".57" />
      <path d="M15.6 24.71c-.94 0-1.71-.77-1.71-1.71s.77-1.71 1.71-1.71 1.71.77 1.71 1.71-.77 1.71-1.71 1.71m0-2.28a.57.57 0 1 0 0 1.14.57.57 0 0 0 0-1.14" />
    </svg>
  );
}

/** The draggable help panel (`import-details.php:1651-1763`, `import-details.js:1285-1361`). */
export function TroubleshootPanel({
  open,
  section,
  opened = 0,
  onClose,
  pos = null,
  onPos,
}: {
  open: boolean;
  section: string | null;
  /** Counts opens: each one scrolls to its section again, as the design. */
  opened?: number;
  onClose: () => void;
  /** Kept by the page, so the panel opens where it was left (the design's `style.top`). */
  pos?: { top: number; left: number } | null;
  onPos?: (p: { top: number; left: number }) => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const drag = useRef<{ sx: number; sy: number; ox: number; oy: number } | null>(null);
  const [highlight, setHighlight] = useState<string | null>(null);
  const [dragging, setDragging] = useState(false);

  // First open: bottom-right of the window (`import-details.js:1297-1303`).
  useLayoutEffect(() => {
    if (!open || pos || !ref.current) return;
    const el = ref.current;
    onPos?.({
      top: Math.max(70, window.innerHeight - el.offsetHeight - 30),
      left: Math.max(20, window.innerWidth - el.offsetWidth - 30),
    });
  }, [open, pos, onPos]);

  useEffect(() => {
    if (!open || !section) return;
    const el = ref.current?.querySelector<HTMLElement>(`#${section}`);
    el?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    setHighlight(section);
    const t = setTimeout(() => setHighlight(null), 2000);
    return () => clearTimeout(t);
  }, [open, section, opened]);

  if (!open) return null;
  return (
    <div
      ref={ref}
      className={cn('di-troubleshoot-modal is-open', dragging && 'is-drag')}
      id="modalTroubleshootErrors"
      role="dialog"
      aria-labelledby="tsModalTitle"
      style={pos ? { top: pos.top, left: pos.left, right: 'auto', bottom: 'auto' } : undefined}
    >
      <div className="di-ts-head">
        <div className="di-ts-head__left">
          <button type="button" className="di-ts-back" aria-label="Back" onClick={onClose}>
            <CrmIcon name="chevron-left" className="iconSize-14" />
            <span>Back</span>
          </button>
          <a
            href="https://knowledge.hubspot.com/crm-setup/troubleshoot-import-errors"
            target="_blank"
            rel="noopener noreferrer"
            className="di-ts-newtab"
          >
            <span>Open in new tab</span>
            <CrmIcon name="external" className="iconSize-14" />
          </a>
        </div>
        <div
          className="di-ts-head__grip"
          title="Drag to move panel"
          aria-label="Drag to move panel"
          onPointerDown={(e) => {
            if (window.innerWidth < 640 || !ref.current) return;
            const r = ref.current.getBoundingClientRect();
            drag.current = { sx: e.clientX, sy: e.clientY, ox: r.left, oy: r.top };
            e.currentTarget.setPointerCapture(e.pointerId);
            setDragging(true);
          }}
          onPointerMove={(e) => {
            const d = drag.current;
            const el = ref.current;
            if (!d || !el) return;
            onPos?.({
              left: Math.min(
                window.innerWidth - el.offsetWidth - 12,
                Math.max(12, d.ox + e.clientX - d.sx),
              ),
              top: Math.min(window.innerHeight - 80, Math.max(12, d.oy + e.clientY - d.sy)),
            });
          }}
          onPointerUp={() => {
            drag.current = null;
            setDragging(false);
          }}
          onPointerCancel={() => {
            drag.current = null;
            setDragging(false);
          }}
        >
          <svg className="iconSize-14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
            <circle cx="9" cy="6" r="1.5" />
            <circle cx="15" cy="6" r="1.5" />
            <circle cx="9" cy="12" r="1.5" />
            <circle cx="15" cy="12" r="1.5" />
            <circle cx="9" cy="18" r="1.5" />
            <circle cx="15" cy="18" r="1.5" />
          </svg>
        </div>
        <div className="di-ts-head__right">
          <button type="button" className="di-ts-close" aria-label="Close modal" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </div>
      </div>

      <div className="di-ts-body">
        <h2 className="di-ts-title" id="tsModalTitle">
          Review and troubleshoot record import errors
        </h2>
        <p className="di-ts-sub">Available with any CRM subscription</p>
        <p className="di-ts-intro">
          When importing records or activities into your CRM, you may encounter errors. Below, learn
          how to resolve errors detected during an import, download an error file, or view error
          details to correct issues in your import file.
        </p>
        <div className="di-ts-video-card">
          <div className="di-ts-video-thumb">
            <svg
              className="di-ts-play-icon"
              viewBox="0 0 24 24"
              fill="currentColor"
              aria-hidden="true"
            >
              <polygon points="5 3 19 12 5 21 5 3" />
            </svg>
          </div>
          <div className="di-ts-video-info">
            <span className="di-ts-video-tag">CRM Academy Video</span>
            <h3 className="di-ts-video-name">How to Review &amp; Troubleshoot Import Errors</h3>
            <span className="di-ts-video-time">4 min video</span>
          </div>
        </div>
        {TROUBLESHOOT_SECTIONS.map((s) => (
          <div
            key={s.id}
            className={cn('di-ts-section', highlight === s.id && 'is-highlighted')}
            id={s.id}
          >
            <h3 className="di-ts-sec-title">{s.title}</h3>
            <div className="di-ts-block">
              <h4 className="di-ts-block-lbl">What the error means</h4>
              <p>{TS_TEXT[s.id]![0]}</p>
            </div>
            <div className="di-ts-block">
              <h4 className="di-ts-block-lbl">How to resolve the error</h4>
              <p>{TS_TEXT[s.id]![1]}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/** The panel's help text (`import-details.php:1698-1761`). */
const TS_TEXT: Record<string, [React.ReactNode, React.ReactNode]> = {
  'ts-sec-invalid-domain': [
    <>
      The import file does not contain a valid domain name or URL syntax for the affected company or
      contact property (e.g. <code>example.com</code>). Common causes include trailing paths,
      whitespace, missing extensions, or formatting prefixes.
    </>,
    <>
      Update your import file with the correct domain format and re-import. Ensure no{' '}
      <code>http://</code>, <code>https://</code>, or subpage routes are included in domain fields.
    </>,
  ],
  'ts-sec-invalid-alt-id': [
    'The alternate identifier specified in the file does not match an existing unique property or format requirement in your CRM database.',
    'Confirm the unique property exists and matches values in CRM before running the import.',
  ],
  'ts-sec-assoc-id': [
    'CRM could not find a matching parent or child record using the provided association column (Record ID, domain, or email).',
    'Check that the referenced associated records are imported or present in CRM first, then rerun associations.',
  ],
  'ts-sec-assoc-failed': [
    'The system encountered a conflict or permission restriction when mapping relationship links between records.',
    'Verify that your user role has permission to create associations across the selected object types.',
  ],
  'ts-sec-parse-row': [
    'The import row contains malformed characters, unclosed quotation marks, or an incorrect column delimiter.',
    'Re-export your CSV file encoded as UTF-8 without special non-printable control characters.',
  ],
  'ts-sec-invalid-value': [
    'A value in the row does not fit the property its column is mapped to, for example an email address without an @, text in a number property, or an option a dropdown property does not have. The error names the property first (Email: must be an email).',
    'Correct the value in your file, or map the column to a property of the right type, then import the corrected rows again. The error file has only the rows that failed.',
  ],
  'ts-sec-other': [
    'The row could not be imported for the reason shown beside it, which is not one of the common errors above.',
    'Find the row by its number in the rows with errors, correct it in your file and import it again. The error file has only the rows that failed.',
  ],
};
