'use client';

/**
 * The design's New / Edit template modal (#mEditor): sharing and folder pickers, name, subject with
 * Insert, the rich-text body with token chips, formatting (More, link, image), the Insert menu,
 * "Preview example email" for a contact, and Save template / Save as new / Update existing.
 * Suggestions are the design's tips, worked out here; closing with edits asks first, and an
 * update of a template changed by someone else since it was opened is refused. Generate with AI
 * asks the API for a draft once an AI service is connected; Video inserts a Vidyard video.
 */
import { useCallback, useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import type { Snippet } from '@/features/snippets/api.client';
import { MtIcon, MtListbox, MtMenu, MtModal, MtModalHead, MtPop } from '@/features/snippets/ui/mt';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { safeEmailHtml } from '@/lib/utils/safe-html';
import {
  createTemplate,
  previewTemplateDraft,
  updateTemplate,
  type MessageTemplate,
  type TemplateFolder,
  type TemplatePreview,
} from '../api.client';
import {
  formatToken,
  inertDocumentLinks,
  shareLabel,
  shareOf,
  shareToApi,
  templateSuggestions,
  vidyardLinks,
  type MergeToken,
  type ShareState,
} from '../model';
import { GenerateContentModal, InsertVideoModal } from './DesignDialogs';
import {
  bodyHasContent,
  hydrateTokens,
  relabelTokens,
  serializeBody,
  tokenChip,
  tokenOfChip,
} from './editorDom';
import {
  ContactPicker,
  InsertMenu,
  TokenForm,
  UrlPanel,
  labelOfToken,
  useCustomTokens,
  type PreviewContact,
} from './editorParts';
import { ShareDrawer, type ShareOptions } from './ShareDrawer';

const SWATCHES = [
  '#000000',
  '#475467',
  '#98a2b3',
  '#ffffff',
  '#c01048',
  '#e04f16',
  '#f28f23',
  '#fac515',
  '#067647',
  '#0e7c86',
  '#2456e6',
  '#7a3ed6',
  '#fde2e4',
  '#ffe8d1',
  '#fff4c2',
  '#d8f5e4',
  '#d6ecf5',
  '#e3dcfb',
];
const FONTS = [
  ['Sans Serif', 'Arial'],
  ['Serif', 'Georgia'],
  ['Monospace', 'Courier New'],
  ['Verdana', 'Verdana'],
  ['Times New Roman', 'Times New Roman'],
] as const;
const SIZES = ['10', '11', '12', '14', '16', '18', '24', '32'];

type Pop = 'share' | 'folder' | 'subject' | 'insert' | 'more' | 'link' | 'image' | 'suggest' | null;
type MorePop = 'font' | 'size' | 'color' | 'hilite' | 'align' | null;

/** The empty preview's art (message-templates.html #edPreview). */
function EmptyArt() {
  return (
    <svg className="mt-empty__art" viewBox="0 0 180 150" aria-hidden="true" focusable="false">
      <path d="M90 78 148 106 90 134 32 106z" fill="var(--surface-3)" />
      <path
        d="M90 90 118 104 90 118 62 104z"
        fill="none"
        stroke="var(--border-strong)"
        strokeWidth="1.4"
        strokeDasharray="3 3"
      />
      <path d="M80 62h20l10 40H70z" fill="var(--brand-soft)" opacity=".7" />
      <circle
        cx="96"
        cy="44"
        r="20"
        fill="var(--surface)"
        stroke="var(--border-strong)"
        strokeWidth="3"
      />
      <circle
        cx="96"
        cy="44"
        r="13"
        fill="var(--surface-2)"
        stroke="var(--border)"
        strokeWidth="2"
      />
      <path d="m111 59 15 15" stroke="var(--border-strong)" strokeWidth="7" strokeLinecap="round" />
      <path
        d="M121 24l8-9M130 36l11-4M110 17l2-10"
        stroke="var(--border-strong)"
        strokeWidth="2"
        strokeLinecap="round"
      />
    </svg>
  );
}

export function TemplateEditorModal({
  template,
  initialFolderId,
  folders,
  shareOptions,
  me,
  ownerName,
  atLimit,
  onClose,
  onSaved,
  draft = null,
  hydrateBody,
}: {
  /** null: a new template. A restricted one comes with its grants. */
  template: MessageTemplate | null;
  /**
   * Sequences #59: a new template's starting name, subject and body (a sequence step's own
   * email, saved as a template from the step editor).
   */
  draft?: { name: string; subject: string; bodyHtml: string } | null;
  /**
   * Sequences QA steps BUG-11: extra chips for the body after its tokens (a sequence's
   * pre-made placeholders, "Placeholder: X CONTENT"). Saved back as their text by serializeBody.
   */
  hydrateBody?: (root: HTMLElement) => void;
  /** Where a new template goes (the open folder); undefined: "Select a Folder". */
  initialFolderId?: string | null;
  folders: TemplateFolder[];
  shareOptions: ShareOptions;
  me: { id: string; name: string; email: string };
  ownerName: (id: string) => string;
  atLimit: () => boolean;
  onClose: () => void;
  onSaved: (t: MessageTemplate, created: boolean) => void;
}) {
  const toast = useToast();
  const isNew = !template;
  const custom = useCustomTokens();
  const customRef = useRef(custom);
  customRef.current = custom;
  const labelOf = useCallback((t: MergeToken) => labelOfToken(t, customRef.current), []);

  const [name, setName] = useState(template?.name ?? draft?.name ?? '');
  const [nameInvalid, setNameInvalid] = useState(false);
  const [subject, setSubject] = useState(template?.subject ?? draft?.subject ?? '');
  const [share, setShare] = useState<ShareState>(
    template
      ? shareOf(template.visibility, template.grants)
      : { mode: 'everyone', users: [], teams: [] },
  );
  const [folderId, setFolderId] = useState<string | null | undefined>(
    template ? template.folderId : initialFolderId,
  );
  const [shareDrawer, setShareDrawer] = useState(false);
  const [showPreview, setShowPreview] = useState(true);
  const [contact, setContact] = useState<PreviewContact | null>(null);
  const [preview, setPreview] = useState<TemplatePreview | null>(null);
  const [previewing, setPreviewing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [pop, setPop] = useState<Pop>(null);
  const [morePop, setMorePop] = useState<MorePop>(null);
  const [chip, setChip] = useState<HTMLElement | null>(null);
  const [fontName, setFontName] = useState('Sans Serif');
  const [fontSize, setFontSize] = useState('11');
  const [fmtOn, setFmtOn] = useState<Record<string, boolean>>({});
  const [confirmDiscard, setConfirmDiscard] = useState(false);
  const [dialog, setDialog] = useState<'ai' | 'video' | null>(null);
  /** What the body holds, for Suggestions. */
  const [bodyFacts, setBodyFacts] = useState({ hasLink: false, hasToken: false, words: 0 });
  /** The form as it opened: closing asks only when it differs. */
  const opened = useRef<string | null>(null);

  const bodyRef = useRef<HTMLDivElement>(null);
  const subjectRef = useRef<HTMLInputElement>(null);
  const saved = useRef<Range | null>(null);
  const btns = useRef<Record<string, HTMLElement | null>>({});
  const [, force] = useState(0);
  const setBtn = (k: string) => (el: HTMLElement | null) => {
    btns.current[k] = el;
  };
  const anchor = (k: string) => btns.current[k] ?? null;

  useEffect(() => {
    const body = bodyRef.current;
    if (body) {
      const html = template?.bodyHtml ?? draft?.bodyHtml;
      body.innerHTML = html ? safeEmailHtml(html) : '';
      hydrateTokens(body, labelOf);
    }
    try {
      document.execCommand('styleWithCSS', false, 'true');
      document.execCommand('defaultParagraphSeparator', false, 'p');
    } catch {
      // older browsers
    }
    opened.current = JSON.stringify(readForm());
    force((n) => n + 1); // anchors are set now
    // Filled once, when it opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Suggestions follow every change to the body: typing, inserts and formatting.
  useEffect(() => {
    const body = bodyRef.current;
    if (!body) return;
    const read = () => {
      const text = (body.textContent ?? '').replace(/\u200B/g, ' ').trim();
      const next = {
        hasLink: !!body.querySelector('a[href]'),
        hasToken: !!body.querySelector('.mt-token'),
        words: text ? text.split(/\s+/).length : 0,
      };
      setBodyFacts((cur) =>
        cur.hasLink === next.hasLink && cur.hasToken === next.hasToken && cur.words === next.words
          ? cur
          : next,
      );
    };
    read();
    const observer = new MutationObserver(read);
    observer.observe(body, { childList: true, subtree: true, characterData: true });
    return () => observer.disconnect();
  }, []);
  const suggestions = templateSuggestions({ subject, ...bodyFacts });

  // Custom field labels arrive after opening: relabel the chips.
  useEffect(() => {
    if (bodyRef.current) relabelTokens(bodyRef.current, labelOf);
  }, [custom, labelOf]);

  // --- caret and formatting ---
  const selectionSave = () => {
    const sel = window.getSelection();
    const body = bodyRef.current;
    if (body && sel && sel.rangeCount) {
      const range = sel.getRangeAt(0);
      if (body.contains(range.commonAncestorContainer)) saved.current = range.cloneRange();
    }
  };
  const selectionRestore = () => {
    const body = bodyRef.current;
    if (!body) return;
    body.focus();
    const sel = window.getSelection();
    if (!sel) return;
    sel.removeAllRanges();
    if (saved.current && body.contains(saved.current.commonAncestorContainer)) {
      sel.addRange(saved.current);
    } else {
      const r = document.createRange();
      r.selectNodeContents(body);
      r.collapse(false);
      sel.addRange(r);
    }
  };
  useEffect(() => {
    const onSel = () => {
      selectionSave();
      const next: Record<string, boolean> = {};
      for (const cmd of ['bold', 'italic', 'underline']) {
        try {
          next[cmd] = document.queryCommandState(cmd);
        } catch {
          next[cmd] = false;
        }
      }
      setFmtOn((cur) =>
        cur.bold === next.bold && cur.italic === next.italic && cur.underline === next.underline
          ? cur
          : next,
      );
    };
    document.addEventListener('selectionchange', onSel);
    return () => document.removeEventListener('selectionchange', onSel);
  }, []);

  const exec = (cmd: string, value?: string) => {
    selectionRestore();
    let colorRange: Range | null = null;
    if (cmd === 'foreColor') {
      const s = window.getSelection();
      if (s && s.rangeCount) colorRange = s.getRangeAt(0).cloneRange();
    }
    try {
      document.execCommand(cmd, false, value);
    } catch {
      // unsupported command
    }
    // The design keeps a list marker the colour of the text chosen for its item.
    if (cmd === 'foreColor' && value && colorRange && bodyRef.current) {
      bodyRef.current.querySelectorAll('li').forEach((li) => {
        let touches = false;
        try {
          touches = colorRange.intersectsNode(li);
        } catch {
          touches = li.contains(colorRange.startContainer);
        }
        if (touches) li.style.setProperty('--mt-list-marker-color', value);
      });
    }
    selectionSave();
  };
  /** The design's `applyFontSize`: a px size on a span (execCommand only knows 1-7). */
  const applyFontSize = (px: number) => {
    selectionRestore();
    try {
      document.execCommand('fontSize', false, '7');
    } catch {
      // unsupported
    }
    bodyRef.current
      ?.querySelectorAll<HTMLElement>('font[size="7"], span[style*="xxx-large"]')
      .forEach((n) => {
        if (n.tagName === 'FONT') {
          const s = document.createElement('span');
          s.style.fontSize = `${px}px`;
          while (n.firstChild) s.appendChild(n.firstChild);
          n.replaceWith(s);
        } else {
          n.style.fontSize = `${px}px`;
        }
      });
    selectionSave();
  };
  const insertNode = (node: Node) => {
    selectionRestore();
    const sel = window.getSelection();
    if (!sel || !sel.rangeCount) return;
    const range = sel.getRangeAt(0);
    range.deleteContents();
    const last = node.nodeType === 11 ? node.lastChild : node;
    range.insertNode(node);
    if (last) {
      let after: Node = last;
      // A caret can't sit right after a chip at the end of a line without a character there.
      if (last.nodeType === 1 && (!last.nextSibling || last.nextSibling.nodeValue === '')) {
        const z = document.createTextNode('\u200B');
        last.parentNode?.insertBefore(z, last.nextSibling);
        after = z;
      }
      const r = document.createRange();
      r.setStartAfter(after);
      r.collapse(true);
      sel.removeAllRanges();
      sel.addRange(r);
      saved.current = r.cloneRange();
    }
  };
  const keepCaret = (e: React.MouseEvent) => {
    if ((e.target as Element).closest('button')) e.preventDefault();
  };
  const toggle = (p: Exclude<Pop, null>) => {
    if (p !== 'subject') selectionSave();
    setMorePop(null);
    setPop((cur) => (cur === p ? null : p));
  };

  // --- tokens ---
  const insertToken = (t: MergeToken) => insertNode(tokenChip(t, labelOf(t)));
  const insertSubjectToken = (t: MergeToken) => {
    const input = subjectRef.current;
    const text = formatToken(t);
    const s = input?.selectionStart ?? subject.length;
    const e = input?.selectionEnd ?? subject.length;
    const next = subject.slice(0, s) + text + subject.slice(e);
    setSubject(next);
    window.setTimeout(() => {
      input?.focus();
      input?.setSelectionRange(s + text.length, s + text.length);
    }, 0);
  };
  // The extra chips' list can arrive after the body is filled; the text is the same once saved.
  useEffect(() => {
    if (bodyRef.current) hydrateBody?.(bodyRef.current);
  }, [hydrateBody]);
  const insertSnippet = (s: Snippet) => {
    const holder = document.createElement('div');
    holder.innerHTML = safeEmailHtml(s.bodyHtml);
    hydrateTokens(holder, labelOf);
    hydrateBody?.(holder);
    const frag = document.createDocumentFragment();
    while (holder.firstChild) frag.appendChild(holder.firstChild);
    insertNode(frag);
  };
  const insertLink = (href: string, text: string) => {
    const a = document.createElement('a');
    a.href = href;
    a.target = '_blank';
    a.rel = 'noopener noreferrer';
    a.textContent = text;
    insertNode(a);
  };
  const insertDocument = (href: string, text: string, boxed: boolean) => {
    if (!boxed) {
      insertLink(href, text);
      return;
    }
    // "Include link preview": the link in a card (inline styles: email keeps nothing else).
    const card = document.createElement('div');
    card.style.border = '1px solid #d0d5dd';
    card.style.borderRadius = '8px';
    card.style.padding = '12px 16px';
    const a = document.createElement('a');
    a.href = href;
    a.target = '_blank';
    a.rel = 'noopener noreferrer';
    a.textContent = text;
    card.append('\u{1F4C4} ', a);
    insertNode(card);
  };
  /** The video's thumbnail linked to it, with a text link under it for blocked images. */
  const insertVideo = (videoId: string, title: string) => {
    const { watch, thumbnail } = vidyardLinks(videoId);
    const link = () => {
      const a = document.createElement('a');
      a.href = watch;
      a.target = '_blank';
      a.rel = 'noopener noreferrer';
      return a;
    };
    const picture = link();
    const img = document.createElement('img');
    img.src = thumbnail;
    img.alt = title;
    img.setAttribute('width', '400');
    img.style.maxWidth = '100%';
    picture.append(img);
    const words = link();
    words.textContent = title;
    const block = document.createElement('p');
    block.append(picture, document.createElement('br'), words);
    insertNode(block);
  };
  /** The design's `generateAi`: the draft goes after what is written; an empty subject is filled. */
  const insertAiDraft = (draft: { subject: string; bodyHtml: string }) => {
    const body = bodyRef.current;
    if (!body) return;
    if (!subject.trim()) setSubject(draft.subject);
    const holder = document.createElement('div');
    holder.innerHTML = safeEmailHtml(draft.bodyHtml);
    hydrateTokens(holder, labelOf);
    // Added at the end, as whole paragraphs: never inside the one the caret was in.
    if (!bodyHasContent(body)) body.innerHTML = '';
    else body.insertAdjacentHTML('beforeend', '<p><br></p>');
    while (holder.firstChild) body.appendChild(holder.firstChild);
    saved.current = null;
    toast('Content generated and added to your template.');
  };
  const onBodyClick = (e: React.MouseEvent) => {
    const c = (e.target as Element).closest<HTMLElement>('.mt-token');
    if (c && bodyRef.current?.contains(c)) {
      setPop(null);
      setChip((cur) => (cur === c ? null : c));
    }
  };
  const onBodyKey = (e: React.KeyboardEvent) => {
    const c = (e.target as Element).closest<HTMLElement>('.mt-token');
    if (c && (e.key === 'Enter' || e.key === ' ')) {
      e.preventDefault();
      setChip(c);
    }
  };
  useEffect(() => {
    if (!chip) return;
    chip.classList.add('is-selected');
    return () => chip.classList.remove('is-selected');
  }, [chip]);

  // --- preview ---
  const generate = async () => {
    const body = bodyRef.current;
    if (!contact || !body) return;
    if (!bodyHasContent(body) && !subject.trim()) {
      toast('Add a subject or some content to preview the email.', 'info');
      return;
    }
    setPreviewing(true);
    try {
      setPreview(
        await previewTemplateDraft({
          contactId: contact.id,
          subject: subject.trim(),
          bodyHtml: serializeBody(body),
        }),
      );
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setPreviewing(false);
    }
  };

  // --- save ---
  const readForm = () => {
    const body = bodyRef.current;
    const html = body && bodyHasContent(body) ? serializeBody(body) : '<p><br></p>';
    return {
      name: name.trim(),
      subject: subject.trim(),
      bodyHtml: html,
      folderId: folderId ?? null,
      ...shareToApi(share),
    };
  };
  const isDirty = () => opened.current !== null && JSON.stringify(readForm()) !== opened.current;
  const requestClose = () => {
    if (isDirty()) {
      setPop(null);
      setConfirmDiscard(true);
    } else {
      onClose();
    }
  };
  // A refresh or a closed tab would lose the edits too: the browser asks.
  const isDirtyRef = useRef(isDirty);
  isDirtyRef.current = isDirty;
  useEffect(() => {
    const warn = (e: BeforeUnloadEvent) => {
      if (isDirtyRef.current()) e.preventDefault();
    };
    window.addEventListener('beforeunload', warn);
    return () => window.removeEventListener('beforeunload', warn);
  }, []);
  const nameMissing = () => {
    setNameInvalid(true);
    document.getElementById('edName')?.focus();
    toast('Template name is required.', 'danger');
  };
  const saveAsNew = async () => {
    const v = readForm();
    if (!v.name) return nameMissing();
    if (atLimit()) {
      toast('You have reached the limit of 10,000 templates.', 'danger');
      return;
    }
    setSaving(true);
    try {
      const created = await createTemplate(v);
      onSaved(created, true);
    } catch (err) {
      toast(errorText(err), 'danger');
      setSaving(false);
    }
  };
  const updateExisting = async () => {
    if (!template) return;
    const v = readForm();
    if (!v.name) return nameMissing();
    setSaving(true);
    try {
      onSaved(
        await updateTemplate(template.id, { ...v, expectedUpdatedAt: template.updatedAt }),
        false,
      );
    } catch (err) {
      toast(errorText(err), 'danger');
      setSaving(false);
    }
  };

  const folderLabel =
    folderId === undefined
      ? 'Select a Folder'
      : folderId === null
        ? 'No folder'
        : (folders.find((f) => f.id === folderId)?.name ?? 'No folder');
  const fmtBtn = (cmd: string, label: string, icon: string) => (
    <button
      key={cmd}
      type="button"
      className={cn('mt-fmt__btn', fmtOn[cmd] && 'is-on')}
      data-cmd={cmd}
      aria-label={label}
      title={label}
      onClick={() => exec(cmd)}
    >
      <MtIcon name={icon} />
    </button>
  );

  return (
    <MtModal
      id="mEditor"
      onClose={requestClose}
      labelledBy="edTitle"
      className={cn('mt-modal--editor', !showPreview && 'is-solo')}
      staticBackdrop
      focus="#edName"
    >
      <MtModalHead
        id="edTitle"
        title={isNew ? 'New template' : 'Edit template'}
        onClose={requestClose}
      />
      <div className="mt-ed">
        <section className="mt-ed__col mt-ed__compose" aria-labelledby="edComposeH">
          <div className="mt-ed__head">
            <h3 id="edComposeH">Compose email template</h3>
            <button
              type="button"
              className="mt-link-btn mt-ed__showprev"
              id="edShowPreview"
              onClick={() => setShowPreview(true)}
            >
              <MtIcon name="eye" />
              Show preview
            </button>
          </div>
          <div className="mt-compose">
            <div className="mt-compose__row mt-compose__meta">
              <button
                ref={setBtn('share')}
                type="button"
                className="mt-dd"
                id="edShare"
                aria-haspopup="listbox"
                aria-expanded={pop === 'share'}
                onClick={() => toggle('share')}
              >
                <span id="edShareLbl">{shareLabel(share)}</span>
                <MtIcon name="chevron-down" size={14} />
              </button>
              <button
                ref={setBtn('folder')}
                type="button"
                className="mt-dd"
                id="edFolder"
                aria-haspopup="listbox"
                aria-expanded={pop === 'folder'}
                onClick={() => toggle('folder')}
              >
                <span id="edFolderLbl">{folderLabel}</span>
                <MtIcon name="chevron-down" size={14} />
              </button>
              <span className="mt-compose__owner">
                <strong>Owner:</strong>{' '}
                <span id="edOwner">{ownerName(template?.ownerId ?? me.id)}</span>
              </span>
            </div>
            <div className={cn('mt-compose__row', nameInvalid && 'is-invalid')}>
              <label className="mt-compose__lbl" htmlFor="edName">
                Template name:
              </label>
              <input
                className="mt-compose__input"
                type="text"
                id="edName"
                maxLength={191}
                autoComplete="off"
                value={name}
                onChange={(e) => {
                  setName(e.target.value);
                  setNameInvalid(false);
                }}
              />
            </div>
            <div className="mt-compose__row">
              <label className="mt-compose__lbl" htmlFor="edSubject">
                Subject:
              </label>
              <input
                ref={subjectRef}
                className="mt-compose__input"
                type="text"
                id="edSubject"
                maxLength={500}
                autoComplete="off"
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
              />
              <button
                ref={setBtn('subject')}
                type="button"
                className="mt-dd"
                id="edSubjInsert"
                aria-haspopup="menu"
                aria-expanded={pop === 'subject'}
                onClick={() => toggle('subject')}
              >
                Insert
                <MtIcon name="chevron-down" size={14} />
              </button>
            </div>
            <div
              ref={bodyRef}
              className="mt-editor"
              id="edBody"
              contentEditable
              suppressContentEditableWarning
              role="textbox"
              aria-multiline="true"
              aria-label="Email body"
              data-mt-placeholder="Write your email template..."
              onInput={() => {
                const body = bodyRef.current;
                if (body && !bodyHasContent(body)) body.innerHTML = '';
              }}
              onClick={onBodyClick}
              onKeyDown={onBodyKey}
              onPaste={(e) => {
                // The design pastes plain text only.
                e.preventDefault();
                const text = e.clipboardData.getData('text');
                try {
                  document.execCommand('insertText', false, text);
                } catch {
                  insertNode(document.createTextNode(text));
                }
              }}
              onBlur={selectionSave}
            />
            <div className="mt-compose__foot">
              <span className="mt-sig">
                <MtIcon name="signature" size={18} />
                Default signature will be included.
                <a
                  className="link"
                  href="/settings/profile#tab-email"
                  id="edSigEdit"
                  target="_blank"
                  rel="noopener"
                >
                  Edit
                  <MtIcon name="external" size={14} />
                </a>
              </span>
              <button
                ref={setBtn('suggest')}
                type="button"
                className="mt-suggest"
                id="edSuggest"
                aria-haspopup="dialog"
                aria-expanded={pop === 'suggest'}
                onClick={() => toggle('suggest')}
              >
                <span className={cn('mt-badge', !suggestions.length && 'is-zero')} id="edSuggestN">
                  {suggestions.length}
                </span>
                Suggestions
              </button>
            </div>
            <div
              className="mt-fmt"
              role="toolbar"
              aria-label="Text formatting"
              onMouseDown={keepCaret}
            >
              {fmtBtn('bold', 'Bold', 'bold')}
              {fmtBtn('italic', 'Italic', 'italic')}
              {fmtBtn('underline', 'Underline', 'underline')}
              {fmtBtn('removeFormat', 'Clear formatting', 'clear-format')}
              <button
                ref={setBtn('more')}
                type="button"
                className="mt-fmt__txt"
                id="edMore"
                aria-haspopup="dialog"
                aria-expanded={pop === 'more'}
                onClick={() => toggle('more')}
              >
                More
                <MtIcon name="chevron-down" size={14} />
              </button>
              <button
                ref={setBtn('link')}
                type="button"
                className="mt-fmt__btn"
                id="edLink"
                aria-haspopup="dialog"
                aria-label="Insert link"
                title="Insert link"
                aria-expanded={pop === 'link'}
                onClick={() => toggle('link')}
              >
                <MtIcon name="link" />
              </button>
              <button
                ref={setBtn('image')}
                type="button"
                className="mt-fmt__btn"
                id="edImage"
                aria-haspopup="dialog"
                aria-label="Insert image"
                title="Insert image"
                aria-expanded={pop === 'image'}
                onClick={() => toggle('image')}
              >
                <MtIcon name="image" />
              </button>
              <button
                ref={setBtn('insert')}
                type="button"
                className="mt-fmt__txt"
                id="edInsert"
                aria-haspopup="menu"
                aria-expanded={pop === 'insert'}
                onClick={() => toggle('insert')}
              >
                Insert
                <MtIcon name="chevron-down" size={14} />
              </button>
              <button
                type="button"
                className="mt-fmt__txt mt-fmt__ai"
                id="edAI"
                aria-haspopup="dialog"
                onClick={() => {
                  setPop(null);
                  setDialog('ai');
                }}
              >
                Generate with AI
              </button>
            </div>
          </div>
        </section>

        <section
          className="mt-ed__col mt-ed__previewcol"
          id="edPreviewCol"
          aria-labelledby="edPrevH"
        >
          <div className="mt-ed__head">
            <h3 id="edPrevH">Preview example email</h3>
            <button
              type="button"
              className="mt-link-btn"
              id="edHidePreview"
              onClick={() => setShowPreview(false)}
            >
              <MtIcon name="eye-off" />
              Hide preview
            </button>
          </div>
          <div className="mt-preview-pick">
            <div className="mt-grow" id="edContactHost">
              <ContactPicker value={contact} onChange={setContact} />
            </div>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              id="edGenerate"
              disabled={!contact || previewing}
              onClick={() => void generate()}
            >
              Generate
            </button>
          </div>
          <div className="mt-preview" id="edPreview" aria-live="polite">
            {preview && contact ? (
              <div className="mt-mail">
                <dl className="mt-mail__meta">
                  <div>
                    <dt>From</dt>
                    <dd>{`${me.name} <${me.email}>`}</dd>
                  </div>
                  <div>
                    <dt>To</dt>
                    <dd>
                      {contact.name && contact.email && contact.name !== contact.email
                        ? `${contact.name} <${contact.email}>`
                        : contact.email || contact.name}
                    </dd>
                  </div>
                  <div>
                    <dt>Subject</dt>
                    <dd>{preview.subject || '(no subject)'}</dd>
                  </div>
                </dl>
                <div
                  dangerouslySetInnerHTML={{
                    __html: inertDocumentLinks(safeEmailHtml(preview.bodyHtml)),
                  }}
                />
                <div className="mt-mail__sig">
                  <strong>{me.name}</strong>
                  <br />
                  {me.email}
                </div>
              </div>
            ) : (
              <div className="mt-empty">
                <EmptyArt />
                <p>Compose the email template and select a contact to preview the example email.</p>
              </div>
            )}
          </div>
        </section>
      </div>
      <div className="mt-modal__foot mt-modal__foot--editor">
        {isNew ? (
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            id="edSave"
            disabled={!name.trim() || saving}
            onClick={() => void saveAsNew()}
          >
            Save template
          </button>
        ) : (
          <>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              id="edSaveNew"
              disabled={!name.trim() || saving}
              onClick={() => void saveAsNew()}
            >
              Save as new template
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              id="edUpdate"
              disabled={!name.trim() || saving || !template?.canEdit}
              title={
                template?.canEdit
                  ? undefined
                  : 'Only its owner or a settings admin can change this template'
              }
              onClick={() => void updateExisting()}
            >
              Update existing template
            </button>
          </>
        )}
        <button type="button" className="btn-crm btn-crm--outline" onClick={requestClose}>
          Cancel
        </button>
      </div>

      {pop === 'suggest' ? (
        <MtPop anchor={anchor('suggest')} onClose={() => setPop(null)} align="end" placement="top">
          <ul className="mt-suggest-list">
            {!suggestions.length ? (
              <li className="is-ok">
                <MtIcon name="check" />
                <span>No suggestions. This template looks good.</span>
              </li>
            ) : null}
            {suggestions.map((s) => (
              <li key={s}>
                <MtIcon name="info" />
                <span>{s}</span>
              </li>
            ))}
          </ul>
        </MtPop>
      ) : null}
      {dialog === 'ai' ? (
        <GenerateContentModal
          onClose={() => setDialog(null)}
          onGenerated={(draft) => {
            setDialog(null);
            insertAiDraft(draft);
          }}
        />
      ) : null}
      {dialog === 'video' ? (
        <InsertVideoModal
          onClose={() => setDialog(null)}
          onInsert={(videoId, title) => {
            setDialog(null);
            // After the dialog is gone, so the caret goes back into the body.
            window.setTimeout(() => insertVideo(videoId, title), 0);
          }}
        />
      ) : null}
      {confirmDiscard ? (
        <MtModal
          id="mDiscard"
          onClose={() => setConfirmDiscard(false)}
          labelledBy="mDiscardT"
          describedBy="mDiscardD"
          role="alertdialog"
          className="mt-modal--sm"
          focus="#discardKeep"
        >
          <MtModalHead
            id="mDiscardT"
            title="Discard your changes?"
            onClose={() => setConfirmDiscard(false)}
          />
          <div className="mt-modal__body" id="mDiscardD">
            <p className="mt-text">
              You have unsaved changes. If you close now, they will be lost.
            </p>
          </div>
          <div className="mt-modal__foot">
            <button
              type="button"
              className="btn-crm btn-crm--danger"
              id="discardGo"
              onClick={onClose}
            >
              Discard changes
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              id="discardKeep"
              onClick={() => setConfirmDiscard(false)}
            >
              Keep editing
            </button>
          </div>
        </MtModal>
      ) : null}

      {pop === 'share' ? (
        <MtPop anchor={anchor('share')} onClose={() => setPop(null)}>
          <MtListbox
            width={360}
            selected={share.mode}
            items={[
              {
                value: 'private',
                label: 'Private',
                sub: 'Only you can view and use this template',
              },
              {
                value: 'everyone',
                label: 'Shared with everyone',
                sub: 'Everyone can view and use this template',
              },
              {
                value: 'specific',
                label: 'Shared with specific users and teams',
                sub: 'Certain users and teams can view and use this template',
              },
            ]}
            onSelect={(it) => {
              setPop(null);
              if (it.value === 'specific') setShareDrawer(true);
              else setShare({ mode: it.value as ShareState['mode'], users: [], teams: [] });
            }}
          />
        </MtPop>
      ) : null}
      {pop === 'folder' ? (
        <MtPop anchor={anchor('folder')} onClose={() => setPop(null)}>
          <MtListbox
            width={260}
            searchable
            searchPlaceholder="Search"
            selected={folderId ?? ''}
            items={[
              { value: '', label: 'No folder' },
              ...[...folders]
                .sort((a, b) => a.name.localeCompare(b.name))
                .map((f) => ({ value: f.id, label: f.name })),
            ]}
            onSelect={(it) => {
              setPop(null);
              setFolderId(it.value || null);
            }}
          />
        </MtPop>
      ) : null}
      {pop === 'subject' || pop === 'insert' ? (
        <MtPop
          anchor={anchor(pop)}
          onClose={() => setPop(null)}
          // It also shows forms (tokens, documents, meetings): the menu inside has its own role.
          label="Insert"
          align={pop === 'subject' ? 'end' : 'center'}
        >
          <div style={{ width: pop === 'subject' ? 330 : 360 }}>
            <InsertMenu
              mode={pop === 'subject' ? 'subject' : 'body'}
              custom={custom}
              meId={me.id}
              onClose={() => setPop(null)}
              onToken={(t) => (pop === 'subject' ? insertSubjectToken(t) : insertToken(t))}
              onSnippet={insertSnippet}
              onMeetingLink={insertLink}
              onDocument={insertDocument}
              onVideo={() => setDialog('video')}
            />
          </div>
        </MtPop>
      ) : null}
      {chip ? (
        <MtPop anchor={chip} onClose={() => setChip(null)} align="start">
          <div style={{ paddingTop: 16, width: 340 }}>
            <TokenForm
              initial={tokenOfChip(chip)}
              allowFallback
              submitLabel="Save"
              custom={custom}
              onCancel={() => setChip(null)}
              onSubmit={(t) => {
                chip.replaceWith(tokenChip(t, labelOf(t)));
                setChip(null);
              }}
            />
          </div>
        </MtPop>
      ) : null}
      {pop === 'link' ? (
        <MtPop anchor={anchor('link')} onClose={() => setPop(null)} align="start">
          <UrlPanel
            title="Link address"
            button="Apply"
            allowMail
            onCancel={() => setPop(null)}
            onInvalid={() =>
              toast('Enter a valid web address starting with http:// or https://', 'danger')
            }
            onApply={(url) => {
              setPop(null);
              selectionRestore();
              const sel = window.getSelection();
              if (sel && sel.rangeCount && sel.getRangeAt(0).collapsed) insertLink(url, url);
              else exec('createLink', url);
            }}
          />
        </MtPop>
      ) : null}
      {pop === 'image' ? (
        <MtPop anchor={anchor('image')} onClose={() => setPop(null)} align="start">
          <UrlPanel
            title="Image address"
            button="Insert"
            extra={{ label: 'Alt text', placeholder: 'Describe the image' }}
            allowMail={false}
            onCancel={() => setPop(null)}
            onInvalid={() =>
              toast('Enter a valid web address starting with http:// or https://', 'danger')
            }
            onApply={(url, alt) => {
              setPop(null);
              const img = document.createElement('img');
              img.src = url;
              img.alt = alt;
              insertNode(img);
            }}
          />
        </MtPop>
      ) : null}
      {pop === 'more' ? (
        <MtPop
          anchor={anchor('more')}
          onClose={() => {
            setPop(null);
            setMorePop(null);
          }}
          role="toolbar"
          label="More formatting"
          align="start"
        >
          <div className="mt-moretools" onMouseDown={keepCaret}>
            <button
              ref={setBtn('font')}
              type="button"
              className="mt-fmt__txt"
              aria-haspopup="listbox"
              aria-expanded={morePop === 'font'}
              onClick={() => setMorePop((c) => (c === 'font' ? null : 'font'))}
            >
              <span>{fontName}</span>
              <MtIcon name="chevron-down" size={14} />
            </button>
            <button
              ref={setBtn('size')}
              type="button"
              className="mt-fmt__txt"
              aria-haspopup="listbox"
              aria-expanded={morePop === 'size'}
              onClick={() => setMorePop((c) => (c === 'size' ? null : 'size'))}
            >
              <span>{fontSize}</span>
              <MtIcon name="chevron-down" size={14} />
            </button>
            <span className="mt-moretools__sep" />
            <button
              ref={setBtn('color')}
              type="button"
              className="mt-fmt__txt"
              aria-label="Text color"
              aria-haspopup="dialog"
              aria-expanded={morePop === 'color'}
              onClick={() => setMorePop((c) => (c === 'color' ? null : 'color'))}
            >
              <MtIcon name="font-color" />
              <MtIcon name="chevron-down" size={14} />
            </button>
            <button
              ref={setBtn('hilite')}
              type="button"
              className="mt-fmt__txt"
              aria-label="Highlight color"
              aria-haspopup="dialog"
              aria-expanded={morePop === 'hilite'}
              onClick={() => setMorePop((c) => (c === 'hilite' ? null : 'hilite'))}
            >
              <MtIcon name="highlight" />
              <MtIcon name="chevron-down" size={14} />
            </button>
            <span className="mt-moretools__sep" />
            <button
              type="button"
              className="mt-fmt__btn"
              aria-label="Bulleted list"
              onClick={() => exec('insertUnorderedList')}
            >
              <MtIcon name="list-bullets" />
            </button>
            <button
              type="button"
              className="mt-fmt__btn"
              aria-label="Numbered list"
              onClick={() => exec('insertOrderedList')}
            >
              <MtIcon name="list-ordered" />
            </button>
            <button
              ref={setBtn('align')}
              type="button"
              className="mt-fmt__txt"
              aria-label="Alignment"
              aria-haspopup="menu"
              aria-expanded={morePop === 'align'}
              onClick={() => setMorePop((c) => (c === 'align' ? null : 'align'))}
            >
              <MtIcon name="align-left" />
              <MtIcon name="chevron-down" size={14} />
            </button>
          </div>
        </MtPop>
      ) : null}
      {pop === 'more' && morePop === 'font' ? (
        <MtPop anchor={anchor('font')} onClose={() => setMorePop(null)} arrow={false}>
          <MtListbox
            items={FONTS.map(([label, value]) => ({ value, label }))}
            selected={null}
            width={190}
            onSelect={(it) => {
              setMorePop(null);
              setFontName(it.label);
              exec('fontName', it.value);
            }}
          />
        </MtPop>
      ) : null}
      {pop === 'more' && morePop === 'size' ? (
        <MtPop anchor={anchor('size')} onClose={() => setMorePop(null)} arrow={false}>
          <MtListbox
            items={SIZES.map((v) => ({ value: v, label: v }))}
            selected={fontSize}
            width={90}
            onSelect={(it) => {
              setMorePop(null);
              setFontSize(it.value);
              applyFontSize(Number(it.value) + 3);
            }}
          />
        </MtPop>
      ) : null}
      {pop === 'more' && (morePop === 'color' || morePop === 'hilite') ? (
        <MtPop anchor={anchor(morePop)} onClose={() => setMorePop(null)} arrow={false}>
          <div className="mt-swatches" role="group" aria-label="Colors">
            {SWATCHES.map((c) => (
              <button
                key={c}
                type="button"
                className="mt-swatch"
                style={{ background: c }}
                aria-label={c}
                title={c}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => {
                  const cmd = morePop === 'color' ? 'foreColor' : 'hiliteColor';
                  setMorePop(null);
                  exec(cmd, c);
                }}
              />
            ))}
          </div>
        </MtPop>
      ) : null}
      {pop === 'more' && morePop === 'align' ? (
        <MtPop anchor={anchor('align')} onClose={() => setMorePop(null)}>
          <MtMenu
            onClose={() => setMorePop(null)}
            items={[
              { label: 'Align left', onClick: () => exec('justifyLeft') },
              { label: 'Align center', onClick: () => exec('justifyCenter') },
              { label: 'Align right', onClick: () => exec('justifyRight') },
            ]}
          />
        </MtPop>
      ) : null}

      {shareDrawer ? (
        <ShareDrawer
          share={share.mode === 'specific' ? share : { mode: 'specific', users: [], teams: [] }}
          options={shareOptions}
          onClose={() => setShareDrawer(false)}
          onSave={(s) => {
            setShare(s);
            setShareDrawer(false);
          }}
        />
      ) : null}
    </MtModal>
  );
}
