'use client';

/**
 * The composer's editor and tool row, as the design draws them (inbox-hs.js renderComposer,
 * toolsRow, fmtRow, emojiPop, linkPop, insertMenu): a formatted-text box, the formatting row,
 * emoji, link, image, attach and the "Insert" menu. Used by the reply box and New email. HUB-366.
 */
import Link from 'next/link';
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
  type RefObject,
} from 'react';
import { htmlIsEmpty } from '@/components/crm/ComposeRichText';
import { useToast } from '@/components/crm/ToastProvider';
import { applySnippet, type Snippet, type SnippetTarget } from '@/features/snippets/api.client';
import {
  hashQueryBeforeCaret,
  keepInView,
  matchSnippets,
  readySnippet,
  shortcutBeforeCaret,
} from '@/features/snippets/model';
import { SnippetLoadError } from '@/features/snippets/ui/SnippetLoadError';
import { useSnippetList } from '@/features/snippets/ui/useSnippetHash';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { linkHtml } from '../compose';
import { IxIcon, IxPopover, Tri, type IxIconName } from './ix';

const SOON = 'Coming soon';

export interface InboxEditorHandle {
  /** Puts HTML where the caret was last. */
  insertHtml: (html: string) => void;
  /** A formatting command on the selection ("bold", "insertUnorderedList"). */
  run: (command: string, value?: string) => void;
  focus: () => void;
  selectedText: () => string;
}

/**
 * Chrome moves the caret to the start of the line when it turns a line into a list. These
 * commands change no text, so the caret goes back by counting characters. Only when there is
 * text before it on that line: on an empty line (just after Enter) Chrome places it right, and
 * counting characters would put it at the end of the line above.
 */
const MOVES_CARET = /^(insert(Un)?orderedList|justify)/i;
const LINE = /^(ADDRESS|BLOCKQUOTE|DIV|H[1-6]|LI|OL|P|PRE|TABLE|TD|TH|TR|UL)$/;

/** The text before the caret on its own line. */
function textBeforeInLine(root: HTMLElement): string {
  const selection = window.getSelection();
  const focus = selection?.focusNode;
  if (!selection || !focus || !root.contains(focus)) return '';
  let line: Node = focus;
  while (line !== root && !(line instanceof Element && LINE.test(line.tagName))) {
    line = line.parentNode!;
  }
  const range = document.createRange();
  range.selectNodeContents(line);
  range.setEnd(focus, selection.focusOffset);
  let text = '';
  const read = (node: Node) => {
    // a line break, or a block inside the box, starts a new line
    if (node instanceof Element && (node.tagName === 'BR' || LINE.test(node.tagName))) text = '';
    if (node.nodeType === Node.TEXT_NODE) text += node.textContent ?? '';
    node.childNodes.forEach(read);
  };
  read(range.cloneContents());
  return text;
}

function caretOffset(root: HTMLElement): number | null {
  const selection = window.getSelection();
  if (!selection?.rangeCount || !root.contains(selection.focusNode)) return null;
  const range = document.createRange();
  range.selectNodeContents(root);
  range.setEnd(selection.focusNode!, selection.focusOffset);
  return range.toString().length;
}

function placeCaret(root: HTMLElement, offset: number) {
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  let left = offset;
  for (let node = walker.nextNode(); node; node = walker.nextNode()) {
    const length = node.textContent?.length ?? 0;
    if (left <= length) {
      window.getSelection()?.collapse(node, left);
      return;
    }
    left -= length;
  }
}

/**
 * "#shortcut" snippets while typing (QA #343, as the contact composers have them): a list of the
 * matching ones opens after "#"; arrows move, Enter or Tab puts one in, Esc closes. Typing the
 * whole shortcut and then a space works too.
 */
function useHashSnippets(
  ref: RefObject<HTMLDivElement | null>,
  /** What snippets are filled from; null: this box has no snippets. */
  target: SnippetTarget | null,
  replace: (range: Range, html: string) => void,
) {
  const toast = useToast();
  const [query, setQuery] = useState<string | null>(null);
  const [index, setIndex] = useState(0);
  const { snippets, failed, load } = useSnippetList();
  const matches = query !== null && snippets ? matchSnippets(snippets, query) : [];

  /** The text node and the text before the caret in it. */
  const atCaret = () => {
    const selection = window.getSelection();
    const node = selection?.anchorNode;
    if (!selection?.isCollapsed || !node || node.nodeType !== Node.TEXT_NODE) return null;
    if (!ref.current?.contains(node)) return null;
    const offset = selection.anchorOffset;
    return { node: node as Text, offset, before: (node as Text).data.slice(0, offset) };
  };

  const track = () => {
    if (!target) return;
    const caret = atCaret();
    const next = caret ? hashQueryBeforeCaret(caret.before) : null;
    if (next !== null) load();
    if (next !== query) setIndex(0);
    setQuery(next);
  };

  /** Puts `snippet` where "#typed" is, filled for the contact. */
  const insertSnippet = async (
    snippet: Snippet,
    at: { node: Text; offset: number },
    typed: string,
  ) => {
    setQuery(null);
    if (!target) return;
    try {
      const filled = await applySnippet(snippet.id, target);
      const ready = readySnippet(filled);
      const start = at.offset - typed.length - 1;
      // typed over or moved meanwhile: leave it
      if (!ref.current?.contains(at.node) || start < 0) return;
      if (at.node.data.slice(start, at.offset).toLowerCase() !== `#${typed}`) return;
      const range = document.createRange();
      range.setStart(at.node, start);
      range.setEnd(at.node, at.offset);
      replace(range, ready.html);
      if (ready.notice) toast(ready.notice, 'danger', { durationMs: 8000 });
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const pick = (snippet: Snippet) => {
    const caret = atCaret();
    const typed = caret ? hashQueryBeforeCaret(caret.before) : null;
    if (caret && typed !== null) void insertSnippet(snippet, caret, typed);
  };

  /** True when the key was for the snippet list. */
  const onKeyDown = (e: React.KeyboardEvent): boolean => {
    if (!target || query === null) return false;
    if (matches.length && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
      e.preventDefault();
      const step = e.key === 'ArrowDown' ? 1 : matches.length - 1;
      setIndex((i) => (i + step) % matches.length);
      return true;
    }
    if (matches.length && (e.key === 'Enter' || e.key === 'Tab')) {
      e.preventDefault();
      pick(matches[Math.min(index, matches.length - 1)]!);
      return true;
    }
    if (e.key === 'Escape') {
      e.preventDefault();
      setQuery(null);
      return true;
    }
    if (e.key === ' ') {
      const caret = atCaret();
      const typed = caret ? shortcutBeforeCaret(caret.before) : null;
      const exact = snippets?.find((s) => s.shortcut === typed);
      if (caret && typed && exact) {
        e.preventDefault();
        void insertSnippet(exact, caret, typed);
        return true;
      }
      setQuery(null);
    }
    return false;
  };

  const list =
    target && query !== null && (failed || snippets) ? (
      <div className="ix-hash" role="listbox" aria-label="Snippets">
        {failed ? (
          <SnippetLoadError className="ix-none" onRetry={load} />
        ) : matches.length ? (
          matches.map((s, i) => (
            <button
              key={s.id}
              ref={i === index ? keepInView : undefined}
              type="button"
              role="option"
              aria-selected={i === index}
              className={cn('ix-mi', i === index && 'is-cur')}
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => pick(s)}
            >
              {s.name} <small className="ix-muted">#{s.shortcut}</small>
            </button>
          ))
        ) : (
          <p className="ix-none">No snippets match #{query}</p>
        )}
      </div>
    ) : null;

  return { track, onKeyDown, list, close: () => setQuery(null) };
}

export const InboxEditor = forwardRef<
  InboxEditorHandle,
  {
    /** A new value loads `value` into the box; typing does not reload it. */
    resetKey: string;
    value: string;
    onChange: (html: string) => void;
    label: string;
    placeholder: string;
    className?: string;
    onKeyDown?: (e: React.KeyboardEvent<HTMLDivElement>) => void;
    /** A "/" was typed with no key press seen. True: it opened something, so it is removed. */
    onSlash?: () => boolean;
    /** Set to let "#shortcut" put in a snippet, filled from these records. */
    snippetTarget?: SnippetTarget;
  }
>(function InboxEditor(
  { resetKey, value, onChange, label, placeholder, className, onKeyDown, onSlash, snippetTarget },
  handle,
) {
  const ref = useRef<HTMLDivElement>(null);
  const saved = useRef<Range | null>(null);

  useEffect(() => {
    if (ref.current) ref.current.innerHTML = value;
    saved.current = null;
    // only a new resetKey reloads the box: `value` follows what is typed
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [resetKey]);

  const remember = () => {
    const root = ref.current;
    const selection = window.getSelection();
    if (!root || !selection?.rangeCount) return;
    const range = selection.getRangeAt(0);
    if (root.contains(range.commonAncestorContainer)) saved.current = range.cloneRange();
  };

  /** Focuses the box with the caret where it was; at the end when it was never in it. */
  const restore = useCallback(() => {
    const root = ref.current;
    if (!root) return false;
    root.focus();
    const selection = window.getSelection();
    if (!selection) return false;
    let range = saved.current;
    if (!range || !root.contains(range.commonAncestorContainer)) {
      range = document.createRange();
      range.selectNodeContents(root);
      range.collapse(false);
    }
    selection.removeAllRanges();
    selection.addRange(range);
    return true;
  }, []);

  /** Removes the "/" before the caret when it started a word and `open` used it. */
  const takeSlash = (open: () => boolean) => {
    const selection = window.getSelection();
    const node = selection?.anchorNode;
    const at = selection?.anchorOffset ?? 0;
    if (node?.nodeType !== Node.TEXT_NODE || !ref.current?.contains(node)) return;
    const before = (node.textContent ?? '').slice(0, at);
    if (!/(^|\s)\/$/.test(before) || !open()) return;
    (node as Text).deleteData(at - 1, 1);
  };

  const sync = () => {
    const root = ref.current;
    if (!root) return;
    // A box left with only a <br> still shows its placeholder.
    if (root.innerHTML === '<br>') root.innerHTML = '';
    onChange(htmlIsEmpty(root.innerHTML) && !root.querySelector('li') ? '' : root.innerHTML);
    remember();
  };

  useImperativeHandle(handle, () => ({
    insertHtml: (html) => {
      if (!restore()) return;
      document.execCommand('insertHTML', false, html);
      sync();
    },
    run: (command, arg) => {
      const root = ref.current;
      if (!root || !restore()) return;
      const caret = MOVES_CARET.test(command) && textBeforeInLine(root) ? caretOffset(root) : null;
      const text = root.textContent;
      document.execCommand(command, false, arg);
      if (caret !== null && root.textContent === text) placeCaret(root, caret);
      sync();
    },
    focus: () => void restore(),
    selectedText: () => saved.current?.toString() ?? '',
  }));

  const hash = useHashSnippets(ref, snippetTarget ?? null, (range, html) => {
    saved.current = range;
    if (!restore()) return;
    document.execCommand('insertHTML', false, html);
    sync();
  });

  return (
    <>
      <div
        ref={ref}
        className={cn('ix-ed', className)}
        contentEditable
        suppressContentEditableWarning
        role="textbox"
        aria-multiline="true"
        aria-label={label}
        data-ph={placeholder}
        onInput={(e) => {
          const input = e.nativeEvent as InputEvent;
          if (onSlash && input.inputType === 'insertText' && input.data === '/') {
            takeSlash(onSlash);
          }
          sync();
          hash.track();
        }}
        onKeyUp={remember}
        onMouseUp={remember}
        onBlur={() => {
          remember();
          hash.close();
        }}
        onKeyDown={(e) => {
          if (!hash.onKeyDown(e)) onKeyDown?.(e);
        }}
      />
      {hash.list}
    </>
  );
});

/* ------------------------------------------------------------------ the Insert menu */

export interface InsertOption {
  id: string;
  label: string;
  /** What goes into the email, for entries that insert it as it is. */
  html?: string;
  /** A folder, for lists that can be narrowed to one. */
  group?: string | null;
}

/** One entry of "Insert". Without `load` it is not available: `why` says why. */
export interface InsertItem {
  id: string;
  label: string;
  icon: IxIconName;
  why?: string;
  load?: () => Promise<InsertOption[]>;
  onPick?: (option: InsertOption) => void | Promise<void>;
  emptyText?: string;
  manage?: { href: string; label: string };
  /** The list has a search box (and a folder picker when its entries have folders). */
  searchable?: boolean;
}

function InsertMenu({
  anchor,
  items,
  openAt,
  onClose,
}: {
  anchor: HTMLElement | null;
  items: InsertItem[];
  /** Open straight on one entry's list ("/" opens Templates). */
  openAt: string | null;
  onClose: () => void;
}) {
  const [chosen, setChosen] = useState<string | null>(openAt);
  const [options, setOptions] = useState<InsertOption[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [query, setQuery] = useState('');
  const [folder, setFolder] = useState('');
  /** "Try again" after a list that could not load. */
  const [attempt, setAttempt] = useState(0);
  const item = items.find((i) => i.id === chosen && i.load);
  const load = useRef(item?.load);
  load.current = item?.load;

  useEffect(() => {
    setOptions(null);
    setError(null);
    setQuery('');
    setFolder('');
    if (!chosen) return;
    let alive = true;
    load.current?.().then(
      (list) => alive && setOptions(list),
      (err) => alive && setError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [chosen, attempt]);

  const folders = [...new Set((options ?? []).flatMap((o) => o.group ?? []))].sort();
  const needle = query.trim().toLowerCase();
  const shown = (options ?? []).filter(
    (o) => (!folder || o.group === folder) && (!needle || o.label.toLowerCase().includes(needle)),
  );

  return (
    <IxPopover
      // its size changes with the list: placed again each time
      key={`${chosen ?? 'root'}-${options?.length ?? 'loading'}`}
      anchor={anchor}
      onClose={onClose}
      className="ix-pop--insert"
      label="Insert"
      align="right"
    >
      {item ? (
        <>
          <button type="button" className="ix-mi" role="menuitem" onClick={() => setChosen(null)}>
            <IxIcon name="left" className="ix-i--sm" />
            {item.label}
          </button>
          {error ? (
            <div className="ix-none sn-load-error" role="alert">
              <span>
                Could not load {item.label.toLowerCase()}. {error}
              </span>
              <button
                type="button"
                className="sn-load-error__retry"
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => setAttempt((n) => n + 1)}
              >
                Try again
              </button>
            </div>
          ) : options === null ? (
            <p className="ix-none">Loading…</p>
          ) : options.length === 0 ? (
            <p className="ix-none">{item.emptyText ?? 'Nothing to insert'}</p>
          ) : (
            [
              item.searchable ? (
                <div key="filters" style={{ display: 'flex', gap: 6, padding: '4px 12px' }}>
                  <input
                    className="input"
                    type="search"
                    aria-label={`Search ${item.label}`}
                    placeholder="Search"
                    autoFocus
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    onKeyDown={(e) => {
                      // inside the composer's form: Enter must not submit it
                      if (e.key === 'Enter') e.preventDefault();
                    }}
                  />
                  {folders.length ? (
                    <select
                      className="input"
                      aria-label="Folder"
                      value={folder}
                      onChange={(e) => setFolder(e.target.value)}
                    >
                      <option value="">All folders</option>
                      {folders.map((name) => (
                        <option key={name} value={name}>
                          {name}
                        </option>
                      ))}
                    </select>
                  ) : null}
                </div>
              ) : null,
              shown.length === 0 ? (
                <p key="none" className="ix-none">
                  No matches
                </p>
              ) : null,
              ...shown.map((option) => (
                <button
                  key={option.id}
                  type="button"
                  className="ix-mi"
                  role="menuitem"
                  // keeps the caret in the email, so it goes where the user was typing
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => {
                    onClose();
                    void item.onPick?.(option);
                  }}
                >
                  {option.label}
                </button>
              )),
            ]
          )}
          {item.manage ? (
            <Link className="ix-mi" role="menuitem" href={item.manage.href}>
              {item.manage.label}
            </Link>
          ) : null}
        </>
      ) : (
        items.map((i) => (
          <button
            key={i.id}
            type="button"
            className="ix-mi ix-mi--sub"
            role="menuitem"
            disabled={!i.load}
            title={i.why}
            onMouseDown={(e) => e.preventDefault()}
            onClick={() => setChosen(i.id)}
          >
            <IxIcon name={i.icon} className="ix-i--sm" />
            {i.label}
            <IxIcon name="right" className="ix-i--sm ix-mi__go" />
          </button>
        ))
      )}
    </IxPopover>
  );
}

/* ------------------------------------------------------------------ the tool row */

const EMOJI = [
  '😀', '😊', '😉', '😂', '🙂', '😍', '🤔', '😅',
  '👍', '👎', '👏', '🙏', '👋', '💪', '🤝', '✌️',
  '🎉', '✨', '🔥', '⭐', '✅', '❌', '❗', '❓',
  '📌', '📎', '📅', '⏰', '📞', '✉️', '💡', '🚀',
]; // prettier-ignore

const COLORS = [
  '#33475b',
  '#000000',
  '#d92d20',
  '#e8603c',
  '#f5a524',
  '#12b76a',
  '#0091ae',
  '#2456e6',
  '#7a5af8',
  '#c2185b',
];

/** A 2 x 2 table with its borders written in, as email programs need them. */
const TABLE_CELL = '<td style="border:1px solid #cbd6e2;padding:6px 10px;min-width:90px"><br></td>';
const TABLE_HTML =
  '<table style="border-collapse:collapse;margin:8px 0"><tbody>' +
  `<tr>${TABLE_CELL}${TABLE_CELL}</tr><tr>${TABLE_CELL}${TABLE_CELL}</tr>` +
  '</tbody></table><p><br></p>';

const FONTS = [
  ['Lexend, Arial, sans-serif', 'Sans Serif'],
  ['Georgia, serif', 'Serif'],
  ['Menlo, monospace', 'Monospace'],
] as const;

const SIZES = [
  ['2', '9'],
  ['3', '11'],
  ['4', '14'],
  ['5', '18'],
  ['6', '24'],
] as const;

type ToolMenu = 'emoji' | 'link' | 'color' | 'align' | 'insert';

export function InboxTools({
  editor,
  disabled,
  onImage,
  onAttach,
  insert,
  insertOpenAt,
  onInsertClosed,
}: {
  editor: RefObject<InboxEditorHandle | null>;
  disabled: boolean;
  /** Absent: the row has no image button (the design's New email). */
  onImage?: () => void;
  onAttach?: () => void;
  insert: InsertItem[];
  /** Set to open "Insert" from outside, on this entry. */
  insertOpenAt?: string | null;
  onInsertClosed?: () => void;
}) {
  const [formatting, setFormatting] = useState(false);
  const [menu, setMenu] = useState<ToolMenu | null>(null);
  const [linkText, setLinkText] = useState('');
  const [linkUrl, setLinkUrl] = useState('https://');
  const [linkError, setLinkError] = useState<string | null>(null);
  const anchor = useRef<HTMLElement | null>(null);
  const insertRef = useRef<HTMLButtonElement>(null);

  const close = useCallback(() => {
    setMenu(null);
    onInsertClosed?.();
  }, [onInsertClosed]);

  const openAt = (name: ToolMenu) => (e: React.MouseEvent<HTMLButtonElement>) => {
    anchor.current = e.currentTarget;
    if (menu === name) close();
    else setMenu(name);
  };
  const keepCaret = (e: React.MouseEvent) => e.preventDefault();
  const run = (command: string, value?: string) => editor.current?.run(command, value);

  const showInsert = !disabled && (menu === 'insert' || !!insertOpenAt);

  const button = (
    icon: IxIconName,
    label: string,
    onClick: (e: React.MouseEvent<HTMLButtonElement>) => void,
    options: { on?: boolean; off?: boolean; why?: string; className?: string } = {},
  ) => (
    <button
      type="button"
      className={cn('ix-icon ix-tip', options.on && 'is-on', options.className)}
      data-tip={options.why ?? label}
      aria-label={label}
      aria-pressed={options.on}
      disabled={disabled || options.off}
      onMouseDown={keepCaret}
      onClick={onClick}
    >
      <IxIcon name={icon} className="ix-i--sm" />
    </button>
  );

  const addLink = () => {
    let url = linkUrl.trim();
    if (/^www\./i.test(url)) url = `https://${url}`;
    if (!/^(https?:\/\/|mailto:)[^\s]+$/i.test(url)) {
      setLinkError('Enter a link that starts with https://');
      return;
    }
    close();
    editor.current?.insertHtml(linkHtml(url, linkText.trim() || url));
  };

  return (
    <>
      {formatting && !disabled ? (
        <div className="ix-fmt" role="toolbar" aria-label="Formatting">
          {button('bold', 'Bold', () => run('bold'))}
          {button('italic', 'Italic', () => run('italic'))}
          {button('under', 'Underline', () => run('underline'))}
          {button('strike', 'Strikethrough', () => run('strikeThrough'))}
          <span className="ix-select ix-select--plain">
            <select
              aria-label="Font"
              defaultValue={FONTS[0][0]}
              onChange={(e) => run('fontName', e.target.value)}
            >
              {FONTS.map(([value, name]) => (
                <option key={name} value={value}>
                  {name}
                </option>
              ))}
            </select>
            <Tri />
          </span>
          <span className="ix-select ix-select--plain">
            <select
              aria-label="Font size"
              defaultValue="3"
              onChange={(e) => run('fontSize', e.target.value)}
            >
              {SIZES.map(([value, name]) => (
                <option key={name} value={value}>
                  {name}
                </option>
              ))}
            </select>
            <Tri />
          </span>
          <button
            type="button"
            className="ix-icon ix-tip"
            data-a="color"
            data-tip="Text color"
            aria-label="Text color"
            onMouseDown={keepCaret}
            onClick={openAt('color')}
          >
            <span className="ix-colA">A</span>
            <Tri />
          </button>
          {button('ul', 'Bulleted list', () => run('insertUnorderedList'))}
          {button('ol', 'Numbered list', () => run('insertOrderedList'))}
          {button('align', 'Alignment', openAt('align'))}
          {button('tpl', 'Insert table', () => editor.current?.insertHtml(TABLE_HTML))}
          {button('clear', 'Clear formatting', () => run('removeFormat'))}
        </div>
      ) : null}

      <div className="ix-tools" role="toolbar" aria-label="Message tools">
        {button(
          'format',
          formatting ? 'Hide formatting options' : 'Show formatting options',
          () => setFormatting((v) => !v),
          { on: formatting },
        )}
        {button('emoji', 'Insert emoji', openAt('emoji'))}
        {button('link', 'Insert link', (e) => {
          setLinkText(editor.current?.selectedText() ?? '');
          setLinkUrl('https://');
          setLinkError(null);
          openAt('link')(e);
        })}
        {onImage ? button('image', 'Insert image', onImage) : null}
        {onAttach ? button('clip', 'Attach file', onAttach) : null}
        {button('spark', 'AI assistant', () => {}, {
          off: true,
          why: `AI assistant: ${SOON.toLowerCase()}`,
          className: 'ix-ai',
        })}
        <button
          ref={insertRef}
          type="button"
          className="ix-insert"
          aria-haspopup="menu"
          aria-expanded={showInsert}
          disabled={disabled}
          onMouseDown={keepCaret}
          onClick={openAt('insert')}
        >
          Insert
          <Tri />
        </button>
      </div>

      {menu === 'emoji' ? (
        <IxPopover
          anchor={anchor.current}
          onClose={close}
          className="ix-pop--emoji"
          role="dialog"
          label="Emoji"
        >
          <div className="ix-emoji" role="listbox" aria-label="Emoji">
            {EMOJI.map((emoji) => (
              <button
                key={emoji}
                type="button"
                role="option"
                aria-selected={false}
                aria-label={emoji}
                onMouseDown={keepCaret}
                onClick={() => {
                  close();
                  editor.current?.insertHtml(emoji);
                }}
              >
                {emoji}
              </button>
            ))}
          </div>
        </IxPopover>
      ) : null}

      {menu === 'link' ? (
        <IxPopover anchor={anchor.current} onClose={close} role="dialog" label="Insert link">
          {/* not a <form>: the composer around it is one already */}
          <div
            className="ix-linkf"
            style={{ padding: '6px 14px', width: 300 }}
            onKeyDown={(e) => {
              if (e.key !== 'Enter') return;
              e.preventDefault();
              addLink();
            }}
          >
            <label className="ix-f">
              <span>Link text</span>
              <input
                className="input"
                value={linkText}
                onChange={(e) => setLinkText(e.target.value)}
              />
            </label>
            <label className="ix-f">
              <span>URL</span>
              <input
                className="input"
                type="url"
                placeholder="https://"
                autoFocus
                value={linkUrl}
                onChange={(e) => setLinkUrl(e.target.value)}
              />
              {linkError ? <small className="crm-text-danger">{linkError}</small> : null}
            </label>
            <div className="ix-linkf__a">
              <button
                type="button"
                className="btn-crm btn-crm--primary btn-crm--sm"
                onClick={addLink}
              >
                Insert
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={close}
              >
                Cancel
              </button>
            </div>
          </div>
        </IxPopover>
      ) : null}

      {menu === 'color' ? (
        <IxPopover anchor={anchor.current} onClose={close} role="dialog" label="Text color">
          <div className="ix-emoji" role="listbox" aria-label="Text color">
            {COLORS.map((color) => (
              <button
                key={color}
                type="button"
                role="option"
                aria-selected={false}
                aria-label={color}
                onMouseDown={keepCaret}
                onClick={() => {
                  close();
                  run('foreColor', color);
                }}
              >
                <span
                  style={{
                    display: 'inline-block',
                    width: 18,
                    height: 18,
                    borderRadius: '50%',
                    background: color,
                  }}
                />
              </button>
            ))}
          </div>
        </IxPopover>
      ) : null}

      {menu === 'align' ? (
        <IxPopover anchor={anchor.current} onClose={close} label="Alignment">
          {(
            [
              ['justifyLeft', 'Align left'],
              ['justifyCenter', 'Align center'],
              ['justifyRight', 'Align right'],
            ] as const
          ).map(([command, name]) => (
            <button
              key={command}
              type="button"
              role="menuitem"
              className="ix-mi"
              onMouseDown={keepCaret}
              onClick={() => {
                close();
                run(command);
              }}
            >
              {name}
            </button>
          ))}
        </IxPopover>
      ) : null}

      {showInsert ? (
        <InsertMenu
          anchor={insertRef.current}
          items={insert}
          openAt={insertOpenAt ?? null}
          onClose={close}
        />
      ) : null}
    </>
  );
}
