'use client';

import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
  type ReactNode,
} from 'react';
import { createPortal } from 'react-dom';
import { AnchoredPopover, POPOVER_Z_INDEX } from '@/components/crm/AnchoredPopover';
import { NOT_AVAILABLE_YET } from '@/components/crm/ComposerSelect';
import { isDarkInk, type EmailTextDefaults } from '@/features/settings/emailDefaults';
import { useToast } from '@/components/crm/ToastProvider';
import {
  applySnippet,
  getSnippetByShortcut,
  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 { SnippetMenu } from '@/features/snippets/ui/SnippetMenu';
import { useSnippetList } from '@/features/snippets/ui/useSnippetHash';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

/** True when rich HTML has no visible text. */
export function htmlIsEmpty(html: string): boolean {
  return !html
    .replace(/<br\s*\/?>/gi, '')
    .replace(/&nbsp;/gi, ' ')
    .replace(/[\u200B-\u200D\uFEFF]/g, '')
    .replace(/<[^>]+>/g, '')
    .replace(/[\u200B-\u200D\uFEFF]/g, '')
    .trim();
}

function IconBtn({
  title,
  onClick,
  children,
  active,
  buttonRef,
  disabled,
  className,
}: {
  title: string;
  onClick?: () => void;
  children: React.ReactNode;
  active?: boolean;
  buttonRef?: React.RefObject<HTMLButtonElement | null>;
  disabled?: boolean;
  className?: string;
}) {
  return (
    <button
      ref={buttonRef}
      type="button"
      className={cn('activity-compose__tool', active && 'is-active', className)}
      title={title}
      aria-label={title}
      disabled={disabled}
      onMouseDown={(e) => e.preventDefault()}
      onClick={onClick}
    >
      {children}
    </button>
  );
}

function ToolIcon({ children, filled }: { children: React.ReactNode; filled?: boolean }) {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden
      fill={filled ? 'currentColor' : 'none'}
      stroke={filled ? undefined : 'currentColor'}
      strokeWidth={filled ? undefined : 1.8}
      strokeLinecap={filled ? undefined : 'round'}
      strokeLinejoin={filled ? undefined : 'round'}
    >
      {children}
    </svg>
  );
}

function Caret() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden className="activity-compose__caret">
      <path d="M7 10l5 5 5-5z" fill="currentColor" />
    </svg>
  );
}

const FONTS = [
  { label: 'Sans Serif', value: 'Arial, Helvetica, sans-serif' },
  { label: 'Serif', value: 'Georgia, "Times New Roman", Times, serif' },
  { label: 'Monospace', value: '"Courier New", Courier, monospace' },
  { label: 'Arial', value: 'Arial, Helvetica, sans-serif' },
  { label: 'Georgia', value: 'Georgia, serif' },
  { label: 'Helvetica', value: 'Helvetica, Arial, sans-serif' },
  { label: 'Tahoma', value: 'Tahoma, Verdana, sans-serif' },
  { label: 'Times New Roman', value: '"Times New Roman", Times, serif' },
  { label: 'Trebuchet MS', value: '"Trebuchet MS", Helvetica, sans-serif' },
  { label: 'Verdana', value: 'Verdana, Geneva, sans-serif' },
] as const;

const FONT_SIZES = [8, 9, 10, 11, 12, 14, 18, 24, 36] as const;

const TEXT_COLORS = [
  '#000000',
  '#33475b',
  '#516f90',
  '#7c98b6',
  '#cbd6e2',
  '#ffffff',
  '#f2545b',
  '#ff7a59',
  '#f5c26b',
  '#00bda5',
  '#00a4bd',
  '#0091ae',
  '#6a78d1',
  '#a2a6ff',
  '#c11574',
  '#067647',
] as const;

const HIGHLIGHTS = [
  { label: 'None', value: 'transparent' },
  { label: '#fff3b0', value: '#fff3b0' },
  { label: '#ffe0b2', value: '#ffe0b2' },
  { label: '#ffd6d6', value: '#ffd6d6' },
  { label: '#d4f5e9', value: '#d4f5e9' },
  { label: '#d6ecff', value: '#d6ecff' },
  { label: '#e6dcff', value: '#e6dcff' },
  { label: '#eaf0f6', value: '#eaf0f6' },
] as const;

const ALIGNS = [
  { label: 'Left', command: 'justifyLeft', path: 'M4 6h16M4 10h10M4 14h16M4 18h10' },
  { label: 'Center', command: 'justifyCenter', path: 'M4 6h16M7 10h10M4 14h16M7 18h10' },
  { label: 'Right', command: 'justifyRight', path: 'M4 6h16M10 10h10M4 14h16M10 18h10' },
  { label: 'Justify', command: 'justifyFull', path: 'M4 6h16M4 10h16M4 14h16M4 18h16' },
] as const;

type MoreSub = 'font' | 'size' | 'color' | 'highlight' | 'align' | null;

function escapeHtml(s: string): string {
  return s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

function rangeInside(root: HTMLElement, range: Range): boolean {
  return root.contains(range.commonAncestorContainer);
}

/** The `#query` being typed: where it ends (in `node`) and the caret's place on screen. */
type HashState = {
  node: Text;
  end: number;
  query: string;
  rect: { left: number; top: number; bottom: number };
};

/** The caret's box (a collapsed range has none in some browsers: then its line's). */
function caretRect(range: Range): { left: number; top: number; bottom: number } | null {
  const r = range.getClientRects()[0] ?? range.getBoundingClientRect();
  if (r && (r.height || r.top)) return { left: r.left, top: r.top, bottom: r.bottom };
  const el = range.startContainer.parentElement;
  const box = el?.getBoundingClientRect();
  return box ? { left: box.left, top: box.top, bottom: box.bottom } : null;
}

/** Where the inline snippet list goes: under the caret, or above when there's no room. */
function hashListStyle(rect: HashState['rect'], rows: number): React.CSSProperties {
  const width = 300;
  const height = Math.min(280, Math.max(1, rows) * 44 + 16);
  const below = rect.bottom + 6;
  const top =
    below + height > window.innerHeight - 8 && rect.top - height - 6 > 8
      ? rect.top - height - 6
      : below;
  const left = Math.max(8, Math.min(rect.left, window.innerWidth - width - 8));
  return {
    position: 'fixed',
    top,
    left,
    width,
    maxHeight: 280,
    overflow: 'hidden',
    zIndex: POPOVER_Z_INDEX + 10,
  };
}

export type ComposeRichTextHandle = {
  insertHtml: (html: string) => void;
};

function readDataUrl(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result ?? ''));
    reader.onerror = () => reject(reader.error ?? new Error('Could not read file'));
    reader.readAsDataURL(file);
  });
}

const INLINE_FILE_MAX_BYTES = 3 * 1024 * 1024;

/**
 * Compact rich-text composer for activity popups.
 * Toolbar matches the design: B/I/U/clear, More, link, image, knowledge, snippet, attach, AI.
 * Image/attach always show after Link. Inbox send uses `onPickFile`; other composers inline the file.
 */
export const ComposeRichText = forwardRef<
  ComposeRichTextHandle,
  {
    openKey: number | string;
    value: string;
    onChange: (html: string) => void;
    placeholder?: string;
    label: string;
    minHeight?: number;
    /** When set, image/attach upload via inbox instead of inlining in the body. */
    onPickFile?: (file: File) => void | Promise<void>;
    /** Extra controls on the right of the toolbar (e.g. Associated with). */
    toolbarEnd?: ReactNode;
    /** Adds the snippet tool and "#shortcut", filled from these records. */
    snippetTarget?: SnippetTarget;
    /** Contacts composer: draws the design's tools that have no API yet, turned off. */
    plannedTools?: boolean;
    /** The paperclip hands files here instead of inlining them (several at once). */
    onAttachFiles?: (files: File[]) => void;
    attachDisabled?: boolean;
    /** Account Defaults › User Defaults › Email — base typing style for this editor. */
    textDefaults?: EmailTextDefaults | null;
    /** PB7: no Insert image or Attach file (the playbook dialog's editors, record-playbook.js:209-222). */
    noFiles?: boolean;
  }
>(function ComposeRichText(
  {
    openKey,
    value,
    onChange,
    placeholder,
    label,
    minHeight = 160,
    onPickFile,
    toolbarEnd,
    snippetTarget,
    plannedTools = false,
    onAttachFiles,
    attachDisabled = false,
    textDefaults = null,
    noFiles = false,
  },
  handleRef,
) {
  const ref = useRef<HTMLDivElement>(null);
  const savedRange = useRef<Range | null>(null);
  const imageInputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const moreBtnRef = useRef<HTMLButtonElement>(null);
  const linkBtnRef = useRef<HTMLButtonElement>(null);
  const snippetBtnRef = useRef<HTMLButtonElement>(null);
  const [snippetOpen, setSnippetOpen] = useState(false);
  const [moreOpen, setMoreOpen] = useState(false);
  const [moreSub, setMoreSub] = useState<MoreSub>(null);
  const [fontLabel, setFontLabel] = useState<(typeof FONTS)[number]['label']>('Sans Serif');
  const [fontSize, setFontSize] = useState<(typeof FONT_SIZES)[number]>(11);
  const [linkOpen, setLinkOpen] = useState(false);
  const [linkText, setLinkText] = useState('');
  const [linkUrl, setLinkUrl] = useState('https://');
  const [linkNewTab, setLinkNewTab] = useState(true);
  const [fileBusy, setFileBusy] = useState(false);

  const nearestFontSize = (pt: number): (typeof FONT_SIZES)[number] => {
    let best: (typeof FONT_SIZES)[number] = FONT_SIZES[0]!;
    for (const n of FONT_SIZES) {
      if (Math.abs(n - pt) < Math.abs(best - pt)) best = n;
    }
    return best;
  };

  useEffect(() => {
    if (ref.current) ref.current.innerHTML = value || '';
    setLinkOpen(false);
    setMoreOpen(false);
    setMoreSub(null);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [openKey]);

  useEffect(() => {
    const labelMatch = FONTS.find((f) => f.label === textDefaults?.font)?.label;
    setFontLabel(labelMatch ?? 'Sans Serif');
    setFontSize(textDefaults ? nearestFontSize(textDefaults.fontSizePt) : 11);
  }, [textDefaults?.font, textDefaults?.fontSizePt]);

  const sync = () => onChange(ref.current?.innerHTML ?? '');

  const rememberSelection = () => {
    const root = ref.current;
    const sel = window.getSelection();
    if (!root || !sel || sel.rangeCount === 0) return;
    const range = sel.getRangeAt(0);
    if (!rangeInside(root, range)) {
      savedRange.current = null;
      return;
    }
    savedRange.current = range.cloneRange();
  };

  const restoreSelection = () => {
    const root = ref.current;
    const range = savedRange.current;
    if (!root || !range || !rangeInside(root, range)) return;
    const sel = window.getSelection();
    if (!sel) return;
    sel.removeAllRanges();
    sel.addRange(range);
  };

  const run = (command: string, arg?: string) => {
    ref.current?.focus();
    restoreSelection();
    document.execCommand(command, false, arg);
    sync();
  };

  const insertHtml = useCallback((html: string) => {
    ref.current?.focus();
    restoreSelection();
    document.execCommand('insertHTML', false, html);
    sync();
    // restoreSelection/sync close over the latest refs.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useImperativeHandle(handleRef, () => ({ insertHtml }), [insertHtml]);

  // QA #343: "#shortcut" then Space or Enter puts that snippet in, filled for the contact. While
  // `#` and a word are typed, a list of the matching snippets shows under the caret (arrows move,
  // Enter or Tab inserts, Esc closes).
  const toast = useToast();
  const snippetTargetRef = useRef(snippetTarget);
  snippetTargetRef.current = snippetTarget;
  const [hash, setHash] = useState<HashState | null>(null);
  const [hashIndex, setHashIndex] = useState(0);
  const { snippets: hashSnippets, failed: hashFailed, load: loadHashSnippets } = useSnippetList();
  const hashMatches = hash && hashSnippets ? matchSnippets(hashSnippets, hash.query) : [];

  /** Replaces `#shortcut` (ending at `end` in `node`) with the snippet filled for the record. */
  const insertSnippetAt = async (
    node: Text,
    end: number,
    typed: string,
    snippet: Snippet | null,
  ) => {
    const target = snippetTargetRef.current;
    if (!target) return;
    let filled: { bodyHtml: string; missingFields: string[] };
    try {
      const found = snippet ?? (await getSnippetByShortcut(typed));
      filled = await applySnippet(found.id, target);
    } catch (err) {
      // No snippet has that shortcut: the text stays as typed.
      if (!(isApiError(err) && err.isNotFound)) toast(errorText(err), 'danger');
      return;
    }
    const root = ref.current;
    const start = end - typed.length - 1;
    // Typed over or moved meanwhile: leave it.
    if (
      !root ||
      !root.contains(node) ||
      start < 0 ||
      node.data.slice(start, end).toLowerCase() !== `#${typed}`
    )
      return;
    const ready = readySnippet(filled);
    const range = document.createRange();
    range.setStart(node, start);
    range.setEnd(node, end);
    savedRange.current = range;
    insertHtml(ready.html);
    if (ready.notice) toast(ready.notice, 'danger', { durationMs: 8000 });
  };

  /** After typing: the `#query` before the caret opens (or updates) the inline list. */
  const trackHash = () => {
    if (!snippetTargetRef.current) return;
    const sel = window.getSelection();
    const root = ref.current;
    const r = root && sel?.rangeCount && sel.isCollapsed ? sel.getRangeAt(0) : null;
    const node = r?.startContainer;
    const query =
      r && node && node.nodeType === Node.TEXT_NODE && root?.contains(node)
        ? hashQueryBeforeCaret((node as Text).data.slice(0, r.startOffset))
        : null;
    if (!root || !r || !node || query === null) {
      setHash(null);
      return;
    }
    const rect = caretRect(r) ?? root.getBoundingClientRect();
    loadHashSnippets();
    if (!hash || hash.query !== query) setHashIndex(0);
    setHash({ node: node as Text, end: r.startOffset, query, rect });
  };

  const pickHash = (snippet: Snippet) => {
    const h = hash;
    setHash(null);
    if (h) void insertSnippetAt(h.node, h.end, h.query, snippet);
  };

  const onBodyKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    if (!snippetTarget) return;
    if (hash && hashMatches.length) {
      if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        e.preventDefault();
        const n = hashMatches.length;
        setHashIndex((i) => (i + (e.key === 'ArrowDown' ? 1 : n - 1)) % n);
        return;
      }
      if (e.key === 'Enter' || e.key === 'Tab') {
        e.preventDefault();
        pickHash(hashMatches[Math.min(hashIndex, hashMatches.length - 1)]!);
        return;
      }
    }
    if (hash && e.key === 'Escape') {
      e.preventDefault();
      e.stopPropagation();
      setHash(null);
      return;
    }
    if (e.key !== ' ' && e.key !== 'Enter') return;
    setHash(null);
    const sel = window.getSelection();
    if (!sel || !sel.rangeCount || !sel.isCollapsed) return;
    const r = sel.getRangeAt(0);
    const node = r.startContainer;
    if (node.nodeType !== Node.TEXT_NODE || !ref.current?.contains(node)) return;
    const shortcut = shortcutBeforeCaret((node as Text).data.slice(0, r.startOffset));
    if (shortcut) void insertSnippetAt(node as Text, r.startOffset, shortcut, null);
  };

  useEffect(() => {
    if (!hash) return;
    const close = (e: Event) => {
      // Scrolling the list itself must not close it.
      if (e.target instanceof Element && e.target.closest('[aria-label="Snippets"]')) return;
      setHash(null);
    };
    window.addEventListener('scroll', close, true);
    window.addEventListener('resize', close);
    return () => {
      window.removeEventListener('scroll', close, true);
      window.removeEventListener('resize', close);
    };
  }, [hash]);
  const wrapInline = (style: Record<string, string>) => {
    ref.current?.focus();
    restoreSelection();
    const sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return;
    const range = sel.getRangeAt(0);
    const span = document.createElement('span');
    Object.assign(span.style, style);
    if (range.collapsed) {
      span.appendChild(document.createTextNode('\u200b'));
      range.insertNode(span);
    } else {
      span.appendChild(range.extractContents());
      range.insertNode(span);
    }
    const next = document.createRange();
    next.selectNodeContents(span);
    next.collapse(false);
    sel.removeAllRanges();
    sel.addRange(next);
    savedRange.current = next.cloneRange();
    sync();
  };

  const toggleMoreSub = (key: MoreSub) => {
    rememberSelection();
    setMoreSub((cur) => (cur === key ? null : key));
  };

  const openLinkPopover = () => {
    rememberSelection();
    const sel = window.getSelection();
    const text =
      sel && sel.rangeCount > 0 && ref.current && rangeInside(ref.current, sel.getRangeAt(0))
        ? sel.toString().trim()
        : '';
    setLinkText(text);
    setLinkUrl('https://');
    setLinkNewTab(true);
    setMoreOpen(false);
    setLinkOpen(true);
  };

  const insertLink = () => {
    const url = linkUrl.trim();
    if (!/^https?:\/\//i.test(url)) return;
    const text = (linkText.trim() || url).replace(/</g, '');
    const target = linkNewTab ? ' target="_blank" rel="noopener noreferrer"' : '';
    insertHtml(`<a href="${escapeHtml(url)}"${target}>${escapeHtml(text)}</a>&nbsp;`);
    setLinkOpen(false);
  };

  const handlePickedFile = async (file: File | undefined, kind: 'image' | 'file') => {
    if (!file) return;
    rememberSelection();
    if (onPickFile) {
      setFileBusy(true);
      try {
        await onPickFile(file);
      } finally {
        setFileBusy(false);
      }
      return;
    }
    if (file.size > INLINE_FILE_MAX_BYTES) return;
    setFileBusy(true);
    try {
      const dataUrl = await readDataUrl(file);
      const name = escapeHtml(file.name);
      const isImage = kind === 'image' || file.type.startsWith('image/');
      if (isImage) {
        insertHtml(`<img src="${dataUrl}" alt="${name}" style="max-width:100%;height:auto;">`);
      } else {
        insertHtml(`<p><a href="${dataUrl}" download="${name}">${name}</a></p>`);
      }
    } finally {
      setFileBusy(false);
    }
  };

  const pickImage = () => {
    if (fileBusy) return;
    rememberSelection();
    imageInputRef.current?.click();
  };

  const pickFile = () => {
    if (fileBusy) return;
    rememberSelection();
    fileInputRef.current?.click();
  };

  const tool = (text: string, title: string, command: string, className?: string) => (
    <button
      type="button"
      className={cn('activity-compose__tool', className)}
      title={title}
      aria-label={title}
      onMouseDown={(e) => {
        e.preventDefault();
        rememberSelection();
      }}
      onClick={() => run(command)}
    >
      {text}
    </button>
  );

  return (
    <div className="activity-compose">
      <div
        key={openKey}
        ref={ref}
        className="activity-compose__body"
        data-dark-ink={textDefaults && isDarkInk(textDefaults.color) ? '' : undefined}
        style={{
          minHeight,
          ...(textDefaults
            ? {
                fontFamily: textDefaults.fontFamily,
                fontSize: `${textDefaults.fontSizePt}pt`,
                color: textDefaults.color,
              }
            : null),
        }}
        contentEditable
        role="textbox"
        aria-multiline="true"
        aria-label={label}
        data-placeholder={placeholder}
        suppressContentEditableWarning
        onMouseUp={() => {
          rememberSelection();
          if (hash) trackHash();
        }}
        onKeyUp={(e) => {
          rememberSelection();
          // Caret moved with the keys: the list follows (or closes).
          if (
            hash &&
            (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'Home' || e.key === 'End')
          )
            trackHash();
        }}
        onKeyDown={onBodyKeyDown}
        onInput={() => {
          sync();
          trackHash();
        }}
        onBlur={() => setHash(null)}
      />
      {hash && snippetTarget && (hashFailed || (hashSnippets && (hashMatches.length || hash.query)))
        ? createPortal(
            <div
              className="crm-anchored-popover acx-pop--list"
              role="listbox"
              aria-label="Snippets"
              style={hashListStyle(hash.rect, hashMatches.length)}
            >
              {/* The one scrolling box: the popover's padding is taken off its 280px. */}
              <div className="acx-list__items" style={{ maxHeight: 264 }}>
                {hashFailed ? (
                  <SnippetLoadError className="acx-list__empty" onRetry={loadHashSnippets} />
                ) : hashMatches.length ? (
                  hashMatches.map((s, i) => (
                    <button
                      key={s.id}
                      ref={i === hashIndex ? keepInView : undefined}
                      type="button"
                      role="option"
                      aria-selected={i === hashIndex}
                      className={cn('acx-list__item', i === hashIndex && 'is-selected')}
                      onMouseDown={(e) => e.preventDefault()}
                      onMouseEnter={() => setHashIndex(i)}
                      onClick={() => pickHash(s)}
                    >
                      <span className="acx-list__label">
                        {s.name} <small>#{s.shortcut}</small>
                      </span>
                    </button>
                  ))
                ) : (
                  <div className="acx-list__empty">No snippets match #{hash.query}</div>
                )}
              </div>
            </div>,
            document.body,
          )
        : null}
      <div className="activity-compose__bar" role="toolbar" aria-label="Formatting">
        {tool('B', 'Bold', 'bold', 'is-bold')}
        {tool('I', 'Italic', 'italic', 'is-italic')}
        {tool('U', 'Underline', 'underline', 'is-underline')}
        {tool('Tx', 'Clear formatting', 'removeFormat')}

        <button
          ref={moreBtnRef}
          type="button"
          className={cn(
            'activity-compose__tool activity-compose__tool--text',
            moreOpen && 'is-active',
          )}
          title="More formatting"
          aria-label="More formatting"
          aria-expanded={moreOpen}
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => {
            rememberSelection();
            setLinkOpen(false);
            setMoreOpen((o) => !o);
            setMoreSub(null);
          }}
        >
          More
          <Caret />
        </button>
        <AnchoredPopover
          open={moreOpen}
          anchorRef={moreBtnRef}
          onClose={() => {
            setMoreOpen(false);
            setMoreSub(null);
          }}
          className="activity-compose__more-pop"
          label="More formatting"
          fitContent
          maxHeight={420}
          preferred="up"
          align="center"
          gap={10}
        >
          <div className="activity-compose__more" role="toolbar" aria-label="More formatting">
            <span className="activity-compose__more-item">
              <button
                type="button"
                className={cn('activity-compose__more-select', moreSub === 'font' && 'is-open')}
                aria-haspopup="listbox"
                aria-expanded={moreSub === 'font'}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => toggleMoreSub('font')}
              >
                <span>{fontLabel}</span>
                <Caret />
              </button>
              {moreSub === 'font' ? (
                <div className="activity-compose__more-drop" role="listbox">
                  {FONTS.map((f) => (
                    <button
                      key={f.label}
                      type="button"
                      role="option"
                      aria-selected={fontLabel === f.label}
                      className={cn(fontLabel === f.label && 'is-active')}
                      style={{ fontFamily: f.value }}
                      onMouseDown={(e) => e.preventDefault()}
                      onClick={() => {
                        setFontLabel(f.label);
                        wrapInline({ fontFamily: f.value });
                        setMoreSub(null);
                      }}
                    >
                      {f.label}
                    </button>
                  ))}
                </div>
              ) : null}
            </span>

            <span className="activity-compose__more-item">
              <button
                type="button"
                className={cn('activity-compose__more-select', moreSub === 'size' && 'is-open')}
                aria-haspopup="listbox"
                aria-expanded={moreSub === 'size'}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => toggleMoreSub('size')}
              >
                <span>{fontSize}</span>
                <Caret />
              </button>
              {moreSub === 'size' ? (
                <div className="activity-compose__more-drop" role="listbox">
                  {FONT_SIZES.map((n) => (
                    <button
                      key={n}
                      type="button"
                      role="option"
                      aria-selected={fontSize === n}
                      className={cn(fontSize === n && 'is-active')}
                      onMouseDown={(e) => e.preventDefault()}
                      onClick={() => {
                        setFontSize(n);
                        wrapInline({ fontSize: `${n}px` });
                        setMoreSub(null);
                      }}
                    >
                      {n}
                    </button>
                  ))}
                </div>
              ) : null}
            </span>

            <span className="activity-compose__more-item">
              <button
                type="button"
                className={cn(
                  'activity-compose__tool activity-compose__tool--pair',
                  moreSub === 'color' && 'is-active',
                )}
                aria-label="Text colour"
                title="Text colour"
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => toggleMoreSub('color')}
              >
                <ToolIcon>
                  <path d="m6 16 6-12 6 12M8 12h8" />
                </ToolIcon>
                <Caret />
              </button>
              {moreSub === 'color' ? (
                <div className="activity-compose__more-drop activity-compose__more-drop--swatches">
                  {TEXT_COLORS.map((c) => (
                    <button
                      key={c}
                      type="button"
                      title={c}
                      aria-label={`Colour ${c}`}
                      className="activity-compose__swatch"
                      style={{ background: c }}
                      onMouseDown={(e) => e.preventDefault()}
                      onClick={() => {
                        wrapInline({ color: c });
                        setMoreSub(null);
                      }}
                    />
                  ))}
                </div>
              ) : null}
            </span>

            <span className="activity-compose__more-item">
              <button
                type="button"
                className={cn(
                  'activity-compose__tool activity-compose__tool--pair',
                  moreSub === 'highlight' && 'is-active',
                )}
                aria-label="Highlight"
                title="Highlight"
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => toggleMoreSub('highlight')}
              >
                <ToolIcon>
                  <path d="m9 11-6 6v3h3l6-6M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4" />
                </ToolIcon>
                <Caret />
              </button>
              {moreSub === 'highlight' ? (
                <div className="activity-compose__more-drop activity-compose__more-drop--swatches">
                  {HIGHLIGHTS.map((c) => (
                    <button
                      key={c.label}
                      type="button"
                      title={c.label === 'None' ? 'None' : c.value}
                      aria-label={c.label === 'None' ? 'No highlight' : `Colour ${c.value}`}
                      className={cn(
                        'activity-compose__swatch',
                        c.value === 'transparent' && 'is-none',
                      )}
                      style={{
                        background: c.value === 'transparent' ? 'transparent' : c.value,
                      }}
                      onMouseDown={(e) => e.preventDefault()}
                      onClick={() => {
                        wrapInline({ backgroundColor: c.value });
                        setMoreSub(null);
                      }}
                    />
                  ))}
                </div>
              ) : null}
            </span>

            <span className="activity-compose__sep" />

            <button
              type="button"
              className="activity-compose__tool"
              aria-label="Blockquote"
              title="Blockquote"
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => run('formatBlock', 'blockquote')}
            >
              <ToolIcon filled>
                <path d="M5 7h5v5H7.5c0 2 1 3 2.5 3.5V18c-3 0-5-2.5-5-6zm9 0h5v5h-2.5c0 2 1 3 2.5 3.5V18c-3 0-5-2.5-5-6z" />
              </ToolIcon>
            </button>
            <button
              type="button"
              className="activity-compose__tool"
              aria-label="Bulleted list"
              title="Bulleted list"
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => run('insertUnorderedList')}
            >
              <ToolIcon>
                <path d="M9 6h11M9 12h11M9 18h11" />
                <circle cx="4.5" cy="6" r="1" fill="currentColor" />
                <circle cx="4.5" cy="12" r="1" fill="currentColor" />
                <circle cx="4.5" cy="18" r="1" fill="currentColor" />
              </ToolIcon>
            </button>
            <button
              type="button"
              className="activity-compose__tool"
              aria-label="Numbered list"
              title="Numbered list"
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => run('insertOrderedList')}
            >
              <ToolIcon>
                <path d="M10 6h10M10 12h10M10 18h10M4 5h1v4M4 9h2M4 14h2l-2 3h2" />
              </ToolIcon>
            </button>

            <span className="activity-compose__more-item">
              <button
                type="button"
                className={cn(
                  'activity-compose__tool activity-compose__tool--pair',
                  moreSub === 'align' && 'is-active',
                )}
                aria-label="Alignment"
                title="Alignment"
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => toggleMoreSub('align')}
              >
                <ToolIcon>
                  <path d="M4 6h16M4 10h10M4 14h16M4 18h10" />
                </ToolIcon>
                <Caret />
              </button>
              {moreSub === 'align' ? (
                <div className="activity-compose__more-drop">
                  {ALIGNS.map((a) => (
                    <button
                      key={a.command}
                      type="button"
                      onMouseDown={(e) => e.preventDefault()}
                      onClick={() => {
                        run(a.command);
                        setMoreSub(null);
                      }}
                    >
                      <ToolIcon>
                        <path d={a.path} />
                      </ToolIcon>
                      {a.label}
                    </button>
                  ))}
                </div>
              ) : null}
            </span>
          </div>
          <span className="activity-compose__more-arrow" aria-hidden />
        </AnchoredPopover>

        <span className="activity-compose__sep" />

        <IconBtn
          title="Insert link"
          active={linkOpen}
          buttonRef={linkBtnRef}
          onClick={openLinkPopover}
        >
          <ToolIcon>
            <path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7" />
            <path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7" />
          </ToolIcon>
        </IconBtn>
        <AnchoredPopover
          open={linkOpen}
          anchorRef={linkBtnRef}
          onClose={() => setLinkOpen(false)}
          className="activity-compose__link-pop"
          label="Insert link"
          width={320}
          maxHeight={320}
          preferred="up"
          align="center"
        >
          <label className="activity-compose__link-field">
            <span>Text to display</span>
            <input
              className="input"
              value={linkText}
              onChange={(e) => setLinkText(e.target.value)}
              placeholder="Link text"
              autoFocus
            />
          </label>
          <label className="activity-compose__link-field">
            <span>URL</span>
            <input
              className="input"
              value={linkUrl}
              onChange={(e) => setLinkUrl(e.target.value)}
              placeholder="https://"
            />
          </label>
          <label className="activity-compose__link-check">
            <input
              type="checkbox"
              checked={linkNewTab}
              onChange={(e) => setLinkNewTab(e.target.checked)}
            />
            Open in a new tab
          </label>
          <div className="activity-compose__link-actions">
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={!/^https?:\/\//i.test(linkUrl.trim())}
              onClick={insertLink}
            >
              Insert
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={() => setLinkOpen(false)}
            >
              Cancel
            </button>
          </div>
        </AnchoredPopover>

        {noFiles ? null : (
          <IconBtn
            title={fileBusy ? 'Uploading…' : 'Insert image'}
            disabled={fileBusy}
            onClick={pickImage}
          >
            <ToolIcon>
              <rect x="3" y="4" width="18" height="16" rx="2" />
              <circle cx="8.5" cy="9.5" r="1.5" />
              <path d="m21 16-5-5-9 9" />
            </ToolIcon>
          </IconBtn>
        )}

        {plannedTools ? (
          <button
            type="button"
            className="activity-compose__tool"
            aria-label="Insert knowledge article"
            title={NOT_AVAILABLE_YET}
            disabled
          >
            <ToolIcon>
              <path d="M2 9l10-5 10 5-10 5z" />
              <path d="M6 11v5c0 1.5 3 3 6 3s6-1.5 6-3v-5" />
            </ToolIcon>
          </button>
        ) : null}

        {snippetTarget ? (
          <>
            <IconBtn
              title="Insert snippet"
              active={snippetOpen}
              buttonRef={snippetBtnRef}
              onClick={() => {
                rememberSelection();
                setSnippetOpen((o) => !o);
              }}
            >
              <ToolIcon>
                <path d="M4 5h7M7.5 5v8M14 9h6M14 13h6M4 17h16M4 21h16" />
              </ToolIcon>
            </IconBtn>
            <SnippetMenu
              open={snippetOpen}
              anchorRef={snippetBtnRef}
              onClose={() => setSnippetOpen(false)}
              target={snippetTarget}
              onInsert={(html) => {
                // The reply can land after the window closed.
                if (ref.current) insertHtml(html);
              }}
            />
          </>
        ) : null}

        {noFiles ? null : (
          <IconBtn
            title={fileBusy ? 'Uploading…' : 'Attach file'}
            disabled={fileBusy || attachDisabled}
            onClick={pickFile}
          >
            <ToolIcon>
              <path d="m21 11-8.5 8.5a5 5 0 0 1-7-7L14 4a3.5 3.5 0 0 1 5 5l-8.5 8.5a2 2 0 0 1-3-3L15 7" />
            </ToolIcon>
          </IconBtn>
        )}

        {plannedTools ? (
          <button
            type="button"
            className="activity-compose__tool"
            aria-label="Writing tools"
            title={NOT_AVAILABLE_YET}
            disabled
          >
            <ToolIcon filled>
              <path d="M12 2c.5 4.8 2.7 7.5 8 8-5.3.5-7.5 3.2-8 8-.5-4.8-2.7-7.5-8-8 5.3-.5 7.5-3.2 8-8z" />
            </ToolIcon>
          </button>
        ) : null}

        {toolbarEnd ? <div className="activity-compose__end">{toolbarEnd}</div> : null}

        <input
          ref={imageInputRef}
          type="file"
          accept="image/png,image/jpeg,image/gif,image/webp"
          hidden
          onChange={(e) => {
            const file = e.target.files?.[0];
            e.target.value = '';
            void handlePickedFile(file, 'image');
          }}
        />
        <input
          ref={fileInputRef}
          type="file"
          hidden
          multiple={Boolean(onAttachFiles)}
          onChange={(e) => {
            const picked = Array.from(e.target.files ?? []);
            e.target.value = '';
            if (onAttachFiles) onAttachFiles(picked);
            else void handlePickedFile(picked[0], 'file');
          }}
        />
      </div>
    </div>
  );
});
