'use client';

/**
 * The row menu's "Restore CRM changes" drawer (`data-integration.php:1847-1984`,
 * `data-integration.js:696-1376`). QA #553 (the user's call, 16 Nov 2026): Prepare preview asks
 * the API for the changes, the preview lists them as the design's cards, and Restore puts the
 * ticked ones back. Nothing shown is the design's sample data.
 */
import { useEffect, useMemo, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { useBusinessCurrency } from '@/features/custom-properties/field-types';
import { restoreStamp, toggleChange } from '@/features/list-page/ui/RestoreChangesForm';
import { zonedDateTimeText } from '@/features/list-page/listZone';
import { listAllOwners, type Owner } from '@/features/owners/api.client';
import { listPicklist, type PicklistOption } from '@/features/picklists/api.client';
import {
  previewPropertyChanges,
  restorePropertyChanges,
  type DrawerObject,
  type PropertyChange,
  type PropertyChangesPreview,
} from '@/features/property-changes/api.client';
import type { DescribeField } from '@/features/property-history/describe';
import {
  companyHistoryDescriber,
  contactHistoryDescriber,
  dealHistoryDescriber,
} from '@/features/property-history/records';
import { isApiError, errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  RESTORE_OBJECT_OPTIONS,
  RESTORE_SOURCE_OPTIONS,
  chipSummary,
  togglePick,
} from '../restore';
import {
  BLOCKED_TEXT,
  changedByText,
  drawerProperties,
  drawerQuery,
  isDrawerObject,
  prepareDisabled,
  previewSub,
  restoreButtonText,
  restoreFailedText,
  restoreToast,
  type RestoreProperty,
} from '../restoreFlow';

const OBJECT_TAG: Record<DrawerObject, string> = {
  contact: 'Contact',
  company: 'Company',
  deal: 'Deal',
};

const objectLabel = (object: string) =>
  RESTORE_OBJECT_OPTIONS.find((o) => o.value === object)?.label ?? object;

/** The drawer's Properties box and its popover (`data-integration.php:1906-1938`). */
function PropertiesField({
  all,
  failed,
  picked,
  onPicked,
  open,
  onOpen,
}: {
  /** The object's property labels; null while they load. */
  all: string[] | null;
  failed: boolean;
  picked: string[];
  onPicked: (next: string[]) => void;
  /** The popover, held by the drawer so Escape closes it first (`data-integration.js:1319-1327`). */
  open: boolean;
  onOpen: (open: boolean) => void;
}) {
  const [above, setAbove] = useState(false);
  const [maxHeight, setMaxHeight] = useState<number | undefined>(undefined);
  const [q, setQ] = useState('');
  const box = useRef<HTMLDivElement>(null);
  const anchor = useRef<HTMLDivElement>(null);
  const search = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (anchor.current && !anchor.current.contains(e.target as Node)) onOpen(false);
    };
    document.addEventListener('click', onClick);
    // Opening clears and focuses the search (`data-integration.js:969-985`).
    search.current?.focus();
    return () => document.removeEventListener('click', onClick);
  }, [open, onOpen]);

  const toggleOpen = () => {
    if (!open && box.current) {
      // Above when there's no room below, capped to the room there (`data-integration.js:909-936`).
      const r = box.current.getBoundingClientRect();
      const body = box.current.closest('.di-drawer__body')?.getBoundingClientRect();
      const below =
        (body ? Math.min(body.bottom, window.innerHeight) : window.innerHeight) - r.bottom - 8;
      const over = r.top - (body ? Math.max(body.top, 0) : 0) - 8;
      const up = below < 280 && over > below;
      setAbove(up);
      setMaxHeight(Math.min(280, Math.max(120, Math.floor((up ? over : below) - 8))));
      setQ('');
    }
    onOpen(!open);
  };

  const { chips, more } = chipSummary(picked);
  const shown = (all ?? []).filter(
    (p) => !q.trim() || p.toLowerCase().includes(q.trim().toLowerCase()),
  );
  return (
    <div className="di-drawer-field">
      <label className="di-drawer-label">Properties</label>
      <div className="di-restore-props-anchor" ref={anchor}>
        <div
          ref={box}
          className={cn('di-restore-props-box', open && 'is-active')}
          id="diRestorePropsBox"
          tabIndex={0}
          role="button"
          aria-haspopup="menu"
          aria-expanded={open}
          onClick={toggleOpen}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              toggleOpen();
            }
          }}
        >
          <div className="di-restore-chips-list" id="diRestoreChipsList">
            {chips.length ? (
              chips.map((c) => (
                <span key={c} className="di-rc-chip">
                  {c}
                </span>
              ))
            ) : (
              <span className="di-rc-placeholder">Select properties</span>
            )}
          </div>
          <div className="di-restore-more-row" style={{ visibility: more ? 'visible' : 'hidden' }}>
            <span className="di-restore-more-label" id="diRestoreMoreLabel">
              {more}
            </span>
            <span className="di-restore-more-caret">
              <CrmIcon name="chevron-down" className="iconSize-14" />
            </span>
          </div>
        </div>
        <div
          className={cn('di-props-popover', above && 'is-open-above')}
          id="diPropsPopover"
          role="menu"
          hidden={!open}
          style={maxHeight ? { maxHeight } : undefined}
        >
          <div className="di-props-search-wrap">
            <input
              ref={search}
              type="search"
              className="di-props-search"
              id="diPropsSearch"
              placeholder="Search properties"
              aria-label="Search properties"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
          </div>
          <div className="di-props-list" id="diPropsCheckboxList">
            {all === null ? (
              <div className="crm-text-muted crm-fs-8 crm-p-2 crm-text-center">
                Loading properties…
              </div>
            ) : failed ? (
              <div className="crm-text-muted crm-fs-8 crm-p-2 crm-text-center">
                Couldn&apos;t load properties. Try again later.
              </div>
            ) : shown.length === 0 ? (
              <div className="crm-text-muted crm-fs-8 crm-p-2 crm-text-center">
                No properties found
              </div>
            ) : (
              shown.map((p) => {
                const on = picked.includes(p);
                return (
                  <button
                    key={p}
                    type="button"
                    className={cn('di-props-item', on && 'is-selected')}
                    role="menuitemcheckbox"
                    aria-checked={on}
                    onClick={() => onPicked(togglePick(picked, p))}
                  >
                    <span>{p}</span>
                  </button>
                );
              })
            )}
          </div>
        </div>
      </div>
      <button
        type="button"
        className="di-restore-clear-link"
        id="diRestoreClearProps"
        disabled={picked.length === 0}
        onClick={() => onPicked([])}
      >
        <svg
          className="di-restore-trash-icon"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
          <path d="M10 11v6M14 11v6" />
        </svg>
        <span>Clear all filters</span>
      </button>
    </div>
  );
}

/** The wait step (`data-integration.php:1935-1941`, `.js:1119-1124`). */
export function RestoreWait({ object, importName }: { object: string; importName: string | null }) {
  return (
    <div className="di-restore-wait" id="diRestoreWait" role="status">
      <span className="di-restore-spinner" aria-hidden="true" />
      <strong className="di-restore-wait-title">Preparing your preview</strong>
      <p className="di-restore-wait-msg" id="diRestoreWaitMsg">
        We&apos;re searching {objectLabel(object).toLowerCase()} changes
        {importName ? ` for ${importName}` : ''}...
      </p>
    </div>
  );
}

/**
 * The preview step (`data-integration.php:1944-1959`, `.js:1134-1215`): the expiry banner, the
 * count, Select all and one card per change, struck-through value → the value restore puts back.
 * Changes the API won't put back (changed since, not theirs to edit, a locked property) can't be
 * ticked and say why (the user's call D3). One a restore just skipped says why too but can be
 * ticked again, to retry it (as the list pages' panel).
 */
export function RestorePreviewBody({
  preview,
  changes,
  describe,
  picked,
  why,
  source,
  object,
  importName,
  timeZone,
  readOnly,
  onToggle,
  onAll,
}: {
  preview: PropertyChangesPreview;
  /** The preview's changes still to show (restored ones are gone). */
  changes: PropertyChange[];
  describe: (object: DrawerObject) => DescribeField;
  picked: ReadonlySet<string>;
  /** Why a restore skipped a change, by id. */
  why: Readonly<Record<string, string>>;
  source: string;
  object: string;
  importName: string | null;
  timeZone?: string;
  readOnly: boolean;
  onToggle: (id: string) => void;
  onAll: (on: boolean) => void;
}) {
  const selectable = readOnly ? [] : changes.filter((c) => c.status === 'ready');
  const allOn = selectable.length > 0 && selectable.every((c) => picked.has(c.id));
  const expires = new Date(Date.parse(preview.preparedAt) + 24 * 3_600_000).toISOString();
  const sub = previewSub(changes.length, source, objectLabel(object));
  return (
    <div className="di-restore-preview" id="diRestorePreview">
      <div className="di-restore-info-banner">
        <CrmIcon name="info" className="iconSize-16" />
        <div>
          <strong>Your preview is ready.</strong> Review and restore before{' '}
          <span id="diRestoreExpTime">{restoreStamp(expires, timeZone)}</span>.
        </div>
      </div>
      <p className="di-restore-preview-sub" id="diRestorePreviewSub">
        <strong>{sub.count}</strong>
        {sub.rest}
      </p>
      <div className="di-restore-all-wrap">
        <label className="di-restore-all-label">
          <input
            type="checkbox"
            id="diRestoreSelectAll"
            className="crm-form-check-input"
            checked={allOn}
            disabled={selectable.length === 0}
            onChange={() => onAll(!allOn)}
          />
          <span id="diRestoreSelectAllText">Select all {selectable.length}</span>
        </label>
      </div>
      <div className="di-restore-changes-list" id="diRestoreChangesList">
        {changes.length === 0 ? (
          <div className="di-restore-empty">
            <strong>No changes found</strong>
            <p className="crm-text-muted crm-m-0">
              Nothing matches these filters. Go back and select different properties or another
              import.
            </p>
          </div>
        ) : (
          changes.map((c) => {
            const info = describe(c.objectType)(c.field);
            const on = picked.has(c.id);
            const blocked = c.status === 'ready' ? why[c.id] : BLOCKED_TEXT[c.status];
            const inputId = `diChg-${c.id}`;
            return (
              <label
                key={c.id}
                className={cn('di-restore-card', on && 'is-selected')}
                htmlFor={inputId}
              >
                <input
                  type="checkbox"
                  id={inputId}
                  data-change-id={c.id}
                  checked={on}
                  disabled={readOnly || c.status !== 'ready'}
                  onChange={() => onToggle(c.id)}
                />
                <div className="di-restore-card-content">
                  <div className="di-restore-card-top">
                    <span className="di-restore-card-name">{c.recordName}</span>
                    <span className="di-restore-card-tag">{OBJECT_TAG[c.objectType]}</span>
                  </div>
                  <div className="di-restore-card-prop">
                    {info.label}: <s>{info.text(c.to)}</s> &rarr; <b>{info.text(c.from)}</b>
                  </div>
                  <div className="di-restore-card-meta">
                    Changed by {changedByText(c, importName)} &middot;{' '}
                    {restoreStamp(c.changedAt, timeZone)}
                  </div>
                  {blocked ? <div className="di-restore-card-meta">{blocked}</div> : null}
                </div>
              </label>
            );
          })
        )}
      </div>
    </div>
  );
}

type Step = 'form' | 'wait' | 'preview';

/** History's field labels for an object (no owners or option labels needed for those). */
function labelsOf(type: DrawerObject, defs: CustomPropertyDefinition[]): DescribeField {
  if (type === 'contact') return contactHistoryDescriber({ defs, owners: [], picklists: [] });
  if (type === 'company') return companyHistoryDescriber({ defs, owners: [], industries: [] });
  return dealHistoryDescriber({ defs, owners: [], dealTypes: [], currency: 'USD' });
}

/** Everything the cards and the Properties list need for one object. */
function useObjectData(object: string, open: boolean) {
  const [defs, setDefs] = useState<CustomPropertyDefinition[] | null>(null);
  const [failed, setFailed] = useState(false);
  const [owners, setOwners] = useState<Owner[]>([]);
  const [options, setOptions] = useState<Record<string, PicklistOption[]>>({});
  const currency = useBusinessCurrency(open && object === 'deal');

  useEffect(() => {
    if (!open) return;
    // Deactivated owners too: their past changes and owner values need names.
    listAllOwners(true).then(setOwners, () => setOwners([]));
  }, [open]);

  useEffect(() => {
    if (!open) return;
    let live = true;
    setDefs(null);
    setFailed(false);
    listCustomProperties({ objectType: object }).then(
      (rows) => live && setDefs(rows),
      () => {
        if (!live) return;
        setDefs([]);
        setFailed(isDrawerObject(object));
      },
    );
    const fields: Record<string, Array<[PicklistOption['objectType'], string]>> = {
      contact: [
        ['contact', 'lifecycleStage'],
        ['contact', 'leadStatus'],
      ],
      company: [['company', 'industry']],
      deal: [['deal', 'dealType']],
    };
    void Promise.all(
      (fields[object] ?? []).map(([type, field]) =>
        listPicklist(type, field).then(
          (rows) => [field, rows] as const,
          () => [field, []] as const,
        ),
      ),
    ).then((rows) => live && setOptions(Object.fromEntries(rows)));
    return () => {
      live = false;
    };
  }, [object, open]);

  const describe = useMemo(() => {
    const d = defs ?? [];
    return (type: DrawerObject, timeZone?: string): DescribeField => {
      const formatDateTime = zonedDateTimeText(timeZone);
      if (type === 'contact') {
        return contactHistoryDescriber({
          defs: d,
          owners,
          picklists: [
            ...(options.lifecycleStage ?? []).map((o) => ({ ...o, field: 'lifecycleStage' })),
            ...(options.leadStatus ?? []).map((o) => ({ ...o, field: 'leadStatus' })),
          ],
          formatDateTime,
        });
      }
      if (type === 'company') {
        return companyHistoryDescriber({
          defs: d,
          owners,
          industries: options.industry ?? [],
          formatDateTime,
        });
      }
      return dealHistoryDescriber({
        defs: d,
        owners,
        dealTypes: options.dealType ?? [],
        currency,
        formatDateTime,
      });
    };
  }, [defs, owners, options, currency]);

  return { defs, failed, describe };
}

/** "Restore CRM changes": the form, the wait, the preview and Restore. */
export function RestoreDrawer({
  open,
  importId,
  importName,
  imports,
  timeZone,
  readOnly = false,
  onSoon,
  onClose,
}: {
  open: boolean;
  /** The row the drawer was opened from. */
  importId: string;
  importName: string;
  /** Every loaded import, for "Import name" (two imports may share a name: kept by id). */
  imports: Array<{ id: string; name: string }>;
  /** The user's zone, for the 14 days, the expiry and the cards' times. */
  timeZone?: string;
  /** A read-only person sees the preview but can't restore. */
  readOnly?: boolean;
  onSoon: (label: string) => void;
  onClose: () => void;
}) {
  const toast = useToast();
  // Each open starts as the design's `openDrawer` (`data-integration.js:1063-1095`): the page
  // mounts the drawer afresh for every open (a new `key`), so these start values always apply.
  const [source, setSource] = useState('Import');
  const [chosen, setChosen] = useState(importId);
  const [object, setObject] = useState('contact');
  const [picked, setPicked] = useState<string[]>([]);
  const [propsOpen, setPropsOpen] = useState(false);
  const [step, setStep] = useState<Step>('form');
  const [preview, setPreview] = useState<PropertyChangesPreview | null>(null);
  const [ticked, setTicked] = useState<Set<string>>(new Set());
  const [gone, setGone] = useState<Set<string>>(new Set());
  const [why, setWhy] = useState<Record<string, string>>({});
  const [busy, setBusy] = useState(false);
  /** What the shown preview was asked for. */
  const [asked, setAsked] = useState({ source: 'Import', object: 'contact', importName: '' });
  /** Answers to an older Prepare (or one from before Back) are dropped. */
  const run = useRef(0);
  const { defs, failed, describe } = useObjectData(object, open);

  const options = useMemo(() => {
    const seen = new Set<string>();
    return [{ id: importId, name: importName }, ...imports].filter((i) => {
      if (!i.id || seen.has(i.id)) return false;
      seen.add(i.id);
      return true;
    });
  }, [importId, importName, imports]);

  // Labels only: built from the object's fields, not from owners or picklists (review: their late
  // answers re-ticked every property).
  const properties: RestoreProperty[] | null = useMemo(
    () => drawerProperties(object, defs, failed, (type) => labelsOf(type, defs ?? [])),
    [defs, object, failed],
  );

  // The object's properties, all picked at first, as the design picks its whole list (`:1069`).
  useEffect(() => {
    setPicked(properties ? properties.map((p) => p.label) : []);
  }, [properties]);

  // The page doesn't scroll behind it (the design's `di-noscroll`). Escape closes the Properties
  // popover first, then the drawer (`data-integration.js:1319-1327`).
  useEffect(() => {
    if (!open) return;
    const before = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      if (propsOpen) setPropsOpen(false);
      else onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = before;
      document.removeEventListener('keydown', onKey);
    };
  }, [open, onClose, propsOpen]);

  // A preview or restore answering after the drawer closed is dropped.
  useEffect(() => {
    if (!open) return;
    const runs = run;
    return () => {
      runs.current += 1;
    };
  }, [open]);

  if (!open) return null;

  const chosenName = options.find((o) => o.id === chosen)?.name ?? importName;

  const prepare = async () => {
    setPropsOpen(false);
    const ask = drawerQuery({
      source,
      importId: chosen,
      object,
      picked,
      all: properties ?? [],
      timeZone,
    });
    if ('soon' in ask) {
      onSoon(ask.soon);
      return;
    }
    const mine = ++run.current;
    setAsked({ source, object, importName: source === 'Import' ? chosenName : '' });
    setStep('wait');
    setTicked(new Set());
    setGone(new Set());
    setWhy({});
    try {
      const result = await previewPropertyChanges(ask.query);
      if (run.current !== mine) return;
      setPreview(result);
      setStep('preview');
    } catch (err) {
      if (run.current !== mine) return;
      // Nothing is "ready": back to the form, with the API's message.
      setStep('form');
      toast(errorText(err), 'danger');
    }
  };

  const shown = (preview?.data ?? []).filter((c) => !gone.has(c.id));
  const n = shown.filter((c) => ticked.has(c.id)).length;

  const restore = async () => {
    if (!preview || !n || busy || readOnly) return;
    const ids = shown.filter((c) => ticked.has(c.id)).map((c) => c.id);
    const mine = run.current;
    setBusy(true);
    try {
      const result = await restorePropertyChanges(ids, preview.preparedAt);
      const skipped = new Map(result.skipped.map((s) => [s.id, s.message]));
      if (run.current === mine) {
        setGone((g) => new Set([...g, ...ids.filter((id) => !skipped.has(id))]));
        setWhy((w) => ({ ...w, ...Object.fromEntries(skipped) }));
        // The design clears the ticks and lists what's left (`data-integration.js:1282-1286`).
        setTicked(new Set());
      }
      const [text, tone] = restoreToast(result);
      toast(text, tone);
    } catch (err) {
      const status = isApiError(err) ? err.status : undefined;
      const conflict = isApiError(err) && err.isConflict;
      toast(restoreFailedText(status, errorText(err), conflict), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div
      className="di-drawer-backdrop is-open"
      id="diRestoreChangesDrawer"
      aria-hidden="false"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <aside
        className="di-drawer di-restore-drawer"
        role="dialog"
        aria-modal="true"
        aria-labelledby="diRestoreTitle"
      >
        <header className="di-drawer__header">
          <h2 className="di-drawer__title" id="diRestoreTitle">
            Restore CRM changes
          </h2>
          <button
            type="button"
            className="di-drawer__close"
            aria-label="Close dialog"
            onClick={onClose}
          >
            <CrmIcon name="x" className="iconSize-18" />
          </button>
        </header>
        <div className="di-drawer__body" id="diRestoreDrawerBody">
          <div className="di-restore-form" id="diRestoreForm" hidden={step !== 'form'}>
            <p className="di-restore-desc">
              Tell us what you need to restore from the last 14 days. We&apos;ll run the search and
              notify you when your preview is ready. You&apos;ll have 24 hours to review and
              restore.
            </p>
            <div className="di-drawer-field">
              <label className="di-drawer-label" htmlFor="diRestoreSource">
                Source{' '}
                <span className="crm-text-danger" aria-hidden="true">
                  *
                </span>
              </label>
              <CustomSelect
                id="diRestoreSource"
                className="crm-w-100"
                placeholder="Select source"
                value={source}
                options={[...RESTORE_SOURCE_OPTIONS]}
                onChange={setSource}
              />
            </div>
            {source === 'Import' ? (
              <div className="di-drawer-field" id="diRestoreImportNameField">
                <label className="di-drawer-label" htmlFor="diRestoreImportName">
                  Import name{' '}
                  <span className="crm-text-danger" aria-hidden="true">
                    *
                  </span>
                </label>
                <CustomSelect
                  id="diRestoreImportName"
                  className="crm-w-100"
                  placeholder="Select import"
                  searchable
                  value={chosen}
                  options={options.map((o) => ({ value: o.id, label: o.name }))}
                  onChange={setChosen}
                />
              </div>
            ) : null}
            <div className="di-drawer-field">
              <label className="di-drawer-label" htmlFor="diRestoreObject">
                <span>Objects</span>
                <span
                  className="di-drawer-info"
                  title="Restore changes to records of these objects"
                  aria-label="Restore changes to records of these objects"
                >
                  <CrmIcon name="info" className="iconSize-14" />
                </span>
              </label>
              <CustomSelect
                id="diRestoreObject"
                className="crm-w-100"
                placeholder="Select object"
                value={object}
                options={[...RESTORE_OBJECT_OPTIONS]}
                onChange={setObject}
              />
            </div>
            <PropertiesField
              all={properties ? properties.map((p) => p.label) : null}
              failed={failed}
              picked={picked}
              onPicked={setPicked}
              open={propsOpen}
              onOpen={setPropsOpen}
            />
          </div>
          {step === 'wait' ? (
            <RestoreWait object={asked.object} importName={asked.importName || null} />
          ) : null}
          {step === 'preview' && preview ? (
            <RestorePreviewBody
              preview={preview}
              changes={shown}
              describe={(type) => describe(type, timeZone)}
              picked={ticked}
              why={why}
              source={asked.source}
              object={asked.object}
              importName={asked.importName || null}
              timeZone={timeZone}
              readOnly={readOnly}
              onToggle={(id) => setTicked((t) => toggleChange(shown, t, id))}
              onAll={(on) =>
                setTicked(
                  on
                    ? new Set(shown.filter((c) => c.status === 'ready').map((c) => c.id))
                    : new Set(),
                )
              }
            />
          ) : null}
        </div>
        <footer className="di-drawer__footer" id="diRestoreDrawerFooter">
          {step === 'form' ? (
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              id="diRestorePrepareBtn"
              disabled={prepareDisabled({ object, picked, source, importId: chosen })}
              onClick={() => void prepare()}
            >
              Prepare preview
            </button>
          ) : null}
          {step === 'preview' ? (
            <div className="di-restore-preview-actions" id="diRestorePreviewActions">
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                id="diRestoreSubmitBtn"
                disabled={n === 0 || busy || readOnly}
                aria-busy={busy || undefined}
                title={readOnly ? 'You have view-only access' : undefined}
                onClick={() => void restore()}
              >
                {restoreButtonText(n)}
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                id="diRestoreBackBtn"
                disabled={busy}
                onClick={() => {
                  run.current += 1;
                  setStep('form');
                }}
              >
                Back
              </button>
            </div>
          ) : null}
        </footer>
      </aside>
    </div>
  );
}
