'use client';

/**
 * CRM › Message templates (HUB-721, QA #343): the 17 Nov design's message-templates.php on the
 * /email-templates API. Count "n of 10,000 created", search, Owner filter (users / teams), sort,
 * HubSpot's pager (First, Prev, numbered pages, Next, Last; fixed page size), folders (rows on top,
 * open one to see its templates), row actions (Clone, Move, Manage sharing, Delete), the bulk bar
 * (Move to folder, Delete, Build a sequence), Export, New template (From scratch, From template
 * library) and the editor. Analyze opens sales content analytics or the report library; Build a
 * sequence starts one with an email step per selected template. Search, Owner, folder, sort and
 * page are kept in the address, and /templates/<id>/edit opens that template.
 */
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { lexend } from '@/app/fonts';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { parseCsv, saveFile } from '@/features/exports/ui/ExportButton';
import { listTeamOptions, type TeamOption } from '@/features/members/api.client';
import { useOwners } from '@/features/owners/useOwners';
import { relTime, isoDate } from '@/features/snippets/model';
import {
  MtIcon,
  MtListbox,
  MtMenu,
  MtModal,
  MtModalHead,
  MtPop,
  MtScopeContext,
  MtSelect,
} from '@/features/snippets/ui/mt';
import { errorText } from '@/lib/api/errors';
import {
  SPREADSHEET_MIME,
  spreadsheetFile,
  type SpreadsheetFormat,
} from '@/lib/export/spreadsheet';
import { cn } from '@/lib/utils/cn';
import { safeEmailHtml } from '@/lib/utils/safe-html';
import {
  bulkDeleteTemplates,
  bulkMoveTemplates,
  cloneTemplate,
  createTemplate,
  createTemplateFolder,
  deleteTemplateFolder,
  exportTemplatesCsv,
  getTemplate,
  listTemplateFolders,
  listTemplatePage,
  renameTemplateFolder,
  shareTemplateFolder,
  templateUsage,
  updateTemplate,
  type MessageTemplate,
  type TemplateFolder,
  type TemplatePage,
} from '../api.client';
import { TEMPLATE_LIBRARY } from '../library';
import {
  PAGE_SIZE,
  SEQUENCE_TEMPLATES_MAX,
  TEMPLATE_LIMIT,
  deleteCopy,
  exportInfo,
  fmtNum,
  folderDeleteCopy,
  folderNameProblem,
  listFilters,
  listSearch,
  moveToast,
  nextSort,
  ownerFilterOf,
  pagerModel,
  plural,
  sequenceFromTemplatesHref,
  sequenceUseWarning,
  shareOf,
  shareToApi,
  type ListState,
  type OwnerFilter,
  type ShareState,
  type SortState,
} from '../model';
import { hydrateTokens } from './editorDom';
import { labelOfToken } from './editorParts';
import { ShareDrawer, type ShareOptions } from './ShareDrawer';
import { MTT_SPRITE } from './sprite';
import { TemplateEditorModal } from './TemplateEditorModal';

const folderKey = (id: string) => `folder:${id}`;
const NO_CUSTOM = { contact: [], company: [], deal: [], owner: [], sender: [] };

function MttSprite() {
  return (
    <svg
      width="0"
      height="0"
      style={{ position: 'absolute' }}
      aria-hidden="true"
      focusable="false"
      dangerouslySetInnerHTML={{ __html: `<defs>${MTT_SPRITE}</defs>` }}
    />
  );
}

type DeleteState =
  | { kind: 'templates'; ids: string[]; folderIds: string[] }
  | { kind: 'folder'; folder: TemplateFolder };

type EditorState = { template: MessageTemplate | null } | null;

export function MessageTemplatesView({
  initial,
  openTemplateId = null,
}: {
  /** Search, Owner, folder, sort and page from the address. */
  initial: ListState;
  /** /templates/<id>/edit: the template to open. */
  openTemplateId?: string | null;
}) {
  const router = useRouter();
  const toast = useToast();
  const me = useCurrentUser();
  const { owners } = useOwners(true);
  const [teams, setTeams] = useState<TeamOption[]>([]);

  const [result, setResult] = useState<TemplatePage | null>(null);
  const [loadError, setLoadError] = useState(false);
  const [folders, setFolders] = useState<TemplateFolder[]>([]);

  const [search, setSearch] = useState(initial.query);
  const [query, setQuery] = useState(initial.query);
  const [owner, setOwner] = useState<OwnerFilter>(() => ownerFilterOf(initial.owner, '…'));
  const [sort, setSort] = useState<SortState>(initial.sort);
  const [page, setPage] = useState(initial.page);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [folderId, setFolderId] = useState<string | null>(initial.folderId);
  const activeFolder = folders.find((f) => f.id === folderId) ?? null;
  /** The template named by the address, until it has been read. */
  const [pendingId, setPendingId] = useState<string | null>(openTemplateId);
  const [buildAsk, setBuildAsk] = useState<string[] | null>(null);

  const [ownerBtn, setOwnerBtn] = useState<HTMLButtonElement | null>(null);
  const [ownerOpen, setOwnerOpen] = useState(false);
  const [headMenu, setHeadMenu] = useState<{ kind: 'analyze' | 'new'; anchor: HTMLElement } | null>(
    null,
  );
  const [rowMenu, setRowMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
  const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
  const [editor, setEditor] = useState<EditorState>(null);
  const [cloning, setCloning] = useState<MessageTemplate | null>(null);
  const [moving, setMoving] = useState<string[] | null>(null);
  const [folderModal, setFolderModal] = useState<
    | { mode: 'create' }
    | { mode: 'clone'; from: TemplateFolder }
    | { mode: 'rename'; folder: TemplateFolder }
    | null
  >(null);
  const [deleting, setDeleting] = useState<DeleteState | null>(null);
  const [sharing, setSharing] = useState<{ template: MessageTemplate; share: ShareState } | null>(
    null,
  );
  const [sharingFolder, setSharingFolder] = useState<TemplateFolder | null>(null);
  const [exporting, setExporting] = useState(false);
  const [library, setLibrary] = useState(false);

  const filters = useMemo(
    () => listFilters({ query, owner, folderId, sort }),
    [query, owner, folderId, sort],
  );

  // --- loading ---
  const seq = useRef(0);
  const load = useCallback(() => {
    const mine = ++seq.current;
    setLoadError(false);
    listTemplatePage(filters, page, PAGE_SIZE).then(
      (res) => {
        if (mine !== seq.current) return;
        // A page past the end (after deletes): go to the last one.
        const last = Math.max(1, Math.ceil(res.total / PAGE_SIZE));
        if (!res.data.length && res.total > 0 && page > last) {
          setPage(last);
          return;
        }
        setResult(res);
      },
      () => mine === seq.current && setLoadError(true),
    );
  }, [filters, page]);
  useEffect(load, [load]);
  const loadFolders = useCallback(() => {
    listTemplateFolders().then(
      (res) => {
        setFolders(res.data);
        // A folder in an old address may be gone.
        setFolderId((cur) => (cur && !res.data.some((f) => f.id === cur) ? null : cur));
      },
      () => {
        // The list still works without folder rows.
      },
    );
  }, []);
  useEffect(loadFolders, [loadFolders]);
  const reloadAll = () => {
    load();
    loadFolders();
  };
  useEffect(() => {
    let alive = true;
    listTeamOptions().then(
      (res) => alive && setTeams(res.data),
      () => {
        // No teams: the Owner filter and sharing list users only.
      },
    );
    return () => {
      alive = false;
    };
  }, []);

  // The design's 180 ms search debounce.
  useEffect(() => {
    // Opening with a search from the address must keep its page.
    if (search === query) return;
    const t = window.setTimeout(() => {
      setQuery(search);
      setPage(1);
      setSelected(new Set());
    }, 180);
    return () => window.clearTimeout(t);
  }, [search, query]);

  // The address follows the list and the open template, so a refresh or a shared link returns here.
  const editorId = editor?.template?.id ?? pendingId;
  useEffect(() => {
    const path = editorId ? `/templates/${encodeURIComponent(editorId)}/edit` : '/templates';
    const next = path + listSearch({ query, owner: owner.value, folderId, sort, page });
    if (next !== window.location.pathname + window.location.search) {
      window.history.replaceState(null, '', next);
    }
  }, [editorId, query, owner.value, folderId, sort, page]);

  // /templates/<id>/edit
  const askedFor = useRef(false);
  useEffect(() => {
    if (!openTemplateId || askedFor.current) return;
    askedFor.current = true;
    getTemplate(openTemplateId).then(
      (t) => {
        setEditor({ template: t });
        setPendingId(null);
      },
      (err: unknown) => {
        setPendingId(null);
        toast(errorText(err), 'danger');
      },
    );
  }, [openTemplateId, toast]);

  const ownerNames = useMemo(() => new Map(owners.map((o) => [o.userId, o.name])), [owners]);
  const ownerName = useCallback(
    (id: string | null) =>
      (id && ownerNames.get(id)) ?? (id === me.user.id ? me.user.name : 'Unknown user'),
    [ownerNames, me.user.id, me.user.name],
  );
  const shareOptions: ShareOptions = useMemo(
    () => ({
      users: owners
        .filter((o) => o.active && o.userId)
        .map((o) => ({ id: o.userId, name: o.name })),
      teams: teams.map((t) => ({ id: t.id, name: t.name })),
    }),
    [owners, teams],
  );

  const view = result?.data ?? [];
  const total = result?.total ?? 0;
  const businessCount = result?.businessCount ?? 0;
  const limit = result?.limit ?? TEMPLATE_LIMIT;
  const atLimit = (adding = 1) => businessCount + adding > limit;
  const pager = pagerModel(total, page);
  const filteredOn = !!query.trim() || owner.type !== 'any';
  // Folder rows (HubSpot: folders first) on the first page of the unfiltered, top-level list.
  const folderRows = !activeFolder && !filteredOn && pager.current === 1 ? folders : [];

  const reset = () => {
    setPage(1);
    setSelected(new Set());
  };
  const openFolder = (f: TemplateFolder | null) => {
    setFolderId(f?.id ?? null);
    reset();
  };

  // --- selection ---
  const visibleKeys = [...folderRows.map((f) => folderKey(f.id)), ...view.map((t) => t.id)];
  const onPage = visibleKeys.filter((k) => selected.has(k)).length;
  const allOn = visibleKeys.length > 0 && onPage === visibleKeys.length;
  const someOn = onPage > 0 && onPage < visibleKeys.length;
  const n = selected.size;
  const selIds = [...selected].filter((k) => !k.startsWith('folder:'));
  const selFolderIds = [...selected].filter((k) => k.startsWith('folder:')).map((k) => k.slice(7));
  const toggleKey = (k: string, on: boolean) =>
    setSelected((cur) => {
      const next = new Set(cur);
      if (on) next.add(k);
      else next.delete(k);
      return next;
    });
  const setAll = (on: boolean) =>
    setSelected((cur) => {
      const next = new Set(cur);
      for (const k of visibleKeys) {
        if (on) next.add(k);
        else next.delete(k);
      }
      return next;
    });
  const checkAllRefs = useRef<Array<HTMLInputElement | null>>([]);
  useEffect(() => {
    for (const c of checkAllRefs.current) if (c) c.indeterminate = someOn;
  });

  const byId = (id: string) => view.find((t) => t.id === id);

  // --- actions ---
  const openEditor = async (t: MessageTemplate | null) => {
    if (!t) {
      if (atLimit()) {
        toast(`You have reached the limit of ${fmtNum(limit)} templates.`, 'danger');
        return;
      }
      setEditor({ template: null });
      return;
    }
    try {
      // The list leaves out who a restricted template is shared with.
      setEditor({ template: t.visibility === 'restricted' ? await getTemplate(t.id) : t });
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const openSharing = async (t: MessageTemplate) => {
    try {
      const full = t.visibility === 'restricted' ? await getTemplate(t.id) : t;
      setSharing({ template: full, share: shareOf(full.visibility, full.grants) });
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const runMove = async (ids: string[], dest: TemplateFolder | null) => {
    try {
      const res = await bulkMoveTemplates(ids, dest?.id ?? null);
      setMoving(null);
      setSelected(new Set());
      if (res.skippedIds.length) {
        toast(
          `${res.skippedIds.length} ${plural(res.skippedIds.length, 'template', 'templates')} could not be moved: only the owner or a settings admin can move them.`,
          'danger',
        );
      }
      if (res.count) toast(moveToast(res.count, dest?.name ?? null));
      reloadAll();
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  /** Ids of the templates in a folder (for the folder row's Move). */
  const templatesIn = async (folder: TemplateFolder): Promise<string[]> => {
    const ids: string[] = [];
    for (let p = 1; p <= 100; p++) {
      const res = await listTemplatePage({ folderId: folder.id, sort: 'name' }, p, 100);
      ids.push(...res.data.map((t) => t.id));
      if (ids.length >= res.total || !res.data.length) break;
    }
    return ids;
  };

  const runDelete = async (d: DeleteState) => {
    try {
      if (d.kind === 'folder') {
        await deleteTemplateFolder(d.folder.id);
        if (folderId === d.folder.id) setFolderId(null);
        toast(`Folder "${d.folder.name}" deleted.`);
      } else {
        let failed = 0;
        let deleted = 0;
        if (d.ids.length) {
          const res = await bulkDeleteTemplates(d.ids);
          deleted = res.count;
          failed += res.skippedIds.length;
        }
        for (const id of d.folderIds) {
          try {
            await deleteTemplateFolder(id);
          } catch {
            failed++;
          }
        }
        if (failed) {
          toast(`${failed} ${plural(failed, 'item', 'items')} could not be deleted.`, 'danger');
        }
        if (deleted) {
          toast(deleted === 1 ? 'Template deleted.' : `${deleted} templates deleted.`);
        } else if (d.folderIds.length > failed) {
          toast(
            `${d.folderIds.length - failed} ${plural(d.folderIds.length - failed, 'folder', 'folders')} deleted.`,
          );
        }
      }
      setSelected(new Set());
      setDeleting(null);
      reloadAll();
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const sortTh = (key: SortState['key'], label: string, cls: string) => {
    const active = sort.key === key;
    return (
      <th
        className={cls}
        scope="col"
        aria-sort={active ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}
      >
        <button
          type="button"
          className={cn('mt-sort', active && 'is-active')}
          data-mt-sort={key}
          onClick={() => {
            setSort(nextSort(sort, key));
            reset();
          }}
        >
          {label}{' '}
          <MtIcon
            name={active ? (sort.dir === 'asc' ? 'arrow-up' : 'arrow-down') : 'sort'}
            size={14}
          />
        </button>
      </th>
    );
  };

  const ownerItems = [
    { value: 'any', label: 'Any' },
    ...teams.map((t) => ({ value: `t:${t.id}`, label: t.name, group: 'Teams', icon: 'team' })),
    ...[...owners]
      .filter((o) => o.userId)
      .sort((a, b) => a.name.localeCompare(b.name))
      .map((o) => ({ value: `u:${o.userId}`, label: o.name, group: 'Users' })),
  ];

  // An Owner filter from the address gets its name once the users and teams are read.
  const ownerLabel = ownerItems.find((i) => i.value === owner.value)?.label ?? owner.label;
  const canSequence = Boolean(me.permissionSet.rules.app.use_sequences);
  const startSequence = () => {
    if (selIds.length > SEQUENCE_TEMPLATES_MAX) {
      toast(
        `Pick at most ${SEQUENCE_TEMPLATES_MAX} templates: a sequence holds 25 steps.`,
        'danger',
      );
      return;
    }
    setBuildAsk(selIds);
  };

  const menuTemplate = rowMenu ? byId(rowMenu.id) : undefined;
  const menuFolder = folderMenu ? folders.find((f) => f.id === folderMenu.id) : undefined;
  const goPage = (p: number) => {
    setPage(p);
    setSelected(new Set());
    const tb = document.querySelector('.mtt-page .mt-toolbar');
    if (tb && tb.getBoundingClientRect().top < 0) tb.scrollIntoView();
  };

  return (
    // Dialogs and menus are drawn on <body>, outside the app's font: they carry it themselves.
    <MtScopeContext.Provider value={`mtt-page ${lexend.className}`}>
      <div className="mtt-page" id="mtApp">
        <MttSprite />
        <div className="mt-topbar">
          <div className="mt-container mt-topbar__in">
            <h1 className="mt-title">Message templates</h1>
            <div className="mt-topbar__actions">
              <span className="mt-count" id="mtCount" aria-live="polite">
                {result ? `${fmtNum(businessCount)} of ${fmtNum(limit)} created` : ''}
              </span>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                id="btnNewFolder"
                onClick={() => setFolderModal({ mode: 'create' })}
              >
                New folder
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                id="btnAnalyze"
                aria-haspopup="menu"
                aria-expanded={headMenu?.kind === 'analyze'}
                onClick={(e) => {
                  const anchor = e.currentTarget;
                  setHeadMenu((cur) =>
                    cur?.kind === 'analyze' ? null : { kind: 'analyze', anchor },
                  );
                }}
              >
                Analyze
                <MtIcon name="chevron-down" size={14} />
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                id="btnExport"
                onClick={() => setExporting(true)}
              >
                Export
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--primary btn-crm--sm"
                id="btnNewTemplate"
                aria-haspopup="menu"
                aria-expanded={headMenu?.kind === 'new'}
                onClick={(e) => {
                  const anchor = e.currentTarget;
                  setHeadMenu((cur) => (cur?.kind === 'new' ? null : { kind: 'new', anchor }));
                }}
              >
                New template
                <MtIcon name="chevron-down" size={14} />
              </button>
            </div>
          </div>
        </div>

        <div className="mt-main" id="mtMain">
          <div className="mt-container">
            <div className="mt-toolbar">
              <div className="mt-search">
                <input
                  className="input"
                  type="search"
                  id="mtSearch"
                  placeholder="Search templates"
                  aria-label="Search templates"
                  autoComplete="off"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                />
                <MtIcon name="search" className="mt-search__icon" />
              </div>
              <button
                ref={setOwnerBtn}
                type="button"
                className="mt-owner-btn"
                id="mtOwnerBtn"
                aria-haspopup="listbox"
                aria-expanded={ownerOpen}
                onClick={() => setOwnerOpen((o) => !o)}
              >
                <span className="mt-owner-btn__label">Owner:</span>
                <strong id="mtOwnerVal">{ownerLabel}</strong>
                <MtIcon name="chevron-down" size={14} />
              </button>
            </div>

            {activeFolder ? (
              <div className="mt-folder-viewbar" id="mtFolderViewBar">
                <button type="button" className="mt-link-btn" onClick={() => openFolder(null)}>
                  ‹ All templates
                </button>
                <strong>{activeFolder.name}</strong>
              </div>
            ) : null}

            <div className="mt-table-wrap">
              <table className="mt-table" id="mtTable">
                <caption className="mt-sr">Message templates</caption>
                <thead>
                  <tr
                    className="mt-head-row"
                    id="mtHeadRow"
                    style={{ visibility: n > 0 ? 'collapse' : 'visible' }}
                  >
                    <th className="mt-col-check" scope="col">
                      <label className="check">
                        <input
                          ref={(el) => {
                            checkAllRefs.current[0] = el;
                          }}
                          type="checkbox"
                          id="mtCheckAll"
                          aria-label="Select all templates on this page"
                          checked={allOn}
                          onChange={(e) => setAll(e.target.checked)}
                        />
                        <span className="check__box" />
                      </label>
                    </th>
                    {sortTh('name', 'Name', 'mt-col-name')}
                    {sortTh('owner', 'Owner', 'mt-col-owner')}
                    {sortTh('created', 'Date created', 'mt-col-date')}
                    {sortTh('modified', 'Date modified', 'mt-col-date')}
                  </tr>
                  <tr className="mt-bulk-row" id="mtBulkRow" hidden={n === 0}>
                    <th className="mt-col-check" scope="col">
                      <label className="check">
                        <input
                          ref={(el) => {
                            checkAllRefs.current[1] = el;
                          }}
                          type="checkbox"
                          id="mtCheckAll2"
                          aria-label="Select all templates on this page"
                          checked={allOn}
                          onChange={(e) => setAll(e.target.checked)}
                        />
                        <span className="check__box" />
                      </label>
                    </th>
                    <th colSpan={4} scope="colgroup">
                      <div className="mt-bulk">
                        <span className="mt-bulk__count" id="mtBulkCount" aria-live="polite">
                          {n} selected
                        </span>
                        <button
                          type="button"
                          className="mt-bulk__btn"
                          id="bulkMove"
                          disabled={!selIds.length}
                          onClick={() => setMoving(selIds)}
                        >
                          <MtIcon name="folder" />
                          Move to folder
                        </button>
                        <button
                          type="button"
                          className="mt-bulk__btn"
                          id="bulkDelete"
                          onClick={() =>
                            setDeleting(
                              !selIds.length && selFolderIds.length === 1
                                ? {
                                    kind: 'folder',
                                    folder: folders.find((f) => f.id === selFolderIds[0])!,
                                  }
                                : { kind: 'templates', ids: selIds, folderIds: selFolderIds },
                            )
                          }
                        >
                          <MtIcon name="trash" />
                          Delete
                        </button>
                        <button
                          type="button"
                          className="mt-bulk__btn"
                          id="bulkSequence"
                          disabled={!selIds.length || !canSequence}
                          title={
                            canSequence
                              ? undefined
                              : 'Your permissions do not allow using sequences'
                          }
                          onClick={startSequence}
                        >
                          <MtIcon name="sequence" />
                          Build a sequence
                        </button>
                      </div>
                    </th>
                  </tr>
                </thead>
                <tbody id="mtRows">
                  {result === null ? (
                    <tr>
                      <td colSpan={5} className="mt-cell-empty">
                        {loadError ? (
                          <>
                            Could not load templates.{' '}
                            <button type="button" className="mt-link-btn" onClick={load}>
                              Try again
                            </button>
                          </>
                        ) : (
                          'Loading templates…'
                        )}
                      </td>
                    </tr>
                  ) : (
                    <>
                      {folderRows.map((f) => {
                        const k = folderKey(f.id);
                        const on = selected.has(k);
                        return (
                          <tr
                            key={k}
                            className={cn(
                              'mt-folder-row',
                              on && 'is-selected',
                              folderMenu?.id === f.id && 'is-menu-open',
                            )}
                            data-mt-folder-row={f.id}
                          >
                            <td className="mt-col-check">
                              <label className="check">
                                <input
                                  type="checkbox"
                                  aria-label={`Folder ${f.name}`}
                                  checked={on}
                                  onChange={(e) => toggleKey(k, e.target.checked)}
                                />
                                <span className="check__box" />
                              </label>
                            </td>
                            <td className="mt-col-name">
                              <div className="mt-cell-name mt-folder-row__name">
                                <MtIcon name="folder" size={20} />
                                <button
                                  type="button"
                                  className="mt-name-link mt-folder-name-link"
                                  title={`Folder: ${f.name}`}
                                  onClick={() => openFolder(f)}
                                >
                                  {f.name}
                                </button>
                                <span className="mt-folder-tag mt-folder-count">
                                  {fmtNum(f.templateCount)}{' '}
                                  {plural(f.templateCount, 'template', 'templates')}
                                </span>
                                <button
                                  type="button"
                                  className="mt-actions-btn mt-folder-actions-btn"
                                  aria-haspopup="menu"
                                  aria-expanded={folderMenu?.id === f.id}
                                  aria-label={`Actions for folder ${f.name}`}
                                  onClick={(e) => {
                                    const anchor = e.currentTarget;
                                    setFolderMenu((cur) =>
                                      cur?.id === f.id ? null : { id: f.id, anchor },
                                    );
                                  }}
                                >
                                  Actions
                                  <MtIcon name="chevron-down" size={14} />
                                </button>
                              </div>
                            </td>
                            <td className="mt-cell-owner">{ownerName(f.ownerId)}</td>
                            <td className="mt-cell-date" title={isoDate(f.createdAt)}>
                              {relTime(f.createdAt)}
                            </td>
                            <td className="mt-cell-date" title={isoDate(f.updatedAt)}>
                              {relTime(f.updatedAt)}
                            </td>
                          </tr>
                        );
                      })}
                      {!view.length && !folderRows.length ? (
                        <tr>
                          <td colSpan={5} className="mt-cell-empty">
                            {filteredOn
                              ? 'No templates match your search or filter.'
                              : activeFolder
                                ? 'This folder is empty.'
                                : 'No templates yet.'}
                          </td>
                        </tr>
                      ) : null}
                      {view.map((t) => {
                        const on = selected.has(t.id);
                        return (
                          <tr
                            key={t.id}
                            data-mt-id={t.id}
                            className={cn(
                              on && 'is-selected',
                              rowMenu?.id === t.id && 'is-menu-open',
                            )}
                          >
                            <td className="mt-col-check">
                              <label className="check">
                                <input
                                  type="checkbox"
                                  aria-label={`Select ${t.name}`}
                                  checked={on}
                                  onChange={(e) => toggleKey(t.id, e.target.checked)}
                                />
                                <span className="check__box" />
                              </label>
                            </td>
                            <td className="mt-col-name">
                              <div className="mt-cell-name">
                                <button
                                  type="button"
                                  className="mt-name-link"
                                  data-mt-act="edit"
                                  onClick={() => void openEditor(t)}
                                >
                                  {t.name}
                                </button>
                                {t.folder ? (
                                  <span className="mt-folder-tag" title={`Folder: ${t.folder}`}>
                                    <MtIcon name="folder" size={14} />
                                    {t.folder}
                                  </span>
                                ) : null}
                                <button
                                  type="button"
                                  className="mt-actions-btn"
                                  aria-haspopup="menu"
                                  aria-expanded={rowMenu?.id === t.id}
                                  aria-label={`Actions for ${t.name}`}
                                  onClick={(e) => {
                                    const anchor = e.currentTarget;
                                    setRowMenu((cur) =>
                                      cur?.id === t.id ? null : { id: t.id, anchor },
                                    );
                                  }}
                                >
                                  Actions
                                  <MtIcon name="chevron-down" size={14} />
                                </button>
                              </div>
                            </td>
                            <td className="mt-cell-owner">{ownerName(t.ownerId)}</td>
                            <td className="mt-cell-date" title={isoDate(t.createdAt)}>
                              {relTime(t.createdAt)}
                            </td>
                            <td className="mt-cell-date" title={isoDate(t.updatedAt)}>
                              {relTime(t.updatedAt)}
                            </td>
                          </tr>
                        );
                      })}
                    </>
                  )}
                </tbody>
              </table>
            </div>

            {/* Design v2 renderPager: First, Prev, up to 11 numbered pages, Next, Last; no rows-per-page. */}
            <nav className="mt-pager" id="mtPager" aria-label="Pagination">
              {total > 0 ? (
                <>
                  <button
                    type="button"
                    className="mt-pager__btn"
                    disabled={pager.atStart}
                    aria-label="First page"
                    onClick={() => goPage(1)}
                  >
                    <MtIcon name="chevrons-left" size={14} />
                    First
                  </button>
                  <button
                    type="button"
                    className="mt-pager__btn"
                    disabled={pager.atStart}
                    aria-label="Previous page"
                    onClick={() => goPage(pager.current - 1)}
                  >
                    <MtIcon name="chevron-left" size={14} />
                    Prev
                  </button>
                  {pager.numbers.map((p) => (
                    <button
                      key={p}
                      type="button"
                      className={cn('mt-pager__btn', p === pager.current && 'is-current')}
                      aria-current={p === pager.current ? 'page' : undefined}
                      aria-label={`Page ${p}`}
                      onClick={() => p !== pager.current && goPage(p)}
                    >
                      {p}
                    </button>
                  ))}
                  <button
                    type="button"
                    className="mt-pager__btn"
                    disabled={pager.atEnd}
                    aria-label="Next page"
                    onClick={() => goPage(pager.current + 1)}
                  >
                    Next
                    <MtIcon name="chevron-right" size={14} />
                  </button>
                  <button
                    type="button"
                    className="mt-pager__btn"
                    disabled={pager.atEnd}
                    aria-label="Last page"
                    onClick={() => goPage(pager.pages)}
                  >
                    Last
                    <MtIcon name="chevrons-right" size={14} />
                  </button>
                </>
              ) : null}
            </nav>
          </div>
        </div>

        {headMenu?.kind === 'analyze' ? (
          <MtPop anchor={headMenu.anchor} onClose={() => setHeadMenu(null)} role="menu">
            <MtMenu
              onClose={() => setHeadMenu(null)}
              items={[
                {
                  label: 'View sales content analytics',
                  onClick: () => router.push('/templates/analytics'),
                },
                {
                  label: 'View reports for dashboards',
                  onClick: () => router.push('/reports/library'),
                },
              ]}
            />
          </MtPop>
        ) : null}
        {headMenu?.kind === 'new' ? (
          <MtPop anchor={headMenu.anchor} onClose={() => setHeadMenu(null)} role="menu" align="end">
            <MtMenu
              onClose={() => setHeadMenu(null)}
              items={[
                { label: 'From scratch', onClick: () => void openEditor(null) },
                {
                  label: 'From template library',
                  onClick: () => {
                    if (atLimit()) {
                      toast(`You have reached the limit of ${fmtNum(limit)} templates.`, 'danger');
                      return;
                    }
                    setLibrary(true);
                  },
                },
              ]}
            />
          </MtPop>
        ) : null}

        {ownerOpen ? (
          <MtPop anchor={ownerBtn} onClose={() => setOwnerOpen(false)}>
            <MtListbox
              items={ownerItems}
              selected={owner.value}
              searchable
              searchPlaceholder="Search owner"
              width={340}
              footer={
                <a className="link" href="/settings/users" target="_blank" rel="noopener">
                  Manage users & teams
                  <MtIcon name="external" size={14} />
                </a>
              }
              onSelect={(it) => {
                setOwnerOpen(false);
                setOwner(ownerFilterOf(it.value, it.label));
                reset();
              }}
            />
          </MtPop>
        ) : null}

        {rowMenu && menuTemplate ? (
          <MtPop anchor={rowMenu.anchor} onClose={() => setRowMenu(null)} align="end" role="menu">
            <MtMenu
              onClose={() => setRowMenu(null)}
              items={[
                {
                  label: 'Clone',
                  onClick: () => {
                    if (atLimit()) {
                      toast(`You have reached the limit of ${fmtNum(limit)} templates.`, 'danger');
                      return;
                    }
                    setCloning(menuTemplate);
                  },
                },
                {
                  label: 'Move',
                  disabled: !menuTemplate.canEdit,
                  onClick: () => setMoving([menuTemplate.id]),
                },
                {
                  label: 'Manage sharing',
                  disabled: !menuTemplate.canEdit,
                  onClick: () => void openSharing(menuTemplate),
                },
                {
                  label: 'Delete',
                  disabled: !menuTemplate.canEdit,
                  onClick: () =>
                    setDeleting({ kind: 'templates', ids: [menuTemplate.id], folderIds: [] }),
                },
              ]}
            />
          </MtPop>
        ) : null}

        {folderMenu && menuFolder ? (
          <MtPop
            anchor={folderMenu.anchor}
            onClose={() => setFolderMenu(null)}
            align="end"
            role="menu"
          >
            <MtMenu
              onClose={() => setFolderMenu(null)}
              items={[
                {
                  label: 'Clone',
                  onClick: () => setFolderModal({ mode: 'clone', from: menuFolder }),
                },
                {
                  label: 'Rename',
                  disabled: !menuFolder.canEdit,
                  onClick: () => setFolderModal({ mode: 'rename', folder: menuFolder }),
                },
                {
                  label: 'Move',
                  onClick: () => {
                    templatesIn(menuFolder).then(
                      (ids) => setMoving(ids),
                      (err: unknown) => toast(errorText(err), 'danger'),
                    );
                  },
                },
                {
                  label: 'Manage sharing',
                  disabled: !menuFolder.canEdit,
                  onClick: () => setSharingFolder(menuFolder),
                },
                {
                  label: 'Delete',
                  disabled: !menuFolder.canEdit,
                  onClick: () => setDeleting({ kind: 'folder', folder: menuFolder }),
                },
              ]}
            />
          </MtPop>
        ) : null}

        {editor ? (
          <TemplateEditorModal
            template={editor.template}
            initialFolderId={editor.template ? undefined : (activeFolder?.id ?? undefined)}
            folders={folders}
            shareOptions={shareOptions}
            me={me.user}
            ownerName={(id) => ownerName(id)}
            atLimit={() => atLimit()}
            onClose={() => setEditor(null)}
            onSaved={(t, created) => {
              setEditor(null);
              toast(created ? `Template "${t.name}" saved.` : `Template "${t.name}" updated.`);
              reloadAll();
            }}
          />
        ) : null}

        {cloning ? (
          <CloneModal
            template={cloning}
            folders={folders}
            onClose={() => setCloning(null)}
            onCloned={() => {
              toast(`Cloned "${cloning.name}".`);
              setCloning(null);
              reloadAll();
            }}
          />
        ) : null}

        {moving ? (
          <MoveModal
            ids={moving}
            folders={folders}
            onFolderCreated={(f) => setFolders((cur) => [...cur, f])}
            onClose={() => setMoving(null)}
            onMove={(dest) => runMove(moving, dest)}
          />
        ) : null}

        {folderModal ? (
          <FolderModal
            state={folderModal}
            folders={folders}
            onClose={() => setFolderModal(null)}
            onSaved={(f, renamed) => {
              setFolderModal(null);
              toast(renamed ? `Folder "${f.name}" updated.` : `Folder "${f.name}" created.`);
              reloadAll();
            }}
          />
        ) : null}

        {deleting ? (
          <DeleteModal
            state={deleting}
            names={
              deleting.kind === 'templates' ? deleting.ids.map((id) => byId(id)?.name ?? '') : []
            }
            otherOwners={
              deleting.kind === 'templates'
                ? deleting.ids
                    .map((id) => byId(id))
                    .filter((t): t is MessageTemplate => !!t && t.ownerId !== me.user.id)
                    .map((t) => ownerName(t.ownerId))
                : []
            }
            folderNames={
              deleting.kind === 'templates'
                ? deleting.folderIds.map((id) => folders.find((f) => f.id === id)?.name ?? '')
                : []
            }
            onClose={() => setDeleting(null)}
            onConfirm={() => runDelete(deleting)}
          />
        ) : null}

        {sharing ? (
          <ShareDrawer
            share={sharing.share}
            options={shareOptions}
            onClose={() => setSharing(null)}
            onSave={async (s) => {
              try {
                await updateTemplate(sharing.template.id, shareToApi(s));
                setSharing(null);
                toast('Sharing settings saved.');
                load();
              } catch (err) {
                toast(errorText(err), 'danger');
              }
            }}
          />
        ) : null}

        {sharingFolder ? (
          <ShareDrawer
            noun="folder"
            privateTip="Only you and settings admins see this folder. Its templates keep their own sharing"
            share={shareOf(sharingFolder.visibility ?? 'shared', sharingFolder.grants)}
            options={shareOptions}
            onClose={() => setSharingFolder(null)}
            onSave={async (s) => {
              try {
                await shareTemplateFolder(sharingFolder.id, shareToApi(s));
                setSharingFolder(null);
                toast('Folder sharing settings saved.');
                loadFolders();
              } catch (err) {
                toast(errorText(err), 'danger');
              }
            }}
          />
        ) : null}

        {exporting ? (
          <ExportModal
            count={total}
            filtered={filteredOn}
            onClose={() => setExporting(false)}
            onExport={async (format) => {
              try {
                const blob = await exportTemplatesCsv(filters);
                const day = new Date().toISOString().slice(0, 10);
                const name = `message-templates-${day}.${format}`;
                let rows = 0;
                if (format === 'csv') {
                  rows = Math.max(0, parseCsv(await blob.text()).length - 1);
                  saveFile(blob, name);
                } else {
                  const parsed = parseCsv(await blob.text());
                  rows = Math.max(0, parsed.length - 1);
                  const file = spreadsheetFile({ name: 'Message templates', rows: parsed }, format);
                  saveFile(new Blob([file as BlobPart], { type: SPREADSHEET_MIME[format] }), name);
                }
                setExporting(false);
                toast(`Export ready: ${rows} ${plural(rows, 'template', 'templates')}.`);
              } catch (err) {
                toast(errorText(err), 'danger');
              }
            }}
          />
        ) : null}

        {buildAsk ? (
          <BuildSequenceModal
            ids={buildAsk}
            onClose={() => setBuildAsk(null)}
            onGo={(mode) => router.push(sequenceFromTemplatesHref(mode, buildAsk))}
          />
        ) : null}

        {library ? (
          <LibraryModal
            onClose={() => setLibrary(false)}
            canAdd={(k) => !atLimit(k)}
            limit={limit}
            onSaved={(count) => {
              setLibrary(false);
              toast(`${count} ${plural(count, 'template', 'templates')} added to your list.`);
              reloadAll();
            }}
          />
        ) : null}
      </div>
    </MtScopeContext.Provider>
  );
}

// --- Modals --------------------------------------------------------------------------------------

/** The design's folder search menu inside a dialog (Clone's "Save template to a folder"). */
function CloneModal({
  template,
  folders,
  onClose,
  onCloned,
}: {
  template: MessageTemplate;
  folders: TemplateFolder[];
  onClose: () => void;
  onCloned: (t: MessageTemplate) => void;
}) {
  const toast = useToast();
  const [name, setName] = useState(`${template.name} (copy)`.slice(0, 191));
  const [folderId, setFolderId] = useState<string | null>(template.folderId);
  const [menuOpen, setMenuOpen] = useState(false);
  const [q, setQ] = useState('');
  const [saving, setSaving] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (!menuOpen) return;
    searchRef.current?.focus();
    const onDoc = (e: MouseEvent) => {
      if (!wrapRef.current?.contains(e.target as Node)) setMenuOpen(false);
    };
    document.addEventListener('click', onDoc);
    return () => document.removeEventListener('click', onDoc);
  }, [menuOpen]);
  const query = q.trim().toLowerCase();
  const options = [
    { id: null as string | null, name: 'No folder' },
    ...[...folders].sort((a, b) => a.name.localeCompare(b.name)),
  ].filter((o) => !query || o.name.toLowerCase().includes(query));
  const label = folders.find((f) => f.id === folderId)?.name ?? 'No folder';

  const save = async () => {
    const nm = name.trim();
    if (!nm) {
      document.getElementById('cloneName')?.focus();
      toast('Enter a name for the cloned template.', 'danger');
      return;
    }
    setSaving(true);
    try {
      onCloned(await cloneTemplate(template.id, { name: nm, folderId }));
    } catch (err) {
      toast(errorText(err), 'danger');
      setSaving(false);
    }
  };

  return (
    <MtModal
      id="mClone"
      onClose={onClose}
      labelledBy="mCloneT"
      className="mt-modal--sm mt-clone-modal"
      focus="#cloneName"
    >
      <MtModalHead id="mCloneT" title="Clone template" onClose={onClose} />
      <div className="mt-modal__body">
        <div className="field">
          <label className="field__label" htmlFor="cloneName">
            Name your clone of this template
          </label>
          <input
            className="input"
            type="text"
            id="cloneName"
            maxLength={150}
            autoComplete="off"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </div>
        <div className="field mt-clone-folder-field">
          <label className="field__label" htmlFor="cloneFolderTrigger">
            Save template to a folder
          </label>
          <div className="mt-clone-folder" ref={wrapRef}>
            <button
              type="button"
              className="input mt-clone-folder-trigger"
              id="cloneFolderTrigger"
              aria-haspopup="listbox"
              aria-expanded={menuOpen}
              onClick={() => {
                setQ('');
                setMenuOpen((o) => !o);
              }}
            >
              <span id="cloneFolderLabel">{label}</span>
              <MtIcon name="chevron-down" size={14} />
            </button>
            <div className="mt-clone-folder-menu" id="cloneFolderMenu" hidden={!menuOpen}>
              <div className="mt-search mt-search--block">
                <input
                  ref={searchRef}
                  className="input"
                  type="search"
                  id="cloneFolderSearch"
                  placeholder="Search"
                  aria-label="Search folders"
                  autoComplete="off"
                  value={q}
                  onChange={(e) => setQ(e.target.value)}
                />
                <MtIcon name="search" className="mt-search__icon" />
              </div>
              <ul id="cloneFolderList" role="listbox" aria-label="Folders">
                {options.length ? (
                  options.map((o) => (
                    <li key={o.id ?? 'none'} role="presentation">
                      <button
                        type="button"
                        className="mt-clone-folder-option"
                        role="option"
                        aria-selected={folderId === o.id ? 'true' : 'false'}
                        onClick={() => {
                          setFolderId(o.id);
                          setMenuOpen(false);
                        }}
                      >
                        {o.name}
                      </button>
                    </li>
                  ))
                ) : (
                  <li className="mt-clone-folder-empty">No folders found</li>
                )}
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="cloneSave"
          disabled={saving}
          onClick={() => void save()}
        >
          Save
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </MtModal>
  );
}

function MoveModal({
  ids,
  folders,
  onFolderCreated,
  onClose,
  onMove,
}: {
  ids: string[];
  folders: TemplateFolder[];
  onFolderCreated: (f: TemplateFolder) => void;
  onClose: () => void;
  onMove: (dest: TemplateFolder | null) => Promise<void>;
}) {
  const toast = useToast();
  const [q, setQ] = useState('');
  // undefined: nothing picked yet; null: No folder.
  const [sel, setSel] = useState<string | null | undefined>(undefined);
  const [newBtn, setNewBtn] = useState<HTMLButtonElement | null>(null);
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState('');
  const [newInvalid, setNewInvalid] = useState(false);
  const [busy, setBusy] = useState(false);
  const query = q.trim().toLowerCase();
  const items = [
    { id: null as string | null, name: 'No folder', icon: 'file' },
    ...[...folders]
      .sort((a, b) => a.name.localeCompare(b.name))
      .map((f) => ({ id: f.id as string | null, name: f.name, icon: 'folder' })),
  ].filter((it) => !query || it.name.toLowerCase().includes(query));

  const create = async () => {
    if (folderNameProblem(newName, folders)) {
      setNewInvalid(true);
      return;
    }
    try {
      const f = await createTemplateFolder(newName.trim());
      onFolderCreated(f);
      setSel(f.id);
      setCreating(false);
      setNewName('');
      toast(`Folder "${f.name}" created.`);
    } catch (err) {
      setNewInvalid(true);
      toast(errorText(err), 'danger');
    }
  };

  return (
    <MtModal
      id="mMove"
      onClose={onClose}
      labelledBy="mMoveT"
      className="mt-modal--md"
      focus="#moveSearch"
    >
      <MtModalHead id="mMoveT" title="Move to folder" onClose={onClose} />
      <div className="mt-modal__body">
        <div className="mt-search mt-search--block">
          <input
            className="input"
            type="search"
            id="moveSearch"
            placeholder="Search"
            aria-label="Search folders"
            autoComplete="off"
            value={q}
            onChange={(e) => setQ(e.target.value)}
          />
          <MtIcon name="search" className="mt-search__icon" />
        </div>
        <p className="mt-help-text" id="moveEmptyNote" hidden={ids.length > 0}>
          This folder has no templates to move yet.
        </p>
        <ul className="mt-folder-list" id="moveList" role="listbox" aria-label="Folders">
          {items.map((it) => (
            <li key={it.id ?? 'none'} role="presentation">
              <button
                type="button"
                className="mt-folder-item"
                role="option"
                aria-selected={sel === it.id ? 'true' : 'false'}
                onClick={() => setSel(it.id)}
              >
                <MtIcon name={it.icon} />
                {it.name}
              </button>
            </li>
          ))}
        </ul>
        <button
          ref={setNewBtn}
          type="button"
          className="mt-link-btn mt-link-btn--strong"
          id="moveNew"
          aria-haspopup="dialog"
          aria-expanded={creating}
          onClick={() => setCreating((c) => !c)}
        >
          + Create new folder
        </button>
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="moveGo"
          disabled={sel === undefined || !ids.length || busy}
          onClick={async () => {
            setBusy(true);
            await onMove(sel ? (folders.find((f) => f.id === sel) ?? null) : null);
            setBusy(false);
          }}
        >
          Move
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
      {creating ? (
        <MtPop anchor={newBtn} onClose={() => setCreating(false)} placement="top" align="start">
          <div className="mt-pop__pad" style={{ width: 260 }}>
            <div className="mt-panel__title" style={{ marginBottom: 12 }}>
              Create new folder
            </div>
            <div className={cn('field', newInvalid && 'is-invalid')}>
              <span className="field__label">Folder Name</span>
              <input
                className="input"
                type="text"
                maxLength={100}
                autoComplete="off"
                aria-label="Folder name"
                autoFocus
                value={newName}
                onChange={(e) => {
                  setNewName(e.target.value);
                  setNewInvalid(false);
                }}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault();
                    void create();
                  }
                }}
              />
              <p className="field__error">A folder with this name already exists.</p>
            </div>
            <div className="mt-panel__actions">
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => void create()}
              >
                Save
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => setCreating(false)}
              >
                Cancel
              </button>
            </div>
          </div>
        </MtPop>
      ) : null}
    </MtModal>
  );
}

function FolderModal({
  state,
  folders,
  onClose,
  onSaved,
}: {
  state:
    | { mode: 'create' }
    | { mode: 'clone'; from: TemplateFolder }
    | { mode: 'rename'; folder: TemplateFolder };
  folders: TemplateFolder[];
  onClose: () => void;
  onSaved: (f: TemplateFolder, renamed: boolean) => void;
}) {
  const toast = useToast();
  const [name, setName] = useState(
    state.mode === 'rename'
      ? state.folder.name
      : state.mode === 'clone'
        ? `${state.from.name} (copy)`.slice(0, 100)
        : '',
  );
  const [invalid, setInvalid] = useState(false);
  const [saving, setSaving] = useState(false);
  const renaming = state.mode === 'rename';
  const title =
    state.mode === 'rename'
      ? 'Edit folder'
      : state.mode === 'clone'
        ? 'Clone folder'
        : 'Create new folder';
  const save = async () => {
    if (folderNameProblem(name, folders, renaming ? state.folder.id : undefined)) {
      setInvalid(true);
      document.getElementById('folderName')?.focus();
      return;
    }
    setSaving(true);
    try {
      const f = renaming
        ? await renameTemplateFolder(state.folder.id, name.trim())
        : await createTemplateFolder(name.trim());
      onSaved(f, renaming);
    } catch (err) {
      setInvalid(true);
      toast(errorText(err), 'danger');
      setSaving(false);
    }
  };
  return (
    <MtModal
      id="mFolder"
      onClose={onClose}
      labelledBy="mFolderT"
      className="mt-modal--sm"
      focus="#folderName"
    >
      <MtModalHead id="mFolderT" title={title} onClose={onClose} />
      <div className="mt-modal__body">
        <div className={cn('field', invalid && 'is-invalid')}>
          <label className="field__label" htmlFor="folderName">
            Folder name
          </label>
          <input
            className="input"
            type="text"
            id="folderName"
            maxLength={100}
            autoComplete="off"
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              setInvalid(false);
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && name.trim()) void save();
            }}
          />
          <p className="field__error" id="folderErr">
            A folder with this name already exists.
          </p>
        </div>
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="folderGo"
          disabled={!name.trim() || saving}
          onClick={() => void save()}
        >
          {renaming ? 'Save changes' : 'Create folder'}
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </MtModal>
  );
}

function DeleteModal({
  state,
  names,
  otherOwners,
  folderNames,
  onClose,
  onConfirm,
}: {
  state: DeleteState;
  names: string[];
  otherOwners: string[];
  folderNames: string[];
  onClose: () => void;
  onConfirm: () => Promise<void>;
}) {
  const [busy, setBusy] = useState(false);
  const [inUse, setInUse] = useState<string | null>(null);
  const ids = state.kind === 'templates' ? state.ids.join(',') : '';
  // Deleting a template a sequence sends would stop that email: say so first.
  useEffect(() => {
    if (!ids) return;
    let alive = true;
    templateUsage(ids.split(',')).then(
      (res) => alive && setInUse(sequenceUseWarning(res.sequenceCount, res.usedTemplateIds.length)),
      () => {
        // The delete still works without the warning.
      },
    );
    return () => {
      alive = false;
    };
  }, [ids]);
  let copy: { title: string; warning: string | null; text: string; button: string };
  if (state.kind === 'folder') {
    copy = { ...folderDeleteCopy(state.folder.name), warning: null };
  } else if (!names.length) {
    const f = folderNames.length;
    copy = {
      title: `Delete ${f} ${plural(f, 'folder', 'folders')}?`,
      warning: null,
      text: folderDeleteCopy('').text,
      button: f === 1 ? 'Delete folder' : 'Delete folders',
    };
  } else {
    copy = deleteCopy({ names, otherOwners });
    if (folderNames.length) {
      copy = {
        ...copy,
        title: `Delete ${names.length} ${plural(names.length, 'template', 'templates')} and ${folderNames.length} ${plural(folderNames.length, 'folder', 'folders')}?`,
        text: `${copy.text} Templates in the selected folders will be moved to No folder.`,
      };
    }
  }
  return (
    <MtModal
      id="mDelete"
      onClose={onClose}
      labelledBy="mDeleteT"
      describedBy="mDeleteD"
      role="alertdialog"
      className="mt-modal--sm"
      focus="#deleteGo"
    >
      <MtModalHead id="mDeleteT" title={copy.title} onClose={onClose} />
      <div className="mt-modal__body" id="mDeleteD">
        {copy.warning || inUse ? (
          <div className="mt-alert mt-alert--warning" id="mDeleteWarn">
            <strong>Heads up!</strong>
            {copy.warning ? <p id="mDeleteWarnText">{copy.warning}</p> : null}
            {inUse ? <p id="mDeleteUseText">{inUse}</p> : null}
          </div>
        ) : null}
        <p className="mt-text" id="mDeleteText">
          {copy.text}
        </p>
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className="btn-crm btn-crm--danger"
          id="deleteGo"
          disabled={busy}
          onClick={async () => {
            setBusy(true);
            await onConfirm();
            setBusy(false);
          }}
        >
          {copy.button}
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </MtModal>
  );
}

function ExportModal({
  count,
  filtered,
  onClose,
  onExport,
}: {
  count: number;
  filtered: boolean;
  onClose: () => void;
  onExport: (format: SpreadsheetFormat) => Promise<void>;
}) {
  const [format, setFormat] = useState<SpreadsheetFormat>('csv');
  const [busy, setBusy] = useState(false);
  return (
    <MtModal
      id="mExport"
      onClose={onClose}
      labelledBy="mExportT"
      className="mt-modal--sm"
      focus="#exportGo"
    >
      <MtModalHead id="mExportT" title="Export" onClose={onClose} />
      <div className="mt-modal__body">
        <div className="field">
          <span className="field__label" id="exportFmtLbl">
            File format
          </span>
          <div id="exportSelectHost">
            <MtSelect
              value={format}
              options={[
                { value: 'csv', label: 'CSV' },
                { value: 'xls', label: 'XLS' },
                { value: 'xlsx', label: 'XLSX' },
              ]}
              onChange={(v) => setFormat(v as SpreadsheetFormat)}
            />
          </div>
        </div>
        <p className="mt-text mt-text--lg">The exported file will download to your device.</p>
        <p className="mt-text mt-text--muted" id="exportInfo">
          {exportInfo(count, filtered)}
        </p>
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="exportGo"
          disabled={busy}
          onClick={async () => {
            setBusy(true);
            await onExport(format);
            setBusy(false);
          }}
        >
          Export
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </MtModal>
  );
}

/** The design's "Build a new sequence" dialog and its two ways to start. */
function BuildSequenceModal({
  ids,
  onClose,
  onGo,
}: {
  ids: string[];
  onClose: () => void;
  onGo: (mode: 'scratch' | 'dynamic') => void;
}) {
  const [menu, setMenu] = useState<HTMLElement | null>(null);
  return (
    <MtModal
      id="mSequence"
      onClose={onClose}
      labelledBy="mSequenceT"
      className="mt-modal--sm"
      focus="#btnSeqGo"
    >
      <MtModalHead id="mSequenceT" title="Build a new sequence" onClose={onClose} />
      <div className="mt-modal__body">
        <p className="mt-text">
          This will take you to the sequences tool with the {ids.length} selected{' '}
          {plural(ids.length, 'template', 'templates')}. You can change the order and add steps
          there.
        </p>
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="btnSeqGo"
          aria-haspopup="menu"
          aria-expanded={!!menu}
          onClick={(e) => {
            const anchor = e.currentTarget;
            setMenu((cur) => (cur ? null : anchor));
          }}
        >
          Take me to Sequences
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
      {menu ? (
        <MtPop anchor={menu} onClose={() => setMenu(null)} role="menu">
          <MtMenu
            onClose={() => setMenu(null)}
            items={[
              { label: 'Start from scratch', onClick: () => onGo('scratch') },
              { label: 'Create a dynamic sequence', onClick: () => onGo('dynamic') },
            ]}
          />
        </MtPop>
      ) : null}
    </MtModal>
  );
}

/** The design's Template Library: pick starting points; they're saved as my private templates. */
function LibraryModal({
  onClose,
  canAdd,
  limit,
  onSaved,
}: {
  onClose: () => void;
  canAdd: (count: number) => boolean;
  limit: number;
  onSaved: (count: number) => void;
}) {
  const toast = useToast();
  const [picked, setPicked] = useState<Set<string>>(new Set());
  const [active, setActive] = useState<string | null>(TEMPLATE_LIBRARY[0]?.id ?? null);
  const [saving, setSaving] = useState(false);
  const previewRef = useRef<HTMLDivElement>(null);
  const cur = TEMPLATE_LIBRARY.find((x) => x.id === active);
  useEffect(() => {
    const el = previewRef.current;
    if (!el || !cur) return;
    el.innerHTML = safeEmailHtml(cur.bodyHtml);
    hydrateTokens(el, (t) => labelOfToken(t, NO_CUSTOM), true);
  }, [cur]);
  const count = picked.size;
  const save = async () => {
    const chosen = TEMPLATE_LIBRARY.filter((it) => picked.has(it.id));
    if (!canAdd(chosen.length)) {
      toast(`This would go over the limit of ${fmtNum(limit)} templates.`, 'danger');
      return;
    }
    setSaving(true);
    let saved = 0;
    for (const it of chosen) {
      try {
        await createTemplate({
          name: it.name,
          subject: it.subject,
          bodyHtml: it.bodyHtml,
          visibility: 'personal',
          folderId: null,
        });
        saved++;
      } catch (err) {
        toast(errorText(err), 'danger');
        break;
      }
    }
    setSaving(false);
    if (saved) onSaved(saved);
  };
  let lastCat: string | null = null;
  return (
    <MtModal id="mLibrary" onClose={onClose} labelledBy="mLibraryT" className="mt-modal--lib">
      <MtModalHead id="mLibraryT" title="Template Library" onClose={onClose} />
      <div className="mt-lib">
        <div className="mt-lib__list" id="libList" role="list">
          {TEMPLATE_LIBRARY.map((it) => {
            const head =
              it.category !== lastCat ? (
                <div className="mt-lib__cat" role="presentation">
                  {it.category}
                </div>
              ) : null;
            lastCat = it.category;
            return (
              <div key={it.id} style={{ display: 'contents' }}>
                {head}
                <div
                  className={cn('mt-lib__item', active === it.id && 'is-active')}
                  role="listitem"
                  onClick={(e) => {
                    if ((e.target as Element).closest('.check')) return;
                    setActive(it.id);
                  }}
                >
                  <label className="check">
                    <input
                      type="checkbox"
                      aria-label={`Select ${it.name}`}
                      checked={picked.has(it.id)}
                      onChange={(e) => {
                        const on = e.target.checked;
                        setPicked((p) => {
                          const next = new Set(p);
                          if (on) next.add(it.id);
                          else next.delete(it.id);
                          return next;
                        });
                        setActive(it.id);
                      }}
                    />
                    <span className="check__box" />
                  </label>
                  <button
                    type="button"
                    className="mt-lib__txt"
                    style={{ textAlign: 'left', flex: 1, minWidth: 0 }}
                  >
                    <span className="mt-lib__name">{it.name}</span>
                    <span className="mt-lib__desc">{it.description}</span>
                  </button>
                </div>
              </div>
            );
          })}
        </div>
        <div className="mt-lib__preview" id="libPreview" aria-live="polite">
          {cur ? (
            <>
              <div className="mt-lib__row">
                <strong>Template name:</strong>
                {cur.name}
              </div>
              <div className="mt-lib__row">
                <strong>Subject:</strong>
                {cur.subject}
              </div>
              <div className="mt-mail" ref={previewRef} />
            </>
          ) : null}
        </div>
      </div>
      <div className="mt-modal__foot mt-modal__foot--split">
        <span className="mt-lib__count" id="libCount">
          {count} {plural(count, 'template', 'templates')} selected
        </span>
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="libSave"
          disabled={count === 0 || saving}
          onClick={() => void save()}
        >
          Save my selections
        </button>
      </div>
    </MtModal>
  );
}
