'use client';

/**
 * D09: Actions > Merge on the contact record, the Contacts preview and the company record, as the
 * 28 Oct design's "Merge duplicate records" (`components/record-popups-hs.js` `merge()`,
 * :458-560; `modal()` :206-250; `filterPop()` :93-200). Company preview, deals and Manage
 * Duplicates keep `MergeRecordAction` / `MergeDialog`. EV15b: also the event record (Events only).
 */
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useToast } from '@/components/crm/ToastProvider';
import { formatUserDate, type DatePrefs } from '@/features/activities/readable';
import { getCompany, listCompanies } from '@/features/companies/api.client';
import { getContact, listContacts } from '@/features/contacts/api.client';
import { getDeal, listDeals } from '@/features/deals/api.client';
import { getObjectRecord, listObjectRecords } from '@/features/objects/api.client';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { getTask, listTasks } from '@/features/tasks/api.client';
import { priorityLabel } from '@/features/tasks/format';
import { TASK_STATUS_LABELS } from '@/features/tasks/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { getMergePreview, mergeRecords, OBJECT_NAMES, type MergePreview } from '../api.client';
import { EMPTY, useMergeValueFormatter } from '../format';
import { HxIcon } from './HxIcon';
import {
  buildRows,
  candidatesFrom,
  dragMove,
  filterProps,
  headerCloseAction,
  initialPicks,
  isEmptyValue,
  mergeBody,
  mergedField,
  mergedHeader,
  suggestedSides,
  mergedToast,
  mergeReady,
  moveUp,
  offeredProps,
  pickerParams,
  popPlace,
  propLabel,
  readSelection,
  recordName,
  recordSub,
  removeKey,
  withPick,
  toggleKey,
  wrapFocus,
  writeSelection,
  type MergeCandidateRow,
  type MergeObject,
  type MergeRecordData,
  type Side,
} from './mergeModel';
import { MergeView, NONE, PickerList, PropsView, type MergeRowView } from './MergeDesignViews';

const SINGLE: Record<MergeObject, string> = {
  contact: 'Contact',
  company: 'Company',
  event: 'Event',
  deal: 'Deal',
  lead: 'Lead',
  ticket: 'Ticket',
  task: 'Task',
};

/** The words and record page of each object (EV15b: events at `/events/<id>`). */
const NAMES: Record<MergeObject, { singular: string; plural: string; path: string }> = {
  contact: OBJECT_NAMES.contact,
  company: OBJECT_NAMES.company,
  event: { singular: 'event', plural: 'events', path: '/events' },
  deal: OBJECT_NAMES.deal,
  // LP8: leads at `/leads/<id>`.
  lead: { singular: 'lead', plural: 'leads', path: '/leads' },
  // QA 965: tickets at `/tickets/<id>`.
  ticket: { singular: 'ticket', plural: 'tickets', path: '/tickets' },
  // TKB-c3b: tasks at `/tasks/<id>`.
  task: { singular: 'task', plural: 'tasks', path: '/tasks' },
};

/**
 * TKB-c3b: a task as the dialog reads it, its merge fields (api `tasks/merge.ts` FIELDS) as the
 * task page shows them: stage and priority labels, the due date and the assignee's name.
 */
async function loadTask(id: string, dates: DatePrefs): Promise<MergeRecordData> {
  const task = await getTask(id);
  const due = task.dueAt ?? task.dueDate;
  return {
    id: task.id,
    title: task.title,
    taskType: task.taskType,
    priority: task.priority ? priorityLabel(task.priority) : null,
    status: TASK_STATUS_LABELS[task.status],
    due: due ? formatUserDate(due, { ...dates, time: Boolean(task.dueAt) }) : null,
    assigneeId: task.assignee?.name ?? null,
    notes:
      (task.notes ?? '')
        .replace(/<[^>]+>/g, ' ')
        .replace(/\s+/g, ' ')
        .trim() || null,
    createdAt: task.createdAt,
  };
}

function safeStorage(): Storage | null {
  try {
    return typeof window === 'undefined' ? null : window.localStorage;
  } catch {
    return null;
  }
}

function loadRecord(
  objectType: MergeObject,
  id: string,
  dates: DatePrefs,
): Promise<MergeRecordData> {
  if (objectType === 'task') return loadTask(id, dates);
  const req =
    objectType === 'event' || objectType === 'lead' || objectType === 'ticket'
      ? getObjectRecord(objectType, id)
      : objectType === 'deal'
        ? getDeal(id)
        : objectType === 'company'
          ? getCompany(id)
          : getContact(id);
  return req as unknown as Promise<MergeRecordData>;
}

async function loadCandidates(
  objectType: MergeObject,
  query: string,
  selfId: string,
): Promise<MergeCandidateRow[]> {
  const params = pickerParams(query);
  if (objectType === 'task') {
    // TKB-c3b: the tasks this person may see, by title (`GET /tasks?view=all&assignee=any&q=`).
    const tasks = await listTasks({
      view: 'all',
      assignee: 'any',
      ...(params.search ? { q: params.search } : {}),
      limit: params.limit,
    });
    return candidatesFrom(
      objectType,
      tasks.data.map((t) => ({ id: t.id, title: t.title, createdAt: t.createdAt })),
      selfId,
    );
  }
  const page =
    objectType === 'event' || objectType === 'lead' || objectType === 'ticket'
      ? await listObjectRecords(objectType, { search: params.search, limit: params.limit })
      : objectType === 'deal'
        ? // DR5b: the deals this person may open, matched on the name (`GET /deals?search=`).
          await listDeals({ search: params.search, limit: params.limit })
        : objectType === 'company'
          ? await listCompanies(params)
          : await listContacts(params);
  return candidatesFrom(objectType, page.data as unknown as MergeRecordData[], selfId);
}

const FOCUSABLE = 'button, a[href], input, select, [tabindex="0"]';

export function MergeDesignDialog({
  open,
  objectType,
  record,
  onClose,
  timeZone,
  initialOther,
  onMerged,
}: {
  open: boolean;
  objectType: MergeObject;
  /** The record whose page this is. */
  record: { id: string; label: string; secondary?: string | null };
  onClose: () => void;
  /** D10: date-times in the user's zone. */
  timeZone?: string;
  /**
   * LD4 (Leads bulk Merge, 26 Nov design list-page.js:5272-5276): the second record, already
   * picked when the window opens (it can still be changed). Left out, nothing is picked.
   */
  initialOther?: MergeCandidateRow;
  /**
   * LD4: after a merge, stay where we are (a list) and hand over the kept record's id. Left out,
   * the page loads the kept record, as before.
   */
  onMerged?: (survivorId: string) => void;
}) {
  const initialOtherRef = useRef(initialOther);
  initialOtherRef.current = initialOther;
  const toast = useToast();
  const prefs = useUserPrefs();
  const zone = timeZone ?? prefs.timeZone;
  // TKB-c3b: a task's due date in the viewer's format; read by the loads without reloading them.
  const datesRef = useRef<DatePrefs>({ region: prefs.regionFormat, timeZone: zone });
  datesRef.current = { region: prefs.regionFormat, timeZone: zone };
  const names = NAMES[objectType];
  const format = useMergeValueFormatter(objectType, open, zone);
  const dateText = useCallback(
    (iso: string) =>
      iso ? formatUserDate(iso, { region: prefs.regionFormat, timeZone: zone }) : '',
    [prefs.regionFormat, zone],
  );

  const [view, setView] = useState<'merge' | 'props'>('merge');
  const [defs, setDefs] = useState<CustomPropertyDefinition[] | null>(null);
  const [selection, setSelection] = useState<string[] | null>(null);
  const [draft, setDraft] = useState<string[]>([]);
  const [spQuery, setSpQuery] = useState('');
  const [recA, setRecA] = useState<MergeRecordData | null>(null);
  const [recAError, setRecAError] = useState<string | null>(null);
  const [other, setOther] = useState<MergeCandidateRow | null>(null);
  const [recB, setRecB] = useState<MergeRecordData | null>(null);
  const [preview, setPreview] = useState<MergePreview | null>(null);
  const [pairError, setPairError] = useState<string | null>(null);
  const [prim, setPrim] = useState<Side>('a');
  const [userPicks, setUserPicks] = useState<Record<string, Side>>({});
  const [busy, setBusy] = useState(false);
  const [pickerOpen, setPickerOpen] = useState(false);

  const overlayRef = useRef<HTMLDivElement>(null);
  const pickRef = useRef<HTMLButtonElement>(null);
  const returnTo = useRef<Element | null>(null);

  // Opening: start from this record, the saved properties and nothing picked.
  useEffect(() => {
    if (!open) return;
    returnTo.current = document.activeElement;
    setView('merge');
    setOther(initialOtherRef.current ?? null);
    setRecB(null);
    setPreview(null);
    setPairError(null);
    setPrim('a');
    setUserPicks({});
    setPickerOpen(false);
    setBusy(false);
    setRecA(null);
    setRecAError(null);
    setDefs(null);
    setSelection(null);
    let live = true;
    // Archived definitions too: the preview still returns their values (as `format.ts`).
    // TKB-c3b: a task has no custom fields to merge.
    (objectType === 'task'
      ? Promise.resolve([] as CustomPropertyDefinition[])
      : listCustomProperties({ objectType, includeArchived: true })
    )
      .then((list) => ({ list, failed: false }))
      .catch(() => ({ list: [] as CustomPropertyDefinition[], failed: true }))
      .then(({ list, failed }) => {
        if (!live) return;
        setDefs(list);
        // Failed: keep the saved custom choices rather than dropping (and later overwriting) them.
        setSelection(
          readSelection(safeStorage(), objectType, offeredProps(objectType, list), failed),
        );
      });
    loadRecord(objectType, record.id, datesRef.current)
      .then((r) => live && setRecA(r))
      .catch((err: unknown) => live && setRecAError(errorText(err)));
    return () => {
      live = false;
    };
  }, [open, objectType, record.id]);

  // A record picked: its detail and the preview, with this record as the survivor.
  useEffect(() => {
    if (!open || !other) return;
    let live = true;
    setRecB(null);
    setPreview(null);
    setPairError(null);
    Promise.all([
      loadRecord(objectType, other.id, datesRef.current),
      getMergePreview({ objectType, survivorId: record.id, otherId: other.id }),
    ])
      .then(([r, p]) => {
        if (!live) return;
        setRecB(r);
        setPreview(p);
      })
      .catch((err: unknown) => live && setPairError(errorText(err)));
    return () => {
      live = false;
    };
  }, [open, objectType, record.id, other]);

  // As `modal()` (:251): the body's first input, button or link, else the close button; on
  // each view, so Set properties and Back never leave focus on the page.
  useEffect(() => {
    if (!open) return;
    const t = window.setTimeout(() => {
      const ov = overlayRef.current;
      const first =
        ov
          ?.querySelector('.hx-modal__body')
          ?.querySelector<HTMLElement>('input:not([disabled]), button:not([disabled]), a[href]') ??
        ov?.querySelector<HTMLElement>('.hx-modal__head .hx-x[aria-label="Close"]');
      first?.focus();
    }, 0);
    return () => window.clearTimeout(t);
  }, [open, view]);

  // Focus goes back to what opened the window (Actions) when it closes.
  useEffect(() => {
    if (!open) return;
    return () => {
      const back = returnTo.current;
      if (back instanceof HTMLElement && back.isConnected) back.focus();
    };
  }, [open]);

  const close = useCallback(() => {
    if (busy) return;
    setPickerOpen(false);
    onClose();
  }, [busy, onClose]);

  // `modal()`'s keys (:239-245): Escape closes, Tab stays inside. The picker's own Escape runs
  // first (window, capture) and stops it there.
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      const ov = overlayRef.current;
      if (!ov) return;
      if (e.key === 'Escape') {
        e.stopPropagation();
        close();
        return;
      }
      if (e.key === 'Tab') {
        const list = Array.from(ov.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
          (x) => !(x as HTMLButtonElement).disabled && x.offsetParent !== null,
        );
        const at = wrapFocus(
          list.length,
          list.indexOf(document.activeElement as HTMLElement),
          e.shiftKey,
        );
        if (at >= 0) {
          e.preventDefault();
          list[at]?.focus();
        }
      }
    };
    document.addEventListener('keydown', onKey, true);
    return () => document.removeEventListener('keydown', onKey, true);
  }, [open, close]);

  const offered = useMemo(() => offeredProps(objectType, defs ?? []), [objectType, defs]);
  const ready = defs !== null && selection !== null && recA !== null;
  const pairReady = !other || (recB !== null && preview !== null);
  const rows = useMemo(
    () =>
      ready
        ? buildRows({
            selection,
            preview: other ? preview : null,
            a: recA,
            b: other ? recB : null,
            defs: defs ?? [],
            objectType,
          })
        : [],
    [ready, selection, preview, other, recA, recB, defs, objectType],
  );
  const picks = useMemo(() => ({ ...initialPicks(rows), ...userPicks }), [rows, userPicks]);

  const valueText = useCallback(
    (field: string, value: unknown) => {
      if (isEmptyValue(value)) return NONE;
      const t = format(field, value);
      return t === EMPTY ? NONE : t;
    },
    [format],
  );
  const isLink = (field: string) => field === 'email';

  const nameA = recA ? recordName(objectType, recA) : record.label || recordName(objectType, null);
  const subA = recA ? recordSub(objectType, recA) : (record.secondary ?? '');
  const href = (id: string) => `${names.path}/${id}`;
  const cardA = {
    name: nameA,
    sub: subA,
    createdText: dateText(String(recA?.createdAt ?? '')),
    href: href(record.id),
  };
  const cardB = other
    ? {
        name: other.name,
        sub: other.sub,
        createdText: dateText(other.createdAt),
        href: href(other.id),
      }
    : null;

  const rowViews: MergeRowView[] = rows.map((r) => ({
    field: r.field,
    label: r.label,
    aText: valueText(r.field, r.a),
    bText: other ? valueText(r.field, r.b) : NONE,
    pick: r.pickable && other ? (picks[r.field] ?? 'a') : other ? prim : 'a',
    off: !other || !r.pickable,
    link: isLink(r.field),
  }));

  // G18: what the API keeps for a field with no row (its rules, from the preview).
  const sides = other ? suggestedSides(preview) : {};
  const header = mergedHeader(
    objectType,
    rows,
    picks,
    other ? prim : 'a',
    recA,
    other ? recB : null,
    sides,
  );
  const merged = {
    name: header.name,
    sub: header.sub,
    createdText: dateText(header.createdAt),
    props: [...rows]
      .sort((x, y) => x.label.localeCompare(y.label))
      .map((r) => ({
        field: r.field,
        label: r.label,
        text: valueText(
          r.field,
          mergedField(r.field, rows, picks, other ? prim : 'a', recA, other ? recB : null, sides),
        ),
        link: isLink(r.field),
      })),
  };

  const rowsError = recAError ?? pairError;
  const canMerge = mergeReady({
    picked: other !== null,
    loaded: ready && pairReady,
    error: rowsError,
    busy,
  });

  const onMerge = async () => {
    if (!other || !canMerge) return;
    setBusy(true);
    try {
      const body = mergeBody(objectType, record.id, other.id, prim, rows, picks);
      const result = await mergeRecords(body);
      const [kept, gone] = prim === 'a' ? [nameA, other.name] : [other.name, nameA];
      toast(mergedToast(gone, kept), 'success');
      if (onMerged) {
        // LD4: a list stays put; it reloads its rows.
        setBusy(false);
        onClose();
        onMerged(result.survivorId);
        return;
      }
      // A full load, so the page shows the kept record even when it is this one (as master).
      window.location.assign(href(result.survivorId));
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
      setBusy(false);
    }
  };

  const openProps = () => {
    setDraft(selection ?? []);
    setSpQuery('');
    setPickerOpen(false);
    setView('props');
  };
  const applyProps = () => {
    setSelection(draft);
    writeSelection(safeStorage(), objectType, draft);
    setView('merge');
  };

  if (!open || typeof document === 'undefined') return null;

  const title = view === 'merge' ? 'Merge duplicate records' : 'Select properties';
  return createPortal(
    <div
      ref={overlayRef}
      className="rpx-modal-ov hx-modal-ov is-open"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) close();
      }}
    >
      <div
        className="rpx-modal hx-modal hx-modal--xl"
        role="dialog"
        aria-modal="true"
        aria-labelledby="hxMergeTitle"
      >
        <header className="hx-modal__head">
          <span data-back="">
            {view === 'props' ? (
              <button
                type="button"
                className="hx-x hx-back"
                aria-label="Back"
                onClick={() => setView('merge')}
              >
                <HxIcon name="back" />
              </button>
            ) : null}
          </span>
          <h2 id="hxMergeTitle">{title}</h2>
          <button
            type="button"
            className="hx-x"
            aria-label="Close"
            onClick={() => (headerCloseAction(view) === 'back' ? setView('merge') : close())}
            disabled={busy}
          >
            <HxIcon name="x" />
          </button>
        </header>
        <div className="hx-modal__body">
          {view === 'merge' ? (
            <MergeView
              ref={pickRef}
              objectType={objectType}
              singular={names.singular}
              recordName={nameA}
              pickLabel={other ? other.name : 'Select a record'}
              pickerOpen={pickerOpen}
              cardA={cardA}
              cardB={cardB}
              prim={prim}
              rows={ready ? rowViews : []}
              rowsError={rowsError}
              merged={merged}
              busy={busy}
              onPrim={(side) => other && setPrim(side)}
              // DR5b: a deal's pipeline and stage move together (`withPick`).
              onPick={(field, side) => setUserPicks((cur) => withPick(cur, field, side))}
              onSwap={(field) =>
                setUserPicks((cur) =>
                  withPick(cur, field, (picks[field] ?? 'a') === 'a' ? 'b' : 'a'),
                )
              }
              onOpenPicker={() => setPickerOpen((o) => !o)}
              onSetProps={openProps}
            />
          ) : (
            <PropsView
              title={SINGLE[objectType]}
              offered={filterProps(offered, spQuery)}
              query={spQuery}
              selected={draft}
              labelOf={(field) => propLabel(field, defs ?? [], undefined, objectType)}
              onQuery={setSpQuery}
              onToggle={(field, on) => setDraft((d) => toggleKey(d, field, on))}
              onRemove={(field) => setDraft((d) => removeKey(d, field))}
              onMoveUp={(i) => setDraft((d) => moveUp(d, i))}
              onDrag={(from, to) => setDraft((d) => dragMove(d, from, to))}
            />
          )}
        </div>
        <footer className="hx-modal__foot">
          {view === 'merge' ? (
            <>
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                data-b="go"
                disabled={!canMerge}
                aria-busy={busy}
                onClick={() => void onMerge()}
              >
                Merge
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                onClick={close}
                disabled={busy}
              >
                Cancel
              </button>
            </>
          ) : (
            <>
              <button type="button" className="btn-crm btn-crm--primary" onClick={applyProps}>
                Apply
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                onClick={() => setView('merge')}
              >
                Cancel
              </button>
            </>
          )}
        </footer>
      </div>
      {pickerOpen && view === 'merge' ? (
        <RecordPicker
          anchor={pickRef}
          objectType={objectType}
          plural={names.plural}
          selfId={record.id}
          selectedId={other?.id ?? null}
          onChoose={(item) => {
            setPickerOpen(false);
            setUserPicks({});
            setOther(item);
            pickRef.current?.focus();
          }}
          onClose={(focus) => {
            setPickerOpen(false);
            if (focus) pickRef.current?.focus();
          }}
        />
      ) : null}
    </div>,
    document.body,
  );
}

/** `filterPop()` for "Select a record" (:93-200, `place()` :124-132): fixed to the window. */
function RecordPicker({
  anchor,
  objectType,
  plural,
  selfId,
  selectedId,
  onChoose,
  onClose,
}: {
  anchor: React.RefObject<HTMLButtonElement | null>;
  objectType: MergeObject;
  plural: string;
  selfId: string;
  selectedId: string | null;
  onChoose: (item: MergeCandidateRow) => void;
  onClose: (focus: boolean) => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);
  const [query, setQuery] = useState('');
  const [items, setItems] = useState<MergeCandidateRow[]>([]);
  const [status, setStatus] = useState<'loading' | 'ready' | 'failed'>('loading');
  const [error, setError] = useState<string | null>(null);
  const [place, setPlace] = useState<ReturnType<typeof popPlace> | null>(null);

  useEffect(() => {
    let live = true;
    setStatus('loading');
    const t = window.setTimeout(
      () => {
        loadCandidates(objectType, query, selfId)
          .then((list) => {
            if (!live) return;
            setItems(list);
            setStatus('ready');
          })
          .catch((err: unknown) => {
            if (!live) return;
            setError(errorText(err));
            setStatus('failed');
          });
      },
      query ? 250 : 0,
    );
    return () => {
      live = false;
      window.clearTimeout(t);
    };
  }, [objectType, query, selfId]);

  const measure = useCallback(() => {
    const a = anchor.current;
    const el = ref.current;
    if (!a || !el) return;
    // The uncapped height (the search, the list's content, the border), within the CSS cap.
    const search = el.querySelector<HTMLElement>('.hx-pop__search')?.offsetHeight ?? 0;
    const list = el.querySelector<HTMLElement>('.hx-pop__list')?.scrollHeight ?? 0;
    const natural = Math.min(440, window.innerHeight - 40, search + list + 2);
    const next = popPlace(a.getBoundingClientRect(), natural, {
      width: window.innerWidth,
      height: window.innerHeight,
    });
    setPlace((p) =>
      p &&
      p.left === next.left &&
      p.top === next.top &&
      p.width === next.width &&
      p.up === next.up &&
      p.maxHeight === next.maxHeight
        ? p
        : next,
    );
  }, [anchor]);

  useLayoutEffect(() => {
    measure();
  }, [measure, items, status]);

  const closeRef = useRef(onClose);
  useEffect(() => {
    closeRef.current = onClose;
  }, [onClose]);

  // The search box takes focus once the popover is placed (`:174`): the first frame is hidden
  // while it is measured, and a hidden input can't take focus.
  const placed = place !== null;
  useEffect(() => {
    if (placed) searchRef.current?.focus();
  }, [placed]);

  useEffect(() => {
    const outside = (e: MouseEvent) => {
      const t = e.target as Node;
      if (ref.current?.contains(t) || anchor.current?.contains(t)) return;
      closeRef.current(false);
    };
    const key = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        e.preventDefault();
        closeRef.current(true);
        return;
      }
      const el = ref.current;
      if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && el?.contains(document.activeElement)) {
        const opts = Array.from(el.querySelectorAll<HTMLElement>('.hx-pop__list button'));
        if (!opts.length) return;
        e.preventDefault();
        const i = opts.indexOf(document.activeElement as HTMLElement);
        const next =
          e.key === 'ArrowDown' ? (i + 1) % opts.length : i <= 0 ? opts.length - 1 : i - 1;
        opts[next]?.focus();
      }
    };
    document.addEventListener('mousedown', outside, true);
    window.addEventListener('keydown', key, true);
    window.addEventListener('resize', measure);
    return () => {
      document.removeEventListener('mousedown', outside, true);
      window.removeEventListener('keydown', key, true);
      window.removeEventListener('resize', measure);
    };
  }, [anchor, measure]);

  return (
    <div
      ref={ref}
      className={cn('hx-pop hx-pop--wide hx-pop--select', place?.up && 'is-up')}
      role="dialog"
      aria-label="Select a record"
      style={
        place
          ? {
              left: place.left,
              top: place.top,
              width: place.width,
              ...(place.maxHeight !== null ? { maxHeight: place.maxHeight } : {}),
            }
          : { left: -9999, top: 0, visibility: 'hidden' }
      }
    >
      <span className="hx-pop__arrow" aria-hidden="true" />
      <div className="hx-pop__search">
        <label className="hx-searchbox">
          <input
            ref={searchRef}
            type="search"
            placeholder={`Search ${plural}`}
            aria-label="Search"
            autoComplete="off"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <HxIcon name="search" />
        </label>
      </div>
      <div className="hx-pop__list" role="listbox">
        <PickerList
          items={items}
          selectedId={selectedId}
          status={status}
          error={error}
          onChoose={onChoose}
        />
      </div>
    </div>
  );
}
