'use client';

/**
 * Building blocks of the Data Model page, ported from data-model.js (dropdown system, checkbox
 * filters, DataTable, drawer, modal, tooltips). Markup and class names follow the prototype so
 * public/crm/assets/css/data-model.css styles them unchanged.
 */
import Link from 'next/link';
import {
  Fragment,
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type ReactNode,
} from 'react';
import { createPortal } from 'react-dom';
import { useFocusTrap } from '@/lib/hooks/useFocusTrap';
import { cn } from '@/lib/utils/cn';
import { byText } from '../model';
import { DmIcon } from './icons';

/* ================================================================ dropdown */

/** Places a fixed menu under (or above) its button, inside the viewport (placeMenu). */
function placeMenu(toggle: HTMLElement, menu: HTMLElement, right: boolean, matchWidth: boolean) {
  const r = toggle.getBoundingClientRect();
  const vw = document.documentElement.clientWidth || window.innerWidth;
  menu.style.top = '0px';
  menu.style.left = '0px';
  menu.style.maxWidth = `${vw - 16}px`;
  if (matchWidth) menu.style.width = `${Math.min(vw - 16, Math.max(r.width, 220))}px`;
  // Up to 520px, so a long row menu (Manage table) shows all its items without scrolling.
  menu.style.maxHeight = `${Math.max(160, Math.min(520, Math.max(window.innerHeight - r.bottom - 14, r.top - 14)))}px`;
  const mw = menu.offsetWidth;
  const mh = menu.offsetHeight;
  let left = right ? r.right - mw : r.left;
  if (left + mw > vw - 8) left = vw - mw - 8;
  if (left < 8) left = 8;
  let top = r.bottom + 6;
  if (top + mh > window.innerHeight - 8 && r.top - mh - 6 > 8) top = r.top - mh - 6;
  menu.style.left = `${left}px`;
  menu.style.top = `${top}px`;
}

export function Dropdown({
  label,
  btnClass,
  className,
  menuClass,
  right = false,
  matchWidth = false,
  ariaLabel,
  disabled,
  title,
  role = 'menu',
  children,
}: {
  label: ReactNode;
  btnClass: string;
  className?: string;
  menuClass?: string;
  right?: boolean;
  /** Select-style menus are as wide as their button. */
  matchWidth?: boolean;
  ariaLabel?: string;
  disabled?: boolean;
  title?: string;
  role?: 'menu' | 'listbox' | 'dialog';
  children: (close: () => void) => ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const toggleRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const openedAt = useRef(0);
  const close = useCallback(() => setOpen(false), []);

  useLayoutEffect(() => {
    if (!open || !toggleRef.current || !menuRef.current) return;
    placeMenu(toggleRef.current, menuRef.current, right, matchWidth);
    openedAt.current = Date.now();
    menuRef.current
      .querySelector<HTMLInputElement>('input[type="search"]')
      ?.focus({ preventScroll: true });
  }, [open, right, matchWidth]);

  useEffect(() => {
    if (!open) return;
    const inside = (t: EventTarget | null) =>
      t instanceof Node && (menuRef.current?.contains(t) || toggleRef.current?.contains(t));
    const onDown = (e: MouseEvent) => {
      if (!inside(e.target)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        setOpen(false);
        toggleRef.current?.focus();
      }
    };
    const onScroll = (e: Event) => {
      if (inside(e.target)) return;
      // the browser scrolls while a menu opens
      if (Date.now() - openedAt.current < 400) return;
      setOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey, true);
    document.addEventListener('scroll', onScroll, true);
    window.addEventListener('resize', close);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey, true);
      document.removeEventListener('scroll', onScroll, true);
      window.removeEventListener('resize', close);
    };
  }, [open, close]);

  return (
    <div className={cn('dm-dd', className)}>
      <button
        ref={toggleRef}
        type="button"
        className={btnClass}
        aria-haspopup={role === 'menu' ? 'true' : role}
        aria-expanded={open}
        aria-label={ariaLabel}
        title={title}
        disabled={disabled}
        onClick={() => setOpen((v) => !v)}
      >
        {label}
      </button>
      {open &&
        createPortal(
          <div
            ref={menuRef}
            className={cn('dm-pop', menuClass, right && 'dm-pop--right')}
            role={role}
            style={{ position: 'fixed' }}
          >
            {children(close)}
          </div>,
          document.body,
        )}
    </div>
  );
}

export interface MenuItem {
  label?: string;
  icon?: string;
  onClick?: () => void;
  href?: string;
  disabled?: boolean;
  divider?: boolean;
  external?: boolean;
  /** Tooltip, e.g. why an item is disabled. */
  title?: string;
}

/** An action menu ("..." on rows, "More", "Manage object"). */
export function ActionMenu({
  label,
  btnClass,
  items,
  right,
  ariaLabel,
}: {
  label: ReactNode;
  btnClass: string;
  items: MenuItem[];
  right?: boolean;
  ariaLabel?: string;
}) {
  return (
    <Dropdown
      label={label}
      btnClass={btnClass}
      menuClass="dm-menu"
      right={right}
      ariaLabel={ariaLabel}
    >
      {(close) =>
        items.map((it, i) => {
          if (it.divider) return <div key={i} className="dm-menu__div" role="separator" />;
          const inner = (
            <>
              {it.icon && <DmIcon name={it.icon} />}
              <span>{it.label}</span>
              {it.external && <DmIcon name="external" size={14} />}
            </>
          );
          if (it.href && !it.disabled) {
            return (
              <Link
                key={i}
                className="dm-menu__item"
                role="menuitem"
                href={it.href}
                onClick={close}
              >
                {inner}
              </Link>
            );
          }
          return (
            <button
              key={i}
              type="button"
              role="menuitem"
              className={cn('dm-menu__item', it.disabled && 'is-disabled')}
              aria-disabled={it.disabled || undefined}
              title={it.title}
              onClick={() => {
                if (it.disabled) return;
                close();
                it.onClick?.();
              }}
            >
              {inner}
            </button>
          );
        })
      }
    </Dropdown>
  );
}

/** A select-style dropdown (one value). */
export function SelectMenu<V extends string>({
  value,
  options,
  onChange,
  placeholder = 'Select',
  search,
  className,
  btnClass = 'dm-select__btn',
  ariaLabel,
  disabled,
  icon,
}: {
  value: V | '';
  /**
   * A disabled option is listed but can't be picked; `title` says why. DMG6: `group` puts a
   * heading above the options of that group ("Supported", "Unsupported").
   */
  options: Array<{ value: V; label: string; disabled?: boolean; title?: string; group?: string }>;
  onChange: (value: V) => void;
  placeholder?: string;
  search?: boolean;
  className?: string;
  btnClass?: string;
  ariaLabel?: string;
  disabled?: boolean;
  icon?: (value: V) => ReactNode;
}) {
  const [q, setQ] = useState('');
  const cur = options.find((o) => o.value === value);
  const shown = q
    ? options.filter((o) => o.label.toLowerCase().includes(q.toLowerCase()))
    : options;
  return (
    <Dropdown
      className={cn('dm-select', className)}
      btnClass={btnClass}
      menuClass="dm-menu dm-menu--select"
      matchWidth
      role="listbox"
      ariaLabel={ariaLabel}
      disabled={disabled}
      label={
        <>
          <span className={cur ? undefined : 'dm-muted'}>
            {cur && icon?.(cur.value)}
            {cur ? cur.label : placeholder}
          </span>
          <DmIcon name="caret" size={18} />
        </>
      }
    >
      {(close) => (
        <>
          {search && (
            <label className="dm-pop__search">
              <input
                type="search"
                placeholder="Search"
                aria-label="Search"
                value={q}
                autoFocus
                onChange={(e) => setQ(e.target.value)}
                onKeyDown={(e) => {
                  // Enter picks the first match, as HubSpot's pickers do.
                  const first = shown.find((o) => !o.disabled);
                  if (e.key === 'Enter' && first) {
                    e.preventDefault();
                    close();
                    setQ('');
                    onChange(first.value);
                  }
                }}
              />
              <DmIcon name="search" />
            </label>
          )}
          {shown.map((o, i) => (
            <Fragment key={o.value}>
              {o.group && o.group !== shown[i - 1]?.group && (
                <p className="dm-menu__head">{o.group}</p>
              )}
              <button
                type="button"
                role="option"
                aria-selected={o.value === value}
                aria-disabled={o.disabled || undefined}
                disabled={o.disabled}
                title={o.title}
                className={cn(
                  'dm-menu__item',
                  o.value === value && 'is-selected',
                  o.disabled && 'is-disabled',
                )}
                onClick={() => {
                  close();
                  setQ('');
                  onChange(o.value);
                }}
              >
                {icon?.(o.value)}
                <span>{o.label}</span>
              </button>
            </Fragment>
          ))}
          {!shown.length && <p className="dm-pop__empty">No results</p>}
        </>
      )}
    </Dropdown>
  );
}

/* ================================================================ checkbox filter */

export interface CheckOption {
  value: string;
  label: string;
  count?: number;
  /** Options with a group get a group head that checks them all. */
  group?: string;
}

/** Checkbox filter dropdown (checkDD + bindChecks). */
export function CheckFilter({
  label,
  options,
  selected,
  onChange,
  search,
  selectAll,
  wide,
  clear,
  chip,
  max,
  onMax,
  footer,
  className,
  btnClass = 'dm-filter__btn',
}: {
  label: string;
  options: CheckOption[];
  selected: string[];
  onChange: (next: string[]) => void;
  search?: boolean;
  selectAll?: boolean;
  wide?: boolean;
  /** An x clears the filter. */
  clear?: boolean;
  /** Grey background while something is chosen. */
  chip?: boolean;
  max?: number;
  onMax?: () => void;
  footer?: (close: () => void) => ReactNode;
  className?: string;
  btnClass?: string;
}) {
  const [q, setQ] = useState('');
  const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
  const query = q.trim().toLowerCase();
  const shown = query ? options.filter((o) => o.label.toLowerCase().includes(query)) : options;
  const groups = useMemo(
    () => [...new Set(options.map((o) => o.group).filter((g): g is string => Boolean(g)))],
    [options],
  );
  const set = new Set(selected);
  const toggle = (value: string, on: boolean) => {
    const next = new Set(selected);
    if (on) next.add(value);
    else next.delete(value);
    if (max && next.size > max) {
      onMax?.();
      return;
    }
    onChange(options.map((o) => o.value).filter((v) => next.has(v)));
  };
  const setMany = (values: string[], on: boolean) => {
    const next = new Set(selected);
    values.forEach((v) => (on ? next.add(v) : next.delete(v)));
    onChange(options.map((o) => o.value).filter((v) => next.has(v)));
  };
  const row = (o: CheckOption) => (
    <label
      key={o.value}
      className={cn(
        'dm-check',
        o.group && 'dm-check--indent',
        o.group && collapsed[o.group] && !query && 'is-collapsed',
      )}
    >
      <input
        type="checkbox"
        checked={set.has(o.value)}
        onChange={(e) => toggle(o.value, e.target.checked)}
      />
      <span>
        {o.label}
        {o.count !== undefined && ` (${o.count})`}
      </span>
    </label>
  );
  return (
    <div className={cn('dm-filter-wrap')} style={{ display: 'inline-flex' }}>
      <Dropdown
        className={cn('dm-filter', chip && selected.length > 0 && 'has-value', className)}
        btnClass={btnClass}
        menuClass={cn('dm-checks', wide && 'dm-checks--wide')}
        role="dialog"
        label={
          <>
            <span>{label}</span>
            <DmIcon name="caret" />
          </>
        }
      >
        {(close) => (
          <>
            {search && (
              <label className="dm-pop__search">
                <input
                  type="search"
                  placeholder="Search"
                  aria-label="Search"
                  value={q}
                  onChange={(e) => setQ(e.target.value)}
                />
                <DmIcon name="search" />
              </label>
            )}
            <div className="dm-checks__list">
              {selectAll && !query && (
                <label className="dm-check dm-check--strong">
                  <input
                    type="checkbox"
                    checked={options.length > 0 && selected.length === options.length}
                    onChange={(e) =>
                      setMany(
                        options.map((o) => o.value),
                        e.target.checked,
                      )
                    }
                  />
                  <span>Select all</span>
                </label>
              )}
              {groups.length && !query
                ? groups.map((g) => {
                    const members = options.filter((o) => o.group === g);
                    return (
                      <div key={g}>
                        <div className="dm-check-group">
                          <label className="dm-check dm-check--strong">
                            <input
                              type="checkbox"
                              checked={members.length > 0 && members.every((m) => set.has(m.value))}
                              onChange={(e) =>
                                setMany(
                                  members.map((m) => m.value),
                                  e.target.checked,
                                )
                              }
                            />
                            <span>{g}</span>
                          </label>
                          <button
                            type="button"
                            className={cn('dm-check-group__caret', collapsed[g] && 'is-collapsed')}
                            aria-label={`${collapsed[g] ? 'Expand' : 'Collapse'} ${g}`}
                            onClick={() => setCollapsed((c) => ({ ...c, [g]: !c[g] }))}
                          >
                            <DmIcon name="caret" size={14} />
                          </button>
                        </div>
                        {members.map(row)}
                      </div>
                    );
                  })
                : shown.map(row)}
              {!shown.length && <p className="dm-pop__empty">No results</p>}
            </div>
            {footer?.(close)}
          </>
        )}
      </Dropdown>
      {clear && selected.length > 0 && (
        <button
          type="button"
          className="dm-filter__clear"
          aria-label={`Clear ${label} filter`}
          onClick={() => onChange([])}
        >
          <DmIcon name="x" size={14} />
        </button>
      )}
    </div>
  );
}

/** "(2) Field type" while something is chosen. */
export const countLabel = (name: string, selected: string[]) =>
  selected.length ? `(${selected.length}) ${name}` : name;

/* ================================================================ data table */

export interface Column<T> {
  key: string;
  label: ReactNode;
  sort?: boolean;
  /** Sort value; default: row[key]. */
  val?: (row: T) => string | number | null;
  render?: (row: T) => ReactNode;
  width?: string;
  cls?: string;
}

export function DataTable<T>({
  rows,
  cols,
  rowKey,
  sortKey: initialSort = null,
  sortDir: initialDir = 1,
  size: initialSize = 10,
  sizes = [10, 20, 50, 100],
  pager = true,
  empty = 'No results',
  tableCls,
  wrapCls,
  rowCls,
  initialPage = 1,
  frozen = 0,
  head,
  onPageKeys,
}: {
  rows: T[];
  cols: Column<T>[];
  rowKey: (row: T) => string;
  sortKey?: string | null;
  sortDir?: 1 | -1;
  size?: number;
  sizes?: number[];
  pager?: boolean;
  empty?: ReactNode;
  tableCls?: string;
  wrapCls?: string;
  rowCls?: (row: T) => string | undefined;
  initialPage?: number;
  /**
   * DMG3 (user's call, beyond the design): the first `frozen` columns stay put while the table
   * scrolls sideways (Edit columns › Frozen columns). 0, the default, freezes nothing.
   */
  frozen?: number;
  /**
   * DMG6: a header row to show instead of the columns' (the design's "N selected · Delete"
   * bulk header); none, the default, keeps them.
   */
  head?: ReactNode;
  /** DMG4: the keys of the rows on the page shown, whenever they change (select-this-page). */
  onPageKeys?: (keys: string[]) => void;
}) {
  const [sortKey, setSortKey] = useState(initialSort);
  const [dir, setDir] = useState<1 | -1>(initialDir);
  const [page, setPage] = useState(initialPage);
  const [size, setSize] = useState(initialSize);
  const wrapRef = useRef<HTMLDivElement>(null);
  const tableRef = useRef<HTMLTableElement>(null);

  // Each frozen column's left offset: the widths of the frozen columns before it, measured.
  const frozenN = Math.max(0, Math.min(frozen, cols.length));
  const [lefts, setLefts] = useState<number[]>([]);
  const colsSig = cols.map((c) => c.key).join();
  useLayoutEffect(() => {
    const table = tableRef.current;
    if (!table || frozenN === 0) {
      setLefts((cur) => (cur.length ? [] : cur));
      return;
    }
    const measure = () => {
      const ths = Array.from(table.querySelectorAll<HTMLElement>('thead tr > th'));
      const out: number[] = [];
      let left = 0;
      for (let i = 0; i < frozenN && i < ths.length; i += 1) {
        out.push(left);
        left += ths[i]!.offsetWidth;
      }
      setLefts((cur) => (cur.join() === out.join() ? cur : out));
    };
    measure();
    if (typeof ResizeObserver === 'undefined') return;
    // The frozen headers too: columns can share the width out anew (another page's text) while
    // the table keeps its size.
    const ro = new ResizeObserver(measure);
    ro.observe(table);
    Array.from(table.querySelectorAll<HTMLElement>('thead tr > th'))
      .slice(0, frozenN)
      .forEach((th) => ro.observe(th));
    return () => ro.disconnect();
  }, [frozenN, colsSig]);
  const stick = (i: number, head: boolean) =>
    i < frozenN && lefts[i] !== undefined
      ? ({ position: 'sticky', left: lefts[i], zIndex: head ? 3 : 2 } as const)
      : undefined;
  const frozenCls = (i: number) =>
    frozenN > 0 && i === frozenN - 1 ? 'is-frozen-edge' : undefined;

  const sorted = useMemo(() => {
    const col = cols.find((c) => c.key === sortKey);
    if (!col) return rows;
    const get = (r: T) => (col.val ? col.val(r) : (r as Record<string, unknown>)[col.key]);
    return [...rows].sort((a, b) => {
      const x = get(a);
      const y = get(b);
      if (typeof x === 'number' || typeof y === 'number')
        return ((Number(x) || 0) - (Number(y) || 0)) * dir;
      return byText(String(x ?? ''), String(y ?? '')) * dir;
    });
  }, [rows, cols, sortKey, dir]);

  const pages = Math.max(1, Math.ceil(sorted.length / size));
  const cur = Math.min(page, pages);
  const slice = pager ? sorted.slice((cur - 1) * size, cur * size) : sorted;
  const pageSig = onPageKeys ? slice.map(rowKey).join('\n') : '';
  useEffect(() => {
    onPageKeys?.(pageSig ? pageSig.split('\n') : []);
    // Only when the rows shown change.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageSig]);
  const go = (p: number) => {
    setPage(p);
    if (wrapRef.current) wrapRef.current.scrollTop = 0;
  };

  const start = Math.max(1, Math.min(cur - 4, pages - 8));
  const end = Math.min(pages, start + 8);
  const nums: number[] = [];
  for (let p = start; p <= end; p++) nums.push(p);

  return (
    <>
      <div ref={wrapRef} className={cn('dm-table-wrap', wrapCls)}>
        <table ref={tableRef} className={cn('dm-table', tableCls)}>
          <thead>
            {head ?? (
              <tr>
                {cols.map((c, ci) => {
                  const active = sortKey === c.key;
                  const s = stick(ci, true);
                  return (
                    <th
                      key={c.key}
                      style={
                        c.width || s ? { ...(c.width && { width: c.width }), ...s } : undefined
                      }
                      className={cn(c.cls, frozenCls(ci)) || undefined}
                    >
                      {c.sort ? (
                        <button
                          type="button"
                          className={cn('dm-th-sort', active && 'is-active')}
                          onClick={() => {
                            if (active) setDir((d) => (d === 1 ? -1 : 1));
                            else {
                              setSortKey(c.key);
                              setDir(1);
                            }
                          }}
                        >
                          {c.label}
                          <DmIcon
                            name={active ? (dir === 1 ? 'arrow-up' : 'arrow-down') : 'sort'}
                            size={14}
                          />
                        </button>
                      ) : (
                        c.label
                      )}
                    </th>
                  );
                })}
              </tr>
            )}
          </thead>
          <tbody>
            {!slice.length && (
              <tr className="dm-table__empty">
                <td colSpan={cols.length}>{empty}</td>
              </tr>
            )}
            {slice.map((r) => (
              <tr key={rowKey(r)} className={rowCls?.(r)}>
                {cols.map((c, ci) => (
                  <td
                    key={c.key}
                    className={cn(c.cls, frozenCls(ci)) || undefined}
                    style={stick(ci, false)}
                  >
                    {c.render ? c.render(r) : String((r as Record<string, unknown>)[c.key] ?? '')}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {pager && (
        <nav className="dm-pager" aria-label="Pagination">
          <button
            type="button"
            className="dm-pager__step"
            disabled={cur <= 1}
            onClick={() => go(cur - 1)}
          >
            <DmIcon name="chevron-left" size={14} />
            Prev
          </button>
          {nums.map((p) => (
            <button
              key={p}
              type="button"
              className={cn('dm-pager__num', p === cur && 'is-current')}
              aria-current={p === cur ? 'page' : undefined}
              onClick={() => go(p)}
            >
              {p}
            </button>
          ))}
          <button
            type="button"
            className="dm-pager__step"
            disabled={cur >= pages}
            onClick={() => go(cur + 1)}
          >
            Next
            <DmIcon name="chevron-right" size={14} />
          </button>
          <Dropdown
            btnClass="dm-pager__size"
            menuClass="dm-menu"
            label={
              <>
                {size} per page
                <DmIcon name="caret" />
              </>
            }
          >
            {(close) =>
              sizes.map((s) => (
                <button
                  key={s}
                  type="button"
                  className={cn('dm-menu__item', s === size && 'is-selected')}
                  onClick={() => {
                    close();
                    setSize(s);
                    setPage(1);
                  }}
                >
                  {s} per page
                </button>
              ))
            }
          </Dropdown>
        </nav>
      )}
    </>
  );
}

/* ================================================================ drawer / modal */

/** Right-hand drawer with a backdrop (openDrawer / closeDrawer). */
export function Drawer({
  open,
  onClose,
  label,
  children,
}: {
  open: boolean;
  onClose: () => void;
  label: string;
  children: ReactNode;
}) {
  const [shown, setShown] = useState(open);
  const [entered, setEntered] = useState(false);
  useEffect(() => {
    if (open) {
      setShown(true);
      const id = requestAnimationFrame(() => setEntered(true));
      document.body.classList.add('dm-no-scroll');
      return () => cancelAnimationFrame(id);
    }
    setEntered(false);
    document.body.classList.remove('dm-no-scroll');
    const t = setTimeout(() => setShown(false), 200);
    return () => clearTimeout(t);
  }, [open]);
  useEffect(() => () => document.body.classList.remove('dm-no-scroll'), []);
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !document.querySelector('.dm-modal')) onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!shown) return null;
  return createPortal(
    <>
      <div className={cn('dm-drawer-backdrop', entered && 'is-open')} onClick={onClose} />
      <aside
        className={cn('dm-drawer', entered && 'is-open')}
        role="dialog"
        aria-modal="true"
        aria-label={label}
      >
        {children}
      </aside>
    </>,
    document.body,
  );
}

export function DrawerHead({
  title,
  onClose,
  onBack,
}: {
  title: string;
  onClose: () => void;
  onBack?: () => void;
}) {
  return (
    <div className="dm-drawer__head">
      {onBack && (
        <button
          type="button"
          className="dm-icon-btn dm-co__back"
          aria-label="Back"
          onClick={onBack}
        >
          <DmIcon name="chevron-left" size={20} />
        </button>
      )}
      <h2>{title}</h2>
      <button type="button" className="dm-icon-btn" aria-label="Close" onClick={onClose}>
        <DmIcon name="x" size={20} />
      </button>
    </div>
  );
}

/**
 * Centered dialog (openModal). `onOk` may return false (or a promise of false) to stay open;
 * the OK button is busy while a promise runs.
 */
export function Modal({
  title,
  children,
  okLabel,
  onOk,
  onClose,
  danger,
  okDisabled,
  noCancel,
  cancelLabel = 'Cancel',
  wide,
}: {
  title: string;
  children: ReactNode;
  okLabel: string;
  onOk: () => boolean | void | Promise<boolean | void>;
  onClose: () => void;
  danger?: boolean;
  okDisabled?: boolean;
  noCancel?: boolean;
  cancelLabel?: string;
  /** Room for a table (a pair's labels). */
  wide?: boolean;
}) {
  const [busy, setBusy] = useState(false);
  const boxRef = useRef<HTMLDivElement>(null);
  useFocusTrap(boxRef);
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  const ok = async () => {
    setBusy(true);
    try {
      if ((await onOk()) !== false) onClose();
    } finally {
      setBusy(false);
    }
  };
  return createPortal(
    <div
      className="dm-modal"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        ref={boxRef}
        className={cn('dm-modal__box', wide && 'dm-modal__box--wide')}
        role="dialog"
        aria-modal="true"
        aria-label={title}
      >
        <div className="dm-modal__head">
          <h2>{title}</h2>
          <button type="button" className="dm-icon-btn" aria-label="Close" onClick={onClose}>
            <DmIcon name="x" size={18} />
          </button>
        </div>
        <div className="dm-modal__body">{children}</div>
        <div className="dm-modal__foot">
          <button
            type="button"
            className={cn(
              'dm-btn dm-btn--sm',
              danger ? 'dm-btn--danger' : 'dm-btn--primary',
              busy && 'is-loading',
            )}
            disabled={okDisabled || busy}
            onClick={() => void ok()}
          >
            {okLabel}
          </button>
          {!noCancel && (
            <button type="button" className="dm-btn dm-btn--outline dm-btn--sm" onClick={onClose}>
              {cancelLabel}
            </button>
          )}
        </div>
      </div>
    </div>,
    document.body,
  );
}

/* ================================================================ small bits */

/** Info icon with a dark tooltip (data-tip in the prototype). */
export function Tip({ text, children }: { text: string; children?: ReactNode }) {
  const ref = useRef<HTMLSpanElement>(null);
  const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
  const tipRef = useRef<HTMLDivElement>(null);
  useLayoutEffect(() => {
    if (!pos || !tipRef.current || !ref.current) return;
    const r = ref.current.getBoundingClientRect();
    const t = tipRef.current;
    const left = Math.min(
      window.innerWidth - t.offsetWidth - 8,
      Math.max(8, r.left + r.width / 2 - t.offsetWidth / 2),
    );
    const top = r.top - t.offsetHeight - 8 < 8 ? r.bottom + 8 : r.top - t.offsetHeight - 8;
    if (left !== pos.left || top !== pos.top) setPos({ left, top });
  }, [pos]);
  const show = () => setPos({ left: -9999, top: -9999 });
  const hide = () => setPos(null);
  return (
    <>
      <span
        ref={ref}
        className="dm-tip"
        tabIndex={0}
        aria-label={text}
        onMouseEnter={show}
        onMouseLeave={hide}
        onFocus={show}
        onBlur={hide}
      >
        {children ?? <DmIcon name="info" size={14} />}
      </span>
      {pos &&
        createPortal(
          <div
            ref={tipRef}
            className="dm-tooltip"
            role="tooltip"
            style={{ left: pos.left, top: pos.top }}
          >
            {text}
          </div>,
          document.body,
        )}
    </>
  );
}

export function SearchBox({
  value,
  onChange,
  placeholder,
  wide,
  className,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder: string;
  wide?: boolean;
  className?: string;
}) {
  return (
    <label className={cn('dm-search', wide && 'dm-search--wide', className)}>
      <input
        type="search"
        placeholder={placeholder}
        aria-label={placeholder}
        value={value}
        onChange={(e) => onChange(e.target.value)}
      />
      {/* The browser's own clear button is hidden app-wide (details.css), so this is ours. */}
      {value ? (
        <button
          type="button"
          className="dm-search__clear"
          aria-label="Clear search"
          onClick={() => onChange('')}
        >
          <DmIcon name="x" size={14} />
        </button>
      ) : (
        <DmIcon name="search" />
      )}
    </label>
  );
}

/** View toggle: graph (tree) / table. */
export function ViewToggle({
  view,
  onChange,
}: {
  view: 'graph' | 'table';
  onChange: (v: 'graph' | 'table') => void;
}) {
  return (
    <div className="dm-viewtoggle" role="group" aria-label="View">
      <button
        type="button"
        className={cn('dm-viewtoggle__btn', view === 'graph' && 'is-active')}
        title="Graph view"
        aria-label="Graph view"
        aria-pressed={view === 'graph'}
        onClick={() => onChange('graph')}
      >
        <DmIcon name="tree" />
      </button>
      <button
        type="button"
        className={cn('dm-viewtoggle__btn', view === 'table' && 'is-active')}
        title="Table view"
        aria-label="Table view"
        aria-pressed={view === 'table'}
        onClick={() => onChange('table')}
      >
        <DmIcon name="table" />
      </button>
    </div>
  );
}

/** Zoomable, drag-to-pan canvas with the round controls (zoomable + canvasControls). */
export function Canvas({
  className,
  children,
  legend,
}: {
  className?: string;
  children: ReactNode;
  legend: string;
}) {
  const [z, setZ] = useState(1);
  const [tip, setTip] = useState(false);
  const canvasRef = useRef<HTMLDivElement>(null);
  const down = useRef<{ x: number; y: number; l: number; t: number } | null>(null);
  const [grab, setGrab] = useState(false);
  useEffect(() => {
    const move = (e: MouseEvent) => {
      const c = canvasRef.current;
      if (!down.current || !c) return;
      c.scrollLeft = down.current.l - (e.clientX - down.current.x);
      c.scrollTop = down.current.t - (e.clientY - down.current.y);
    };
    const up = () => {
      down.current = null;
      setGrab(false);
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
    };
  }, []);
  return (
    <div className="dm-canvas-wrap">
      <div
        ref={canvasRef}
        className={cn('dm-canvas', className, grab && 'is-grabbing')}
        onMouseDown={(e) => {
          if ((e.target as HTMLElement).closest('button, a, input')) return;
          const c = canvasRef.current!;
          down.current = { x: e.clientX, y: e.clientY, l: c.scrollLeft, t: c.scrollTop };
          setGrab(true);
        }}
      >
        <div
          className="dm-canvas__inner"
          style={{ transform: `scale(${z})`, width: `${100 / z}%` }}
        >
          {children}
        </div>
      </div>
      <div className="dm-canvas__ctrl">
        <button
          type="button"
          className="dm-round dm-round--sq"
          title="Legend"
          aria-label="Legend"
          aria-expanded={tip}
          onClick={() => setTip((v) => !v)}
        >
          <DmIcon name="info" />
        </button>
        <button
          type="button"
          className="dm-round"
          title="Zoom in"
          aria-label="Zoom in"
          onClick={() => setZ((v) => Math.min(1.6, +(v + 0.1).toFixed(2)))}
        >
          <DmIcon name="zoom-in" />
        </button>
        <button
          type="button"
          className="dm-round"
          title="Zoom out"
          aria-label="Zoom out"
          onClick={() => setZ((v) => Math.max(0.5, +(v - 0.1).toFixed(2)))}
        >
          <DmIcon name="zoom-out" />
        </button>
        <button
          type="button"
          className="dm-round"
          title="Fit to screen"
          aria-label="Fit to screen"
          onClick={() => {
            setZ(1);
            canvasRef.current?.scrollTo(0, 0);
          }}
        >
          <DmIcon name="move" />
        </button>
      </div>
      {tip && (
        <p
          className="dm-canvas__legend"
          role="note"
          style={{
            position: 'absolute',
            right: 64,
            bottom: 20,
            maxWidth: 280,
            margin: 0,
            padding: '8px 12px',
            fontSize: 12.5,
            background: 'var(--surface)',
            border: '1px solid var(--border)',
            borderRadius: 'var(--radius-sm)',
            boxShadow: 'var(--shadow)',
          }}
        >
          {legend}
        </p>
      )}
    </div>
  );
}

/** Accordion item of the usage drawer. */
export function Accordion({ title, children }: { title: string; children: ReactNode }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="dm-acc__item">
      <button
        type="button"
        className={cn('dm-acc__btn', open && 'is-open')}
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}
      >
        <DmIcon name="chevron-right" size={14} />
        {title}
      </button>
      {open && <div className="dm-acc__body">{children}</div>}
    </div>
  );
}
