'use client';

/**
 * Advanced imports (DI-2d), the 12 Nov design's `advance-imports.php` on the real import API:
 * Step 1 chooses the object, Step 2 uploads the file for it (`POST /imports/upload`), Step 3 maps
 * its columns with Quick import's table and drawers, and Finish saves the mapping
 * (`PATCH /imports/:id/mapping`) and starts the import (`POST /imports/:id/start`). The page has
 * no app shell (the design's `$layout = 'import'`). B5: Contacts and Companies ticked together
 * upload a contact file whose company columns fill each row's company (api.internal-crm #223).
 * B6: Deals ticked with Contacts or Companies fill each row's deal (api.internal-crm #245).
 * B7: custom objects ticked with any other object fill each row's record (api.internal-crm #247);
 * every extra object has its own mode, properties, Mapping Guide and Create property.
 */
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import {
  discardDraftImport,
  getImportRun,
  saveImportMapping,
  startImport,
  uploadImportFile,
} from '@/features/imports/api.client';
import { standardFields } from '@/features/imports/fields';
import { importableFile } from '@/features/imports/spreadsheet';
import type { ImportObjectType, ImportPreview, ImportRun } from '@/features/imports/types';
import { useDraftImport } from '@/features/imports/ui/useDraftImport';
import { listPropertyUsage, type PropertyUsage } from '@/features/data-model/api.client';
import { listObjectDefinitions } from '@/features/objects/api.client';
import type { ObjectDefinition } from '@/features/objects/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  advancedFileProblem,
  advancedInitialColumns,
  chipTarget,
  changeImportAs,
  drawerObjectFor,
  extraObjects,
  tickChange,
  guideRows,
  importAsOptions,
  mainObject,
  requiredCreateFields,
  propertiesFor,
  withExtraColumns,
  pastedFileName,
  advancedNextDisabled,
  canFinish,
  duplicatesFor,
  EXAMPLE_FILE_NAME,
  exampleCsv,
  exampleHeaders,
  markerColumns,
  multiObjectExampleCsv,
  multiObjectExampleName,
  templateAdvancedColumns,
  guideFor,
  importChoices,
  LIVE_TEXT,
  MULTI_OBJECT_SOON,
  loadUsage,
  nextAriaLabel,
  scanSummary,
  usageCounts,
  toggleObjects,
  withCreateList,
  type AdvancedStep,
  type ImportChoice,
  type ImportMode,
} from '../advancedImport';
import { useColumnValues, useImportOwners } from './useImportChecks';
import {
  columnsToCheck,
  duplicateMappingProblem,
  mappingRows,
  noDataRowsProblem,
  pastedCsv,
  scannedRows,
  quickMappingBody,
  quickProperties,
  nameAfterFile,
  withNameAndConsent,
  withNumberFormat,
  ROWS_CHECK_BYTES,
  statusCounts,
  visibleRows,
  withColumnEdits,
  withoutColumnEdits,
  type QuickColumn,
  type QuickEdits,
  type StatusFilter,
} from '../quickImport';
import {
  AdvancedFooter,
  AdvancedTopbar,
  DetailsPanel,
  MapPanel,
  TypePanel,
  UploadPanel,
} from './advancedImportParts';
import { CreatePropertyBody, Drawer, EditValuesBody, FixErrorsBody } from './QuickImportDrawers';
import { QuickImportMapping } from './QuickImportMapping';
import { NO_FIELDS, useFieldData, useFieldDataFor } from './QuickImportView';
import { canEditPropertySettings } from '@/features/permission-sets/property-settings';

/**
 * Cancel leaves the wizard for Import to CRM, as Quick import's Cancel (QA #422; the design reloads
 * the page, `advance-imports.js:48-50`, which only started again). Its upload is deleted.
 */
const EXIT_HREF = '/data-integration/import';
/** After Finish: Data integration, whose history lists the import (`.js:395`). */
const DONE_HREF = '/data-integration';

/** File errors from the browser (Excel conversion) carry their own text; API errors theirs. */
const fileErrorText = (err: unknown) =>
  err instanceof Error && !('status' in err) ? err.message : errorText(err);

interface Uploaded {
  chosen: string;
  sent: File;
  preview: ImportPreview;
  objectType: ImportObjectType;
}

type DrawerState = { kind: 'edit' | 'fix' | 'create'; column: string } | null;
/** `mode:<object>`: an extra object's "Choose how to import" menu (B5-B7). */
type Menu = 'mode' | `mode:${string}` | 'lang' | 'number' | null;

/**
 * A menu under (or, without room, over) its trigger, fixed so it escapes clipped panels; the
 * design's sums (`.js:135-146`, `:425-438`, `:485-497`).
 */
function menuStyle(trigger: HTMLElement, room: number, max: number): CSSProperties {
  const rect = trigger.getBoundingClientRect();
  const below = window.innerHeight - rect.bottom;
  const above = rect.top;
  const openAbove = below < room && above > below;
  return {
    position: 'fixed',
    left: `${rect.left}px`,
    width: `${rect.width}px`,
    top: openAbove ? 'auto' : `${rect.bottom + 4}px`,
    bottom: openAbove ? `${window.innerHeight - rect.top + 4}px` : 'auto',
    maxHeight: `${Math.max(120, Math.min(max, (openAbove ? above : below) - 12))}px`,
  };
}

function download(name: string, text: string) {
  const url = URL.createObjectURL(new Blob([text], { type: 'text/csv;charset=utf-8;' }));
  const a = document.createElement('a');
  a.href = url;
  a.download = name;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

export function AdvancedImportView() {
  const router = useRouter();
  const toast = useToast();
  const soon = (label: string) => toast(`${label} is coming soon`);
  const canCreateProperty = canEditPropertySettings(useCurrentUser());
  // QA #415: the upload is a draft import until Finish starts it; leaving deletes it.
  const draft = useDraftImport();

  const [step, setStepState] = useState<AdvancedStep>(1);
  const [live, setLive] = useState(LIVE_TEXT[1]);

  // Step 1: the business's custom objects; if they can't be loaded, the built-in ones stay.
  const [defs, setDefs] = useState<ObjectDefinition[]>([]);
  useEffect(() => {
    let alive = true;
    listObjectDefinitions()
      .then((d) => alive && setDefs(d))
      .catch(() => {});
    return () => {
      alive = false;
    };
  }, []);
  const choices = useMemo(() => importChoices(defs), [defs]);
  // B5-B7: the ticked objects; the file is uploaded as the main one (contacts, else companies,
  // else deals, else the first ticked custom object), and fills the others from the same rows.
  const [selectedKeys, setSelectedKeys] = useState<ImportObjectType[]>([]);
  const selected = mainObject(selectedKeys);
  const extras = extraObjects(selectedKeys);
  const extrasKey = extras.join(',');
  const companies = extras.includes('company');
  const companiesRef = useRef(companies);
  companiesRef.current = companies;
  const extrasRef = useRef(extras);
  extrasRef.current = extras;
  const choice = [...choices.cards, ...choices.pills].find((c) => c.key === selected) ?? null;
  const extraChoices = useMemo(() => {
    const all = [...choices.cards, ...choices.pills];
    return (extrasKey ? extrasKey.split(',') : [])
      .map((k) => all.find((c) => c.key === k))
      .filter((c): c is ImportChoice => Boolean(c));
  }, [choices, extrasKey]);

  // Step 2
  const [mode, setMode] = useState<ImportMode>('create_update');
  // B5-B7: how each extra object is imported (`.js:57-116`, one picker per object).
  const [extraModeOf, setExtraModeOf] = useState<Record<string, ImportMode>>({});
  const modeOf = (key: string) => extraModeOf[key] ?? 'create_update';
  const [menu, setMenu] = useState<Menu>(null);
  const [menuPos, setMenuPos] = useState<CSSProperties | undefined>(undefined);
  const [language, setLanguage] = useState('English');
  const [langQuery, setLangQuery] = useState('');
  const fileInput = useRef<HTMLInputElement>(null);
  const uploadToken = useRef(0);
  const [dragging, setDragging] = useState(false);
  const [pending, setPending] = useState<string | null>(null);
  const [uploaded, setUploaded] = useState<Uploaded | null>(null);
  const [modal, setModal] = useState<'paste' | null>(null);
  const [pasteText, setPasteText] = useState('');

  // Step 3
  const [fields, addProperty] = useFieldData(selected);
  // B5-B7: each extra object's properties, while it is ticked.
  const [extraFields, addExtraProperty] = useFieldDataFor(extras);
  // QA 18 Nov: read at upload time (the template and the HubSpot markers).
  const extraFieldsRef = useRef(extraFields);
  extraFieldsRef.current = extraFields;
  const choicesRef = useRef(choices);
  choicesRef.current = choices;
  // QA 18 Nov (#710): ?template=<import id> (Use as template on a multi-object import): its
  // objects are ticked, and the file uploaded next takes its mapping, column by column.
  const templateRef = useRef<ImportRun | null>(null);
  useEffect(() => {
    const id = new URLSearchParams(window.location.search).get('template');
    if (!id) return;
    let alive = true;
    getImportRun(id).then(
      (run) => {
        if (!alive) return;
        templateRef.current = run;
        setSelectedKeys(run.objectTypes?.length ? [...run.objectTypes] : [run.objectType]);
        setLive(
          `Using ${run.name || run.fileName} as the import template. Upload a file with the same columns.`,
        );
      },
      (err) => alive && toast(errorText(err), 'danger'),
    );
    return () => {
      alive = false;
    };
    // Once, when the page opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const fieldsOf = (key: string) => extraFields[key] ?? NO_FIELDS;
  // Step 4's "used in" counts (B1): null until loaded, and after a 403 or a failed request.
  const [usageData, setUsageData] = useState<PropertyUsage[] | null>(null);
  useEffect(() => {
    setUsageData(null);
    if (!selected) return;
    let alive = true;
    void loadUsage(listPropertyUsage, selected).then((u) => {
      if (alive) setUsageData(u);
    });
    return () => {
      alive = false;
    };
  }, [selected]);
  const [columns, setColumns] = useState<QuickColumn[]>([]);
  const [edits, setEdits] = useState<QuickEdits>({});
  const [filter, setFilter] = useState<StatusFilter>('all');
  const [search, setSearch] = useState('');
  const [openMenu, setOpenMenu] = useState<string | null>(null);
  const [drawer, setDrawer] = useState<DrawerState>(null);
  const drawerRef = useRef<DrawerState>(null);
  drawerRef.current = drawer;
  const [guideOpen, setGuideOpen] = useState(false);
  const [extraGuideOpen, setExtraGuideOpen] = useState<Record<string, boolean>>({});
  const [highlight, setHighlight] = useState<string | null>(null);

  // Step 4. QA #417: the consent starts unticked and Finish waits for it, as Quick import.
  const [consent, setConsent] = useState(false);
  // The design's segment box starts ticked (`advance-imports.php:321`).
  const [createList, setCreateList] = useState(true);
  const [numberFormat, setNumberFormat] = useState('United States');
  // B3: sent only once picked; the shown default alone leaves the numbers read as before.
  const [pickedFormat, setPickedFormat] = useState<string | null>(null);
  const [numberQuery, setNumberQuery] = useState('');
  const [finishing, setFinishing] = useState(false);
  const finishingRef = useRef(false);

  const objectType = selected ?? 'contact';
  // TK10: tasks are only created, and make no list.
  const taskImport = objectType === 'task';
  useEffect(() => {
    if (!taskImport) return;
    setMode('create_only');
    setCreateList(false);
  }, [taskImport]);
  const objectTypeRef = useRef(objectType);
  objectTypeRef.current = objectType;
  const plural = choice?.label ?? 'Contacts';
  const singular = choice?.singular ?? 'Contact';
  // 19 Nov 2026: owner values checked, and errors counted over the whole file.
  const owners = useImportOwners();
  const properties = useMemo(
    () =>
      propertiesFor(
        quickProperties(
          { standard: standardFields(objectType), ...fields, ...(owners && { owners }) },
          { objectType, singular: singular.toLowerCase(), plural: plural.toLowerCase() },
        ),
        companies,
      ),
    [fields, objectType, singular, plural, companies, owners],
  );
  // B5-B7: the properties each extra object's columns choose from.
  const extraProperties = useMemo(
    () =>
      Object.fromEntries(
        extraChoices.map((c) => [
          c.key,
          quickProperties(
            {
              standard: standardFields(c.key),
              ...(extraFields[c.key] ?? NO_FIELDS),
              ...(owners && { owners }),
            },
            {
              objectType: c.key,
              singular: c.singular.toLowerCase(),
              plural: c.label.toLowerCase(),
            },
          ),
        ]),
      ),
    [extraChoices, extraFields, owners],
  );
  const extraSingulars = Object.fromEntries(extraChoices.map((c) => [c.key, c.singular]));
  const previewRows = useMemo(() => uploaded?.preview.previewRows ?? [], [uploaded]);
  const fileValues = useColumnValues(
    uploaded?.preview.id ?? null,
    columnsToCheck(columns, properties, objectType, extraProperties),
  );
  const rows = useMemo(
    () =>
      mappingRows(columns, previewRows, properties, edits, objectType, extraProperties, fileValues),
    [columns, previewRows, properties, edits, objectType, extraProperties, fileValues],
  );
  const counts = statusCounts(rows);
  const visible = visibleRows(rows, filter, search);
  // IMF1: each object's required custom properties are a row of its create card.
  const guide = guideFor(
    objectType,
    plural,
    singular,
    guideRows(rows, 'contact'),
    requiredCreateFields(fields.custom),
  );
  const extraGuides = extraChoices.map((c) => ({
    choice: c,
    guide: guideFor(
      c.key,
      c.label,
      c.singular,
      guideRows(rows, c.key),
      requiredCreateFields(fieldsOf(c.key).custom),
    ),
  }));
  const scan = scanSummary(
    rows,
    scannedRows(rows, fileValues, previewRows.length, uploaded?.preview.rowCount ?? 0),
  );
  const usage = usageCounts(usageData, rows);
  const drawerRow = drawer ? (rows.find((r) => r.column === drawer.column) ?? null) : null;
  // B5-B7: Create property from an extra object's column makes that object's property.
  const drawerObject = drawerObjectFor(drawerRow?.importAs, extras);
  const drawerFields = drawerObject ? fieldsOf(drawerObject) : fields;

  // B2: the import's name; a new file fills it only while it is empty (advance-imports.js:360).
  const [importName, setImportName] = useState('');
  const nextDisabled =
    step === 4
      ? !canFinish({ consent, name: importName, finishing })
      : step === 3
        ? duplicateMappingProblem(rows) !== null
        : advancedNextDisabled(step, {
            selected,
            uploaded: !!uploaded,
            uploading: pending !== null,
          });

  const setStep = (next: AdvancedStep) => {
    setStepState(next);
    setMenu(null);
    setOpenMenu(null);
    setLive(LIVE_TEXT[next]);
  };

  const clearUpload = () => {
    uploadToken.current += 1;
    setPending(null);
    setUploaded(null);
    draft.discard();
    setColumns([]);
    setEdits({});
    if (fileInput.current) fileInput.current.value = '';
  };

  const toggle = (key: string, checked: boolean) => {
    const res = toggleObjects(selectedKeys, key, checked);
    if (res.soon) soon(MULTI_OBJECT_SOON);
    const change = tickChange(selectedKeys, res.selected);
    if (change.clearUpload) {
      // An upload is for one object: a file sent for another must be sent again.
      clearUpload();
      setMode('create_update');
    } else if (change.resetColumns && uploaded) {
      // B5/B6: Companies or Deals ticked or unticked over the same file: its columns start again.
      setColumns(
        advancedInitialColumns(uploaded.preview, extraObjects(res.selected).includes('company')),
      );
      setEdits({});
    }
    // An extra object ticked or unticked starts its own mode again.
    setExtraModeOf((m) =>
      Object.fromEntries(Object.entries(m).filter(([k]) => !change.resetMode[k])),
    );
    setSelectedKeys(res.selected);
  };

  const accept = async (file: File | undefined) => {
    if (!file || !selected) return;
    const problem = advancedFileProblem(file);
    if (problem) {
      setLive(problem);
      toast(problem, 'danger');
      return;
    }
    const token = ++uploadToken.current;
    const forType = selected;
    setUploaded(null);
    draft.discard();
    setPending(file.name);
    try {
      const sent = await importableFile(file);
      // QA #416: a header with no rows under it isn't sent.
      const empty = noDataRowsProblem(await sent.slice(0, ROWS_CHECK_BYTES).text());
      if (empty) {
        if (token === uploadToken.current) {
          setLive(empty);
          toast(empty, 'danger');
        }
        return;
      }
      const preview = await uploadImportFile(sent, forType);
      if (token !== uploadToken.current) {
        // Another file or object was picked while it uploaded.
        discardDraftImport(preview.id);
        return;
      }
      draft.track(preview.id);
      setUploaded({ chosen: file.name, sent, preview, objectType: forType });
      setImportName((n) => nameAfterFile(n, file.name));
      let cols = advancedInitialColumns(preview, companiesRef.current);
      // HubSpot's template headers ("Event Name <events event_name>") fill the ticked objects.
      cols = markerColumns(
        cols,
        extrasRef.current.map((key) => ({
          key,
          plural:
            choicesRef.current.pills.concat(choicesRef.current.cards).find((c) => c.key === key)
              ?.label ?? key,
          fields: new Set((extraFieldsRef.current[key]?.custom ?? []).map((f) => f.name)),
        })),
      );
      if (templateRef.current)
        cols = templateAdvancedColumns(templateRef.current.mapping, cols, forType);
      setColumns(cols);
      setEdits({});
      setFilter('all');
      setSearch('');
      setLive(`File uploaded: ${sent.name}. Select Next to continue to Map.`);
    } catch (err) {
      if (token === uploadToken.current) toast(fileErrorText(err), 'danger');
    } finally {
      if (token === uploadToken.current) setPending(null);
    }
  };

  const finish = async () => {
    const duplicates = duplicatesFor(mode);
    // B5-B7: each extra object's own mode, in the page's order.
    const extraModes = Object.fromEntries(extras.map((k) => [k, modeOf(k)]));
    if (!uploaded || finishingRef.current) return;
    if (!canFinish({ consent, name: importName, finishing })) return;
    finishingRef.current = true;
    setFinishing(true);
    try {
      const id = uploaded.preview.id;
      await saveImportMapping(
        id,
        withNumberFormat(
          withCreateList(
            withNameAndConsent(
              withExtraColumns(
                quickMappingBody(columns, edits, duplicates),
                columns,
                edits,
                extraModes,
              ),
              importName,
            ),
            createList,
          ),
          pickedFormat,
        ),
      );
      await startImport(id);
      draft.keep();
      router.push(DONE_HREF);
    } catch (err) {
      toast(errorText(err), 'danger');
      finishingRef.current = false;
      setFinishing(false);
    }
  };

  const next = () => {
    if (nextDisabled) return;
    if (step === 4) void finish();
    else setStep((step + 1) as AdvancedStep);
  };

  const openFixed = (which: Exclude<Menu, null>, open: boolean, trigger: HTMLElement) => {
    if (!open) {
      setMenu(null);
      return;
    }
    const pick = which.startsWith('mode');
    const room = pick ? 190 : which === 'lang' ? 220 : 240;
    const max = pick ? 220 : 300;
    setMenuPos(menuStyle(trigger, room, max));
    setMenu(which);
  };

  /** A guide chip: to the row mapped to it, else opens the first unmapped row's menu (`.js:540-558`). */
  const onChip = (field: string, object = 'contact') => {
    // The row may be hidden by the search or the status filter: show every row first.
    setSearch('');
    setFilter('all');
    const target = chipTarget(guideRows(rows, object), field);
    // After the re-render (the row is drawn) and after this click's outside-click close.
    window.requestAnimationFrame(() => {
      if (!target) {
        document
          .getElementById('iqMappingTable')
          ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        return;
      }
      document
        .querySelector(`tr[data-column="${CSS.escape(target.column)}"]`)
        ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      setHighlight(target.column);
      window.setTimeout(() => setHighlight((h) => (h === target.column ? null : h)), 1600);
      if (target.openMenu) setOpenMenu(`property:${target.column}`);
    });
  };

  const anyOpen = modal !== null || drawer !== null;

  // Outside clicks close the open menus; Escape closes them and any dialog.
  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      const t = e.target as Element | null;
      if (
        !t?.closest?.('.upload-mode-picker') &&
        !t?.closest?.('.upload-language-picker') &&
        !t?.closest?.('.details-number-picker')
      ) {
        setMenu(null);
      }
      if (!t?.closest?.('.custom-select-wrapper')) setOpenMenu(null);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      setMenu(null);
      setOpenMenu(null);
      setModal(null);
      setDrawer(null);
    };
    const onResize = () => setMenu(null);
    document.addEventListener('click', onClick);
    document.addEventListener('keydown', onKey);
    window.addEventListener('resize', onResize);
    return () => {
      document.removeEventListener('click', onClick);
      document.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  // A dialog stops the page scrolling behind it.
  useEffect(() => {
    if (!anyOpen) return;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = '';
    };
  }, [anyOpen]);

  // "Tip: press Enter/Return to continue" (`.js:399-404`): not on a control, nor under a dialog.
  const enter = useRef<() => boolean>(() => false);
  enter.current = () => {
    if (anyOpen || nextDisabled) return false;
    next();
    return true;
  };
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Enter') return;
      const t = e.target as Element | null;
      if (t?.closest?.('a, button, input, select, textarea')) return;
      if (enter.current()) e.preventDefault();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  const closeDrawer = () => setDrawer(null);
  const menus = { openMenu, setOpenMenu };

  return (
    // The design's body is `.layout-import` and the page loads Quick import's stylesheet, whose
    // generic rules are scoped to `.iq-page`; `adv-page` scopes this page's own stylesheet. The
    // root inherits Lexend (as Quick import). No `data-active-step` (the design's JS sets it,
    // `.js:307`): its own rules on it change nothing here (React hides the panels), and Repeat a
    // past import's stylesheet hides the stepper and Next on `.import-page[data-active-step="1"]`.
    <div className="layout-import iq-page adv-page" style={{ fontFamily: 'inherit' }}>
      <div className="import-page">
        <div className="import-shell" aria-label="Import files wizard">
          <AdvancedTopbar step={step} onStep={(s) => s <= step && setStep(s)} />

          <TypePanel
            hidden={step !== 1}
            choices={choices}
            selected={selectedKeys}
            onToggle={toggle}
            onSoon={soon}
          />

          {choice ? (
            <UploadPanel
              hidden={step !== 2}
              choice={choice}
              mode={mode}
              modeOpen={menu === 'mode'}
              modeStyle={menu === 'mode' ? menuPos : undefined}
              onModeOpen={(o, t) => openFixed('mode', o, t)}
              onMode={(m) => {
                setMenu(null);
                setMode(m);
              }}
              pending={pending}
              uploaded={uploaded}
              dragging={dragging}
              onDragging={setDragging}
              onFile={(f) => void accept(f)}
              onRemoveFile={clearUpload}
              onPaste={() => setModal('paste')}
              onDownloadExample={() => {
                // QA 18 Nov: several objects get HubSpot's multi-object import template.
                if (extras.length) {
                  const all = [...choices.cards, ...choices.pills];
                  const objects = [objectType, ...extras].map((key) => {
                    const c = all.find((x) => x.key === key);
                    return {
                      key,
                      singular: c?.singular ?? key,
                      plural: c?.label ?? key,
                      displayProperty: defs.find((d) => d.key === key)?.displayProperty,
                    };
                  });
                  download(multiObjectExampleName(objects), multiObjectExampleCsv(objects));
                  setLive('Example CSV downloaded.');
                  return;
                }
                const labels = fields.custom.filter((p) => !p.archived).map((p) => p.label);
                download(EXAMPLE_FILE_NAME, exampleCsv(exampleHeaders(objectType, labels)));
                setLive('Example CSV downloaded.');
              }}
              onSoon={soon}
              language={language}
              langOpen={menu === 'lang'}
              langQuery={langQuery}
              langStyle={menu === 'lang' ? menuPos : undefined}
              onLangOpen={(o, t) => {
                openFixed('lang', o, t);
                if (o) {
                  window.requestAnimationFrame(() =>
                    document.getElementById('language-search')?.focus(),
                  );
                }
              }}
              onLangQuery={setLangQuery}
              onLanguage={(l) => {
                setLanguage(l);
                setMenu(null);
              }}
              fileInputRef={fileInput}
              extras={extraChoices.map((c) => ({
                choice: c,
                mode: modeOf(c.key),
                open: menu === `mode:${c.key}`,
                style: menu === `mode:${c.key}` ? menuPos : undefined,
                onOpen: (o: boolean, t: HTMLElement) => openFixed(`mode:${c.key}`, o, t),
                onMode: (m: ImportMode) => {
                  setMenu(null);
                  setExtraModeOf((x) => ({ ...x, [c.key]: m }));
                },
              }))}
            />
          ) : null}

          {choice ? (
            <MapPanel
              hidden={step !== 3}
              choice={choice}
              guide={guide}
              guideOpen={guideOpen}
              onGuideOpen={setGuideOpen}
              onChip={onChip}
              onLearnMore={() => {
                setGuideOpen(true);
                document
                  .getElementById('iqMappingGuide')
                  ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
              }}
              onSoon={soon}
              scan={scan}
              extraGuides={extraGuides.map((g) => ({
                ...g,
                open: extraGuideOpen[g.choice.key] ?? false,
                onOpen: (open: boolean) =>
                  setExtraGuideOpen((x) => ({ ...x, [g.choice.key]: open })),
                onChip: (field: string) => onChip(field, g.choice.key),
              }))}
            >
              <QuickImportMapping
                rows={rows}
                visible={visible}
                counts={counts}
                properties={properties}
                filter={filter}
                onFilter={setFilter}
                search={search}
                onSearch={setSearch}
                onReset={() => {
                  setFilter('all');
                  setSearch('');
                }}
                {...menus}
                onImportAs={(column, importAs) => {
                  // B5/B6: a property of another object isn't kept (the same field on both is).
                  const list = extraProperties[importAs] ?? properties;
                  const next = changeImportAs(columns, column, importAs, list, extras.length > 0);
                  setColumns(next.columns);
                  if (next.cleared) setEdits((e) => withoutColumnEdits(e, column));
                }}
                onProperty={(column, field) => {
                  setColumns((cs) => cs.map((c) => (c.column === column ? { ...c, field } : c)));
                  setEdits((e) => withoutColumnEdits(e, column));
                }}
                onEditValues={(column) => setDrawer({ kind: 'edit', column })}
                onFixErrors={(column) => setDrawer({ kind: 'fix', column })}
                onCreateProperty={
                  canCreateProperty ? (column) => setDrawer({ kind: 'create', column }) : null
                }
                objectName={{ singular, lower: singular.toLowerCase() }}
                highlight={highlight}
                importAsOptions={
                  extras.length ? importAsOptions(singular, extras, extraSingulars) : undefined
                }
                extraProperties={extras.length ? extraProperties : undefined}
              />
            </MapPanel>
          ) : null}

          <DetailsPanel
            hidden={step !== 4}
            name={importName}
            onName={setImportName}
            createList={createList}
            onCreateList={setCreateList}
            noList={taskImport}
            consent={consent}
            onConsent={setConsent}
            numberFormat={numberFormat}
            numberOpen={menu === 'number'}
            numberQuery={numberQuery}
            numberStyle={menu === 'number' ? menuPos : undefined}
            onNumberOpen={(o, t) => {
              openFixed('number', o, t);
              if (o) {
                window.requestAnimationFrame(() =>
                  document.getElementById('number-format-search')?.focus(),
                );
              }
            }}
            onNumberQuery={setNumberQuery}
            onNumberFormat={(n) => {
              setNumberFormat(n);
              setPickedFormat(n);
              setMenu(null);
            }}
            onEnrich={soon}
            usage={usage}
            onSoon={soon}
          />

          <AdvancedFooter
            step={step}
            nextDisabled={nextDisabled}
            nextAria={step === 1 ? nextAriaLabel(selectedKeys.length) : undefined}
            finishing={finishing}
            onBack={() => step > 1 && setStep((step - 1) as AdvancedStep)}
            onCancel={() => router.push(EXIT_HREF)}
            onNext={next}
          />
          <div className="import-live" aria-live="polite">
            {live}
          </div>

          {/* DRAWERS (Quick import's, `.php:375-758`) */}
          <Drawer
            id="iqDrawerEditValues"
            open={drawer?.kind === 'edit' && !!drawerRow}
            onClose={closeDrawer}
          >
            {drawer?.kind === 'edit' && drawerRow ? (
              <EditValuesBody
                key={drawerRow.column}
                row={drawerRow}
                rows={previewRows}
                edits={edits}
                onSoon={soon}
                onClose={closeDrawer}
                onDone={(n) => {
                  setEdits((e) => withColumnEdits(e, drawerRow.column, n));
                  closeDrawer();
                }}
                {...menus}
              />
            ) : null}
          </Drawer>
          <Drawer
            id="iqDrawerFixErrors"
            open={drawer?.kind === 'fix' && !!drawerRow}
            onClose={closeDrawer}
          >
            {drawer?.kind === 'fix' && drawerRow ? (
              <FixErrorsBody
                key={drawerRow.column}
                row={drawerRow}
                edits={edits}
                onSoon={soon}
                onClose={closeDrawer}
                onDone={(n) => {
                  setEdits((e) => withColumnEdits(e, drawerRow.column, n));
                  closeDrawer();
                }}
                {...menus}
              />
            ) : null}
          </Drawer>
          <Drawer
            id="iqDrawerCreateProperty"
            open={drawer?.kind === 'create' && canCreateProperty}
            onClose={closeDrawer}
          >
            {drawer?.kind === 'create' && canCreateProperty ? (
              <CreatePropertyBody
                key={drawer.column}
                column={drawer.column}
                rows={previewRows}
                uniqueUsed={drawerFields.custom.filter((p) => p.unique && !p.archived).length}
                onSoon={soon}
                onError={(m) => toast(m, 'danger')}
                onClose={closeDrawer}
                taken={drawerFields.custom.map((p) => p.name)}
                objectType={drawerObject ?? objectType}
                onCreated={(saved) => {
                  // B5-B7: an extra object's column's new property is that object's.
                  const forExtra = extrasRef.current.includes(saved.objectType);
                  // Saved for an object no longer being imported (changed while it saved).
                  if (!forExtra && saved.objectType !== objectTypeRef.current) return;
                  if (forExtra) addExtraProperty(saved.objectType, saved);
                  else addProperty(saved);
                  const column = drawer.column;
                  if (drawerRef.current?.kind !== 'create' || drawerRef.current.column !== column)
                    return;
                  setColumns((cs) =>
                    cs.map((c) =>
                      c.column === column
                        ? {
                            ...c,
                            importAs: forExtra ? saved.objectType : 'contact',
                            field: `custom.${saved.name}`,
                          }
                        : c,
                    ),
                  );
                  setEdits((e) => withoutColumnEdits(e, column));
                  closeDrawer();
                }}
                {...menus}
              />
            ) : null}
          </Drawer>

          {/* Paste Spreadsheet Data (`.php:788-808`) */}
          <div
            className={cn('modal-backdrop', modal === 'paste' && 'is-open')}
            id="iqPasteModal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="pasteModalTitle"
            onClick={(e) => {
              if (e.target === e.currentTarget) setModal(null);
            }}
          >
            <div className="modal modal--lg">
              <div className="modal__header">
                <h3 className="modal__title" id="pasteModalTitle">
                  Paste Spreadsheet Data
                </h3>
                <button
                  type="button"
                  className="modal__close"
                  data-close-modal
                  aria-label="Close modal"
                  onClick={() => setModal(null)}
                >
                  <CrmIcon name="x" className="iconSize-16" />
                </button>
              </div>
              <div className="modal__body">
                <p className="crm-fs-7 crm-text-muted crm-mb-3">
                  Copy cells directly from Google Sheets or Excel and paste them here (tab or comma
                  separated with headers):
                </p>
                <textarea
                  id="iqPasteTextarea"
                  className="input iq-paste-textarea"
                  placeholder={
                    'First\tLast\tEmail\tCompany\nAshley\tMackel\tashleymackel@gmail.com\tMcDonalds'
                  }
                  value={pasteText}
                  onChange={(e) => setPasteText(e.target.value)}
                />
              </div>
              <div className="modal__footer">
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  data-close-modal
                  onClick={() => setModal(null)}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--primary"
                  id="iqPasteApplyBtn"
                  onClick={() => {
                    const text = pasteText.trim();
                    if (!text) {
                      toast('Please paste spreadsheet rows or CSV data.', 'danger');
                      return;
                    }
                    const csv = pastedCsv(text);
                    // QA #416: the header alone imports nothing; the dialog stays open.
                    const empty = noDataRowsProblem(csv);
                    if (empty) {
                      toast(empty, 'danger');
                      return;
                    }
                    setModal(null);
                    void accept(
                      new File([csv], pastedFileName(choice?.label ?? 'Contacts'), {
                        type: 'text/csv',
                      }),
                    );
                  }}
                >
                  Use this data
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
