'use client';

/**
 * Advanced imports' parts (DI-2d), drawn with the markup and classes of the 12 Nov design's
 * `advance-imports.php`, so its stylesheet applies as written. Each step is its own component, so
 * every state can be rendered in a test; `AdvancedImportView` holds the state.
 */
import type { CSSProperties, ReactNode, RefObject } from 'react';
import { cn } from '@/lib/utils/cn';
import {
  ADVANCED_STEPS,
  fileSummary,
  HEADER_LANGUAGES,
  importModes,
  matchesLanguage,
  missingIdentifierText,
  NUMBER_FORMATS,
  numberFormatHint,
  requirementGood,
  stepCountText,
  stepState,
  uploadHeading,
  type AdvancedStep,
  type GuideCard,
  type ImportChoice,
  type ImportMode,
  type ObjectGuide,
} from '../advancedImport';

/** The design's "opens elsewhere" arrow (`.php:119-120`, `:135`, `:350`). */
function ExternalIcon() {
  return (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="M9 2h5v5M14 2 7 9" />
      <path d="M12 9v3.5A1.5 1.5 0 0 1 10.5 14h-7A1.5 1.5 0 0 1 2 12.5v-7A1.5 1.5 0 0 1 3.5 4H7" />
    </svg>
  );
}

function ChevronIcon() {
  return (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="m4 6 4 4 4-4" />
    </svg>
  );
}

function FileIcon() {
  return (
    <svg className="upload-file-icon" viewBox="0 0 40 40" aria-hidden="true">
      <path d="M9 4h14l10 10v22H9z" />
      <path d="M23 4v11h10" />
    </svg>
  );
}

function SearchIcon() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true">
      <circle cx="8.5" cy="8.5" r="5.5" />
      <path d="m13 13 4 4" />
    </svg>
  );
}

/** A `#` link of the design: stays on the page and says "<label> is coming soon". */
function soonLink(onSoon: (label: string) => void, label: string) {
  return (e: { preventDefault: () => void }) => {
    e.preventDefault();
    onSoon(label);
  };
}

/* ----------------------------------------------------------------- topbar */

/** `.import-topbar` (`.php:53-62`); a click on a done or current step goes back to it (`.js:368`). */
export function AdvancedTopbar({
  step,
  onStep,
}: {
  step: AdvancedStep;
  onStep: (step: AdvancedStep) => void;
}) {
  return (
    <header className="import-topbar">
      <div className="import-brand">Import files</div>
      <nav className="import-stepper" aria-label="Import progress">
        {ADVANCED_STEPS.map((s) => {
          const st = stepState(s.step, step);
          return (
            <div
              key={s.step}
              className={cn(
                'import-step',
                st.current && 'is-current',
                st.complete && 'is-complete',
              )}
              data-step={s.step}
              onClick={() => {
                if (s.step <= step) onStep(s.step);
              }}
            >
              <span className="import-step__dot"></span>
              <span className="import-step__label">{s.label}</span>
            </div>
          );
        })}
      </nav>
      <div className="import-step-count" id="import-step-count">
        {stepCountText(step)}
      </div>
    </header>
  );
}

/* ----------------------------------------------------------------- step 1 */

export function TypePanel({
  hidden,
  choices,
  selected,
  onToggle,
  onSoon,
}: {
  hidden: boolean;
  choices: { cards: ImportChoice[]; pills: ImportChoice[] };
  /** The ticked objects (B5: Contacts with Companies); one key or none as before. */
  selected: readonly string[] | string | null;
  onToggle: (key: string, checked: boolean) => void;
  onSoon: (label: string) => void;
}) {
  const ticked = (key: string) =>
    Array.isArray(selected) ? selected.includes(key) : selected === key;
  return (
    <section
      className="import-content"
      hidden={hidden}
      style={hidden ? { display: 'none' } : undefined}
    >
      <div className="import-intro">
        <h1>What kind of data is in your file?</h1>
        <p>Select one or more of the objects you want to create and associate.</p>
        <p className="import-help">
          Understand how CRM structures your data into objects using the{' '}
          <a
            href="#"
            aria-label="Data model overview tool"
            onClick={soonLink(onSoon, 'Data model overview tool')}
          >
            data model overview tool{' '}
            <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
              <path d="M6 3H3.5A1.5 1.5 0 0 0 2 4.5v8A1.5 1.5 0 0 0 3.5 14h8a1.5 1.5 0 0 0 1.5-1.5V10M8 2h6v6M14 2 7 9" />
            </svg>
          </a>
        </p>
      </div>

      <section className="import-group import-group--frequent" aria-labelledby="frequent-heading">
        <h2 id="frequent-heading">Frequently imported</h2>
        <div className="import-frequent-grid">
          {choices.cards.map((c) => (
            <label key={c.key} className="import-object-card">
              <input
                type="checkbox"
                name="objects"
                value={c.key}
                checked={ticked(c.key)}
                onChange={(e) => onToggle(c.key, e.target.checked)}
              />
              <span className="import-check" aria-hidden="true"></span>
              <span
                className={`import-art import-art--${c.label.toLowerCase()}`}
                aria-hidden="true"
              >
                {/* eslint-disable-next-line @next/next/no-img-element -- the design's static SVG */}
                <img src={c.art} width={90} alt="" />
              </span>
              <strong>{c.label}</strong>
              <span className="import-object-description">{c.description}</span>
            </label>
          ))}
        </div>
      </section>

      <section className="import-group import-group--objects" aria-labelledby="objects-heading">
        <h2 id="objects-heading">Objects</h2>
        <div className="import-object-grid">
          {choices.pills.map((p) => (
            <label key={p.key} className="import-object-pill">
              <input
                type="checkbox"
                name="objects"
                value={p.key}
                checked={ticked(p.key)}
                onChange={(e) => onToggle(p.key, e.target.checked)}
              />
              <span className="pill-icon">
                <svg
                  viewBox="0 0 20 20"
                  aria-hidden="true"
                  focusable="false"
                  dangerouslySetInnerHTML={{ __html: p.icon ?? '' }}
                />
              </span>
              <span>{p.label}</span>
              <span className="import-check" aria-hidden="true"></span>
            </label>
          ))}
        </div>
      </section>
    </section>
  );
}

/* ----------------------------------------------------------------- step 2 */

export interface UploadPanelProps {
  hidden: boolean;
  choice: ImportChoice;
  mode: ImportMode;
  modeOpen: boolean;
  modeStyle: CSSProperties | undefined;
  onModeOpen: (open: boolean, trigger: HTMLElement) => void;
  onMode: (mode: ImportMode) => void;
  /** A file being uploaded (its name), before the API answers. */
  pending: string | null;
  uploaded: { chosen: string; sent: { name: string; size: number } } | null;
  dragging: boolean;
  onDragging: (on: boolean) => void;
  onFile: (file: File | undefined) => void;
  onRemoveFile: () => void;
  onPaste: () => void;
  onDownloadExample: () => void;
  onSoon: (label: string) => void;
  language: string;
  langOpen: boolean;
  langQuery: string;
  langStyle: CSSProperties | undefined;
  onLangOpen: (open: boolean, trigger: HTMLElement) => void;
  onLangQuery: (q: string) => void;
  onLanguage: (lang: string) => void;
  fileInputRef: RefObject<HTMLInputElement | null>;
  /**
   * B5/B6: the objects the file also fills (companies, deals), each with its own mode
   * (`.js:57-116`, one picker per ticked object).
   */
  extras?: Array<{
    choice: ImportChoice;
    mode: ImportMode;
    open: boolean;
    style: CSSProperties | undefined;
    onOpen: (open: boolean, trigger: HTMLElement) => void;
    onMode: (mode: ImportMode) => void;
  }>;
}

/** "Choose how to import <Objects>" (`.js:62-115`): one per ticked object. */
function ModeField({
  choice,
  mode,
  open,
  style,
  onOpen,
  onMode,
}: {
  choice: ImportChoice;
  mode: ImportMode;
  open: boolean;
  style: CSSProperties | undefined;
  onOpen: (open: boolean, trigger: HTMLElement) => void;
  onMode: (mode: ImportMode) => void;
}) {
  const modes = importModes(choice.label, choice.key);
  const current = modes.find((m) => m.value === mode)!;
  return (
    <div className="upload-mode-field">
      <label htmlFor={`import-mode-${choice.key}`}>Choose how to import {choice.label}</label>
      <div className="upload-mode-picker">
        <button
          type="button"
          className="upload-mode-trigger"
          id={`import-mode-${choice.key}`}
          data-object={choice.key}
          data-value={mode}
          aria-haspopup="listbox"
          aria-expanded={open}
          onClick={(e) => onOpen(!open, e.currentTarget)}
        >
          <span className="upload-mode-value">{current.text}</span>
          <ChevronIcon />
        </button>
        <div className="upload-mode-menu" role="listbox" hidden={!open} style={style}>
          {modes.map((m) => (
            <button
              key={m.value}
              type="button"
              className="upload-mode-option"
              role="option"
              aria-selected={m.value === mode}
              data-value={m.value}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                onMode(m.value);
              }}
            >
              {m.text}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

export function UploadPanel(p: UploadPanelProps) {
  // B5/B6: "Contacts, Companies, Deals file" (`.js:118-120`).
  const extras = p.extras ?? [];
  const label = [p.choice, ...extras.map((e) => e.choice)].map((c) => c.label).join(', ');
  const pick = () => p.fileInputRef.current?.click();
  const summary = p.uploaded ? fileSummary(p.uploaded.chosen, p.uploaded.sent) : null;

  return (
    <section
      className="upload-content"
      data-wizard-panel="2"
      hidden={p.hidden}
      style={p.hidden ? { display: 'none' } : undefined}
    >
      <div className="upload-intro">
        <h1>Upload your files</h1>
        <p>
          Before you upload your files below, make sure your file is{' '}
          <a href="#" className="upload-link" onClick={soonLink(p.onSoon, 'Ready to be imported')}>
            ready to be imported <ExternalIcon />
          </a>
        </p>
        <p>
          Learn how CRM knows when your records are{' '}
          <a href="#" className="upload-link" onClick={soonLink(p.onSoon, 'Duplicates')}>
            duplicates <ExternalIcon />
          </a>
          .
        </p>
      </div>
      <div className="upload-form">
        <div className="upload-mode-list" id="upload-mode-list">
          <ModeField
            choice={p.choice}
            mode={p.mode}
            open={p.modeOpen}
            style={p.modeStyle}
            onOpen={p.onModeOpen}
            onMode={p.onMode}
          />
          {extras.map((e) => (
            <ModeField key={e.choice.key} {...e} />
          ))}
        </div>

        <section className="upload-file-section">
          <h2 id="upload-file-heading">{uploadHeading(label)}</h2>
          <div className="upload-resource-links">
            <a
              href="#"
              className="upload-link"
              onClick={soonLink(p.onSoon, 'View import property requirements')}
            >
              View import property requirements
            </a>
            <span>|</span>
            <a
              href="#"
              className="upload-link"
              id="download-example"
              onClick={(e) => {
                e.preventDefault();
                p.onDownloadExample();
              }}
            >
              Download example file
            </a>
          </div>
          <input
            type="file"
            id="import-file-input"
            accept=".csv,.xlsx,.xls"
            hidden
            ref={p.fileInputRef}
            onChange={(e) => {
              const file = e.target.files?.[0];
              e.target.value = '';
              p.onFile(file);
            }}
          />
          <div
            className={cn(
              'upload-dropzone',
              p.dragging && 'is-dragging',
              (summary || p.pending) && 'has-file',
            )}
            id="upload-dropzone"
            tabIndex={0}
            role="button"
            aria-label="Choose a file to upload"
            onClick={(e) => {
              if (!(e.target as Element).closest('button')) pick();
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                e.stopPropagation();
                pick();
              }
            }}
            onDragEnter={(e) => {
              e.preventDefault();
              p.onDragging(true);
            }}
            onDragOver={(e) => {
              e.preventDefault();
              p.onDragging(true);
            }}
            onDragLeave={(e) => {
              e.preventDefault();
              p.onDragging(false);
            }}
            onDrop={(e) => {
              e.preventDefault();
              p.onDragging(false);
              p.onFile(e.dataTransfer.files?.[0]);
            }}
          >
            <FileIcon />
            <div className="upload-drop-copy" id="upload-drop-copy">
              {summary ? (
                <div className="upload-file-summary">
                  <FileIcon />
                  <strong>{summary.title}</strong>
                  <span>{summary.size}</span>
                  <button
                    type="button"
                    className="upload-remove-file"
                    aria-label="Remove uploaded file"
                    onClick={(e) => {
                      e.stopPropagation();
                      p.onRemoveFile();
                    }}
                  >
                    <svg viewBox="0 0 16 16" aria-hidden="true">
                      <path d="m4 4 8 8M12 4l-8 8" />
                    </svg>
                  </button>
                </div>
              ) : p.pending ? (
                <div className="upload-file-summary">
                  <FileIcon />
                  <strong>Uploading &quot;{p.pending}&quot;...</strong>
                </div>
              ) : (
                <>
                  Drag and drop or{' '}
                  <button
                    type="button"
                    className="upload-inline-button"
                    id="choose-file"
                    onClick={(e) => {
                      e.stopPropagation();
                      pick();
                    }}
                  >
                    choose a file
                  </button>{' '}
                  to upload your {label}.
                  <br />
                  All .csv, .xlsx, and .xls file types are supported.
                  <br />
                  You can also{' '}
                  <button
                    type="button"
                    className="upload-inline-button"
                    id="paste-file"
                    onClick={(e) => {
                      e.stopPropagation();
                      p.onPaste();
                    }}
                  >
                    paste directly from your spreadsheet.
                  </button>
                </>
              )}
            </div>
          </div>
        </section>

        <section className="upload-language-section">
          <h2>Select the language of the column headers in your file</h2>
          <p>
            Identifying the language of the column headers in your file allows us to accurately map
            them to existing properties.{' '}
            <a href="#" className="upload-link" onClick={soonLink(p.onSoon, 'Learn more')}>
              Learn more <ExternalIcon />
            </a>
          </p>
          <div className="upload-language-picker">
            <button
              type="button"
              className="upload-language-trigger"
              id="language-trigger"
              aria-expanded={p.langOpen}
              onClick={(e) => p.onLangOpen(!p.langOpen, e.currentTarget)}
            >
              <span id="language-value">{p.language}</span>
              <ChevronIcon />
            </button>
            <div
              className="upload-language-menu"
              id="language-menu"
              hidden={!p.langOpen}
              style={p.langStyle}
            >
              <label className="upload-language-search">
                <SearchIcon />
                <input
                  id="language-search"
                  type="search"
                  placeholder="Search"
                  autoComplete="off"
                  aria-label="Search languages"
                  value={p.langQuery}
                  onChange={(e) => p.onLangQuery(e.target.value)}
                />
              </label>
              <div className="upload-language-options" id="language-options" role="listbox">
                {HEADER_LANGUAGES.filter((l) => matchesLanguage(l, p.langQuery)).map((lang) => (
                  <button
                    key={lang}
                    type="button"
                    className="upload-language-option"
                    role="option"
                    aria-selected={lang === p.language}
                    onClick={() => p.onLanguage(lang)}
                  >
                    <input
                      type="radio"
                      tabIndex={-1}
                      name="header-language"
                      checked={lang === p.language}
                      onChange={() => {}}
                    />
                    <span>{lang}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        </section>
      </div>
    </section>
  );
}

/* ----------------------------------------------------------------- step 3 */

/** The guide object's glyph (`.php:168`, `:183`, `:196`): ▦ for objects the design doesn't draw. */
function guideGlyph(key: string): string {
  if (key === 'contact') return '▣';
  if (key === 'company') return '♧';
  return '▦';
}

function GuideCardView({
  card,
  good,
  verb,
  plural,
  onChip,
}: {
  card: GuideCard;
  good: boolean;
  verb: 'create' | 'update';
  plural: string;
  onChip: (field: string) => void;
}) {
  return (
    <div className="iq-guide-card">
      <h3>
        <span aria-hidden="true">{verb === 'create' ? '✳' : '↗'}</span> Properties required to{' '}
        {verb} {plural}{' '}
        <span className="iq-guide-info" title={card.info}>
          ⓘ
        </span>
      </h3>
      <GuideRequirement
        rule={card.rule}
        chips={card.chips}
        good={card.also ? requirementGood(card.rule, card.chips) : good}
        onChip={onChip}
      />
      {/* IMF1: the object's required custom properties, a second row of the design's kind. */}
      {card.also ? (
        <GuideRequirement
          rule={card.also.rule}
          chips={card.also.chips}
          good={card.also.good}
          onChip={onChip}
        />
      ) : null}
    </div>
  );
}

/** One rule row (`.iq-guide-requirement`, `advance-imports.php:174`). */
function GuideRequirement({
  rule,
  chips,
  good,
  onChip,
}: {
  rule: GuideCard['rule'];
  chips: GuideCard['chips'];
  good: boolean;
  onChip: (field: string) => void;
}) {
  return (
    <div className="iq-guide-requirement">
      <i className={good ? 'is-good' : 'is-warning'}></i>
      <strong>{rule}</strong>
      {chips.map((c) => (
        <button
          key={c.field}
          type="button"
          className={cn('iq-guide-chip', c.good && 'is-good')}
          data-guide-property={c.field}
          onClick={() => onChip(c.field)}
        >
          {c.good ? `✓ ${c.label}` : c.label}
        </button>
      ))}
    </div>
  );
}

/** One object of the Mapping Guide (`.php:166-196`): its toggle, statuses, and the two cards. */
function GuideObject({
  choice,
  guide,
  open,
  onOpen,
  onChip,
}: {
  choice: ImportChoice;
  guide: ObjectGuide;
  open: boolean;
  onOpen: (open: boolean) => void;
  onChip: (field: string) => void;
}) {
  const detailsId = `iqGuide${guide.singular.replace(/[^A-Za-z0-9]/g, '')}`;
  return (
    <div className="iq-guide-object" data-guide-object={choice.key}>
      <button
        className="iq-guide-toggle"
        type="button"
        aria-expanded={open}
        aria-controls={detailsId}
        onClick={() => onOpen(!open)}
      >
        <span className="iq-guide-chevron" aria-hidden="true">
          ›
        </span>
        <span className="iq-guide-object-icon" aria-hidden="true">
          {guideGlyph(choice.key)}
        </span>
        <span className="iq-guide-object-name">{guide.singular}</span>
        <span
          className={cn(
            'iq-guide-status',
            guide.createGood ? 'iq-guide-status--good' : 'iq-guide-status--warn',
          )}
        >
          <i></i>Create records
        </span>
        <span
          className={cn(
            'iq-guide-status',
            guide.updateGood ? 'iq-guide-status--good' : 'iq-guide-status--warn',
          )}
        >
          <i></i>Update records
        </span>
      </button>
      <div className="iq-guide-details" id={detailsId} hidden={!open}>
        <p
          className={cn(
            'iq-guide-state',
            guide.createGood ? 'iq-guide-state--good' : 'iq-guide-state--warn',
          )}
        >
          <i></i>
          {guide.state}
        </p>
        <div className="iq-guide-card-grid">
          <GuideCardView
            card={guide.create}
            good={guide.createGood}
            verb="create"
            plural={guide.plural}
            onChip={onChip}
          />
          <GuideCardView
            card={guide.update}
            good={guide.updateGood}
            verb="update"
            plural={guide.plural}
            onChip={onChip}
          />
        </div>
      </div>
    </div>
  );
}

export function MapPanel({
  hidden,
  choice,
  guide,
  guideOpen,
  onGuideOpen,
  onChip,
  onLearnMore,
  onSoon,
  scan,
  children,
  extraGuides = [],
}: {
  hidden: boolean;
  choice: ImportChoice;
  guide: ObjectGuide;
  guideOpen: boolean;
  onGuideOpen: (open: boolean) => void;
  onChip: (field: string) => void;
  onLearnMore: () => void;
  onSoon: (label: string) => void;
  scan: { text: string; errors: number };
  /** The mapping toolbar and table (Quick import's). */
  children: ReactNode;
  /** B5: the company's guide, after the contact's (`.php:181-196`). */
  extraGuides?: Array<{
    choice: ImportChoice;
    guide: ObjectGuide;
    open: boolean;
    onOpen: (open: boolean) => void;
    onChip: (field: string) => void;
  }>;
}) {
  const warning = missingIdentifierText(guide.plural, guide.updateGood);
  return (
    <section
      className="map-content"
      data-wizard-panel="3"
      hidden={hidden}
      aria-label="Map file columns"
      style={hidden ? { display: 'none' } : { display: 'block', visibility: 'visible' }}
    >
      <div className="crm-container">
        <section className="iq-step-view is-active" id="iqStep2" aria-label="Step 3: Map columns">
          <h1 className="iq-title crm-text-center crm-mt-4">
            Map columns in your file to CRM properties
          </h1>
          <p className="iq-subtitle crm-text-center">
            Learn how to import{' '}
            <a
              href="#"
              aria-label="Data model overview tool"
              onClick={soonLink(onSoon, 'Records and activities')}
            >
              records and activities
            </a>
          </p>

          <section className="iq-validation-top" aria-label="Import validation and mapping guide">
            {warning ? (
              <div className="iq-unique-warning" role="status">
                <div className="iq-unique-warning__title">
                  <span className="iq-warning-symbol" aria-hidden="true">
                    !
                  </span>
                  <strong>Missing unique identifiers</strong>
                </div>
                <p>
                  {warning}{' '}
                  <button
                    type="button"
                    className="iq-inline-help"
                    data-iq-guide-help
                    onClick={onLearnMore}
                  >
                    Learn more <span aria-hidden="true">↗</span>
                  </button>
                </p>
              </div>
            ) : null}

            <div className="iq-mapping-guide" id="iqMappingGuide">
              <div className="iq-mapping-guide__heading">
                <strong>Mapping Guide</strong>
                <span className="iq-guide-subtitle">
                  Required properties for creating and updating records
                </span>
              </div>
              <GuideObject
                choice={choice}
                guide={guide}
                open={guideOpen}
                onOpen={onGuideOpen}
                onChip={onChip}
              />
              {extraGuides.map((g) => (
                <GuideObject key={g.choice.key} {...g} />
              ))}
            </div>
            <div
              className="iq-scan-summary is-complete"
              id="iqScanSummary"
              role="status"
              aria-live="polite"
            >
              <span className="iq-scan-spinner" aria-hidden="true"></span>
              {scan.errors ? (
                <span className="iq-scan-result-icon" aria-hidden="true">
                  !
                </span>
              ) : null}
              <strong>{scan.text}</strong>
            </div>
          </section>

          {children}
        </section>
      </div>
    </section>
  );
}

/* ----------------------------------------------------------------- step 4 */

export function DetailsPanel(p: {
  hidden: boolean;
  name: string;
  /** B2: the name can be changed (the API keeps it); without a handler it stays as given. */
  onName?: (name: string) => void;
  /** "Create a contacts segment from this import": sent as `options.createList`. */
  createList: boolean;
  onCreateList: (on: boolean) => void;
  consent: boolean;
  onConsent: (on: boolean) => void;
  numberFormat: string;
  numberOpen: boolean;
  numberQuery: string;
  numberStyle: CSSProperties | undefined;
  onNumberOpen: (open: boolean, trigger: HTMLElement) => void;
  onNumberQuery: (q: string) => void;
  onNumberFormat: (name: string) => void;
  /** Enrichment has no API: the box stays unticked and says so. */
  onEnrich: (label: string) => void;
  onSoon: (label: string) => void;
  /** "Used in" counts (B1); "--" until known. */
  usage?: { workflows: string; segments: string };
  /** TK10: a task import makes no segment (tasks have no lists): the box isn't shown. */
  noList?: boolean;
}) {
  const usage = p.usage ?? { workflows: '--', segments: '--' };
  return (
    <section
      className="details-content"
      data-wizard-panel="4"
      hidden={p.hidden}
      aria-labelledby="details-heading"
      style={p.hidden ? { display: 'none' } : undefined}
    >
      <div className="details-inner">
        <h1 id="details-heading">A few final details</h1>

        <div className="details-field details-name-field">
          <label htmlFor="import-name">
            Import name <span aria-hidden="true">*</span>
          </label>
          <input
            id="import-name"
            name="import_name"
            type="text"
            required
            value={p.name}
            onChange={(e) => p.onName?.(e.target.value)}
          />
        </div>

        <label className="details-check-row" hidden={p.noList}>
          <input
            id="create-segment"
            type="checkbox"
            checked={p.createList}
            onChange={(e) => p.onCreateList(e.target.checked)}
          />
          <span>Create a contacts segment from this import</span>
        </label>

        <label className="details-check-row details-consent-row">
          <input
            id="import-consent"
            type="checkbox"
            checked={p.consent}
            onChange={(e) => p.onConsent(e.target.checked)}
          />
          <span>
            * I agree that all contacts in this import are expecting to hear from my organization. I
            have a prior relationship with these contacts and have emailed them at least once in the
            past year. I can confirm this list wasn’t purchased, rented, appended, or provided by a
            third party.
          </span>
        </label>

        <div className="details-field details-number-field">
          <label htmlFor="number-format-trigger">Number Format</label>
          <div className="details-number-picker">
            <button
              type="button"
              className="details-select-trigger"
              id="number-format-trigger"
              aria-expanded={p.numberOpen}
              onClick={(e) => p.onNumberOpen(!p.numberOpen, e.currentTarget)}
            >
              <span id="number-format-value">{p.numberFormat}</span>
              <ChevronIcon />
            </button>
            <div
              className="details-number-menu"
              id="number-format-menu"
              hidden={!p.numberOpen}
              style={p.numberStyle}
            >
              <label className="details-number-search">
                <input
                  id="number-format-search"
                  type="search"
                  placeholder="Search"
                  autoComplete="off"
                  aria-label="Search number formats"
                  value={p.numberQuery}
                  onChange={(e) => p.onNumberQuery(e.target.value)}
                />
                <SearchIcon />
              </label>
              <div className="details-number-options" id="number-format-options" role="listbox">
                {NUMBER_FORMATS.filter((f) => matchesLanguage(f.name, p.numberQuery)).map((f) => (
                  <button
                    key={f.name}
                    type="button"
                    className="details-number-option"
                    role="option"
                    aria-selected={f.name === p.numberFormat}
                    onClick={() => p.onNumberFormat(f.name)}
                  >
                    <span>{f.name}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
          <p id="number-format-hint">{numberFormatHint(p.numberFormat)}</p>
        </div>

        <section className="details-enrich-card" aria-labelledby="enrich-heading">
          <h2 id="enrich-heading">Enrich these records</h2>
          <p>
            Data Enrichment can enrich and fill in missing data for records you import, ensuring
            their accuracy and completeness.{' '}
            <a href="#" className="upload-link" onClick={soonLink(p.onSoon, 'Learn more')}>
              Learn more <ExternalIcon />
            </a>
          </p>
          <label className="details-check-row">
            <input
              id="enrich-contacts"
              type="checkbox"
              checked={false}
              onChange={() => p.onEnrich('Enrich contacts')}
            />
            <span>Enrich contacts</span>
          </label>
          <label className="details-check-row">
            <input
              id="enrich-companies"
              type="checkbox"
              checked={false}
              onChange={() => p.onEnrich('Enrich companies')}
            />
            <span>Enrich companies</span>
          </label>
        </section>

        <section className="details-usage-section" aria-labelledby="usage-heading">
          <h2 id="usage-heading">Properties in your import are used in:</h2>
          <div className="details-usage-card">
            <div className="details-usage-stat">
              <span>WORKFLOWS</span>
              <strong>{usage.workflows}</strong>
            </div>
            <div className="details-usage-stat">
              <span>SEGMENTS</span>
              <strong>{usage.segments}</strong>
            </div>
          </div>
        </section>
      </div>
    </section>
  );
}

/* ----------------------------------------------------------------- footer */

export function AdvancedFooter({
  step,
  nextDisabled,
  nextAria,
  finishing,
  onBack,
  onCancel,
  onNext,
}: {
  step: AdvancedStep;
  nextDisabled: boolean;
  nextAria: string | undefined;
  finishing: boolean;
  onBack: () => void;
  onCancel: () => void;
  onNext: () => void;
}) {
  return (
    <footer className="import-footer">
      <div className="import-footer__left crm-d-flex align-items-center crm-gap-2">
        <button
          className="btn-crm btn-crm--outline import-back"
          type="button"
          hidden={step === 1}
          aria-label="Go back to previous step"
          onClick={onBack}
        >
          <svg viewBox="0 0 20 20" aria-hidden="true" focusable="false">
            <path d="M15.5 10H4.5M9.5 5 4.5 10l5 5" />
          </svg>{' '}
          Back
        </button>
        <button className="btn-crm btn-crm--outline import-cancel" type="button" onClick={onCancel}>
          Cancel
        </button>
      </div>
      <span className="import-tip">
        Tip: press Enter/Return{' '}
        <svg className="import-enter-icon" viewBox="0 0 20 20" aria-hidden="true" focusable="false">
          <path d="M3 4v5h12a2 2 0 0 1 2 2v5M12 12l5 4 0-6" />
        </svg>{' '}
        to continue
      </span>
      <button
        className="btn-crm btn-crm--primary import-next"
        type="button"
        disabled={nextDisabled || finishing}
        aria-label={nextAria}
        onClick={onNext}
      >
        {step === 4 ? (
          'Finish'
        ) : (
          <>
            Next{' '}
            <svg
              className="import-next__icon"
              viewBox="0 0 20 20"
              aria-hidden="true"
              focusable="false"
            >
              <path d="M4 10h11M10 5l5 5-5 5" />
            </svg>
          </>
        )}
      </button>
    </footer>
  );
}
