'use client';

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type ReactNode,
} from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { listCustomProperties } from '@/features/custom-properties/api.client';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { useOwners } from '@/features/owners/useOwners';
import { listTaskQueues } from '@/features/task-queues/api.client';
import { TaskQueueDialog, type QueueUser } from '@/features/task-queues/ui/TaskQueueDialog';
import type { TaskQueue } from '@/features/task-queues/types';
import { MtPop } from '@/features/snippets/ui/mt';
import type { EmailTemplate } from '@/features/inbox/types';
import type { SequenceStep, TaskStepPriority } from '@/features/sequences/types';
import { cn } from '@/lib/utils/cn';
import { safeEmailHtml, safeRichHtml } from '@/lib/utils/safe-html';
import { splitTokens } from '@/features/message-templates/model';
import { hydrateTokens, serializeBody } from '@/features/message-templates/ui/editorDom';
import { labelOfToken, SnippetsPanel } from '@/features/message-templates/ui/editorParts';
import {
  hydratePlaceholders,
  placeholderLabel,
  splitPlaceholders,
  usePlaceholders,
} from '@/features/sequences/placeholders';
import { timeAgo } from './DropMenu';
import { SequenceTemplateEditor } from './SequenceTemplateEditor';

// --- Personalization tokens ----------------------------------------------------------------------

/** The merge fields templates and tasks can use (email-templates rules on the API). */
export const TOKEN_GROUPS = [
  {
    key: 'contact',
    label: 'Contact',
    fields: ['firstName', 'lastName', 'fullName', 'email', 'phone', 'jobTitle'],
  },
  {
    key: 'company',
    label: 'Company',
    fields: ['name', 'domain', 'website', 'phone', 'industry', 'city', 'state', 'country'],
  },
  { key: 'deal', label: 'Deal', fields: ['name', 'amount', 'currency', 'closeDate'] },
  { key: 'owner', label: 'Contact owner', fields: ['name', 'firstName', 'lastName', 'email'] },
  // The CRM user sending the email: whoever sends it, or the user a sequence sends as.
  { key: 'sender', label: 'Sender', fields: ['firstName', 'lastName', 'fullName', 'email'] },
] as const;

export const fieldLabel = (field: string) =>
  field.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase());

export type TokenGroupKey = (typeof TOKEN_GROUPS)[number]['key'];
export type TokenField = { name: string; label: string };

/**
 * Each object's own fields (custom properties) can be tokens too, as the API fills them in
 * (QA 16 Oct #126: only six contact tokens were offered). Read once per page.
 */
const customTokens = new Map<TokenGroupKey, Promise<TokenField[]>>();
export function customTokensOf(group: TokenGroupKey): Promise<TokenField[]> {
  if (group === 'owner' || group === 'sender') return Promise.resolve([]);
  let pending = customTokens.get(group);
  if (!pending) {
    pending = listCustomProperties({ objectType: group }).then(
      (defs) =>
        defs
          .filter((d) => !d.archived)
          .map((d) => ({ name: d.name, label: d.label }))
          .sort((a, b) => a.label.localeCompare(b.label)),
      () => {
        customTokens.delete(group);
        return [];
      },
    );
    customTokens.set(group, pending);
  }
  return pending;
}

/**
 * Sequences #36: text with its personalization tokens as chips ("Contact: First Name", HubSpot's
 * and the template editor's look) instead of raw `{{contact.firstName | there}}`. Sequences
 * HubSpot parity: a token's fallback is optional, so one without it is not marked (HubSpot
 * leaves it blank for a contact without a value); a pre-made sequence's placeholder is a
 * "Placeholder: X CONTENT" chip.
 */
export function TokenText({ text }: { text: string }) {
  const placeholders = usePlaceholders();
  return (
    <>
      {splitTokens(text).map((part, i) => {
        if (typeof part === 'string') {
          return splitPlaceholders(part, placeholders).map((piece, j) =>
            typeof piece === 'string' ? (
              piece
            ) : (
              <span key={`${i}.${j}`} className="mt-token seq-token">
                {placeholderLabel(piece.placeholder)}
              </span>
            ),
          );
        }
        return (
          <span
            key={i}
            className="mt-token seq-token"
            title={part.fallback ? `Fallback: ${part.fallback}` : undefined}
          >
            {labelOfToken(part, NO_CUSTOM)}
          </span>
        );
      })}
    </>
  );
}
const NO_CUSTOM = { contact: [], company: [], deal: [], owner: [], sender: [] };

/** "Insert ▾" / "Personalize ▾": a token picker by object type, with search. */
export function TokenMenu({ label, onPick }: { label: string; onPick: (token: string) => void }) {
  const [open, setOpen] = useState(false);
  const [group, setGroup] = useState<TokenGroupKey>('contact');
  const [search, setSearch] = useState('');
  const [custom, setCustom] = useState<TokenField[]>([]);
  const ref = useRef<HTMLDivElement>(null);
  const popRef = useRef<HTMLDivElement>(null);
  /** Opens upward when it would run past the bottom of the window (QA 14 Oct #42). */
  const [up, setUp] = useState(false);

  useLayoutEffect(() => {
    if (!open) {
      setUp(false);
      return;
    }
    const trigger = ref.current?.getBoundingClientRect();
    const height = popRef.current?.offsetHeight ?? 380;
    if (!trigger) return;
    const below = window.innerHeight - trigger.bottom;
    setUp(below < height + 16 && trigger.top > below);
  }, [open, group]);

  useEffect(() => {
    if (!open) return;
    let alive = true;
    void customTokensOf(group).then((fields) => {
      if (alive) setCustom(fields);
    });
    return () => {
      alive = false;
    };
  }, [open, group]);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (!ref.current?.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    window.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const standard = TOKEN_GROUPS.find((g) => g.key === group)!.fields;
  const fields: TokenField[] = [
    ...standard.map((name) => ({ name, label: fieldLabel(name) })),
    ...custom.filter((c) => !(standard as readonly string[]).includes(c.name)),
  ].filter((f) => f.label.toLowerCase().includes(search.trim().toLowerCase()));
  const groupLabel = TOKEN_GROUPS.find((g) => g.key === group)!.label;

  return (
    <div className="dyn-token" ref={ref}>
      <button
        type="button"
        className="dyn-token__trigger"
        aria-haspopup="dialog"
        aria-expanded={open}
        onMouseDown={(e) => e.preventDefault()} // keep the caret where it is
        onClick={() => setOpen((o) => !o)}
      >
        {label} <span aria-hidden>▾</span>
      </button>
      {open ? (
        <div
          ref={popRef}
          className={cn('dyn-token__pop', up && 'is-up')}
          role="dialog"
          aria-label="Insert personalization token"
        >
          <p className="dyn-token__title">Insert personalization token</p>
          <label className="field__label" htmlFor="dynTokenType">
            Type
          </label>
          <select
            id="dynTokenType"
            className="input"
            value={group}
            onChange={(e) => {
              setGroup(e.target.value as TokenGroupKey);
              setCustom([]);
            }}
          >
            {TOKEN_GROUPS.map((g) => (
              <option key={g.key} value={g.key}>
                {g.label}
              </option>
            ))}
          </select>
          <input
            className="input dyn-token__search"
            type="search"
            placeholder={`Search ${groupLabel.toLowerCase()} tokens`}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            aria-label="Search tokens"
          />
          <ul className="dyn-token__list">
            {fields.map((f) => (
              <li key={f.name}>
                <button
                  type="button"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => {
                    onPick(`{{${group}.${f.name}}}`);
                    setOpen(false);
                  }}
                >
                  {f.label}
                </button>
              </li>
            ))}
            {fields.length === 0 ? <li className="crm-text-muted">No matching token</li> : null}
          </ul>
        </div>
      ) : null}
    </div>
  );
}

/** Puts `text` at the caret of an input (or at its end). */
export function insertAtCaret(
  input: HTMLInputElement | HTMLTextAreaElement | null,
  value: string,
  text: string,
  set: (v: string) => void,
) {
  if (!input) {
    set(value + text);
    return;
  }
  const start = input.selectionStart ?? value.length;
  const end = input.selectionEnd ?? value.length;
  set(value.slice(0, start) + text + value.slice(end));
  requestAnimationFrame(() => {
    input.focus();
    input.setSelectionRange(start + text.length, start + text.length);
  });
}

// --- Rich body -----------------------------------------------------------------------------------

/** Email-safe fonts the editor offers (HUB-271); the server keeps `font face`. */
const FONT_FACES = ['Arial', 'Georgia', 'Verdana', 'Times New Roman', 'Courier New', 'Tahoma'];
/** execCommand font sizes (1-7) with their names. */
const FONT_SIZES: Array<[string, string]> = [
  ['2', 'Small'],
  ['3', 'Normal'],
  ['5', 'Large'],
  ['6', 'Huge'],
];

/**
 * A rich-text body: bold, italic, underline, clear, lists, link, and tokens; the email body
 * (not the compact editor) also has font, size, colour, quote, alignment and image (HUB-271).
 */
const NO_CUSTOM_TOKENS = { contact: [], company: [], deal: [], owner: [], sender: [] };
const chipLabel = (t: Parameters<typeof labelOfToken>[0]) => labelOfToken(t, NO_CUSTOM_TOKENS);

export function RichBody({
  initialHtml,
  onChange,
  placeholder,
  label = 'Email body',
  compact = false,
}: {
  initialHtml: string;
  onChange: (html: string) => void;
  placeholder?: string;
  label?: string;
  /** A shorter editor, e.g. task notes; its token menu reads "Personalize" (QA 16 Oct #111). */
  compact?: boolean;
}) {
  const ref = useRef<HTMLDivElement>(null);
  // Sequences #36: tokens show as chips ("Contact: First Name", the template editor's
  // editorDom) and are saved as `{{contact.firstName | there}}` text. Sequences HubSpot parity:
  // a pre-made sequence's placeholders too ("Placeholder: X CONTENT"), saved as their [text].
  const placeholders = usePlaceholders();
  const emit = () => {
    if (ref.current) onChange(serializeBody(ref.current));
  };
  useEffect(() => {
    if (!ref.current) return;
    ref.current.innerHTML = compact ? initialHtml : safeEmailHtml(initialHtml);
    hydrateTokens(ref.current, chipLabel);
    // Only on mount: the editor owns its content afterwards.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // The list arrives after the editor opens; the text is the same once saved again.
  useEffect(() => {
    if (ref.current) hydratePlaceholders(ref.current, placeholders);
  }, [placeholders]);
  /** The "More" menu or the snippet list, placed by the button that opened it. */
  const [pop, setPop] = useState<{ kind: 'more' | 'snippet'; anchor: HTMLElement } | null>(null);
  /** Where the caret was when the snippet list opened (its search box takes the focus). */
  const savedRange = useRef<Range | null>(null);
  const run = (command: string, value?: string) => {
    ref.current?.focus();
    // execCommand is deprecated but still the simplest cross-browser rich-text tool.
    document.execCommand(command, false, value);
    if ((command === 'insertText' || command === 'insertHTML') && ref.current) {
      hydrateTokens(ref.current, chipLabel);
      hydratePlaceholders(ref.current, placeholders);
    }
    emit();
  };
  const tool = (
    label: string,
    title: string,
    command: string,
    className?: string,
    value?: string,
  ) => (
    <button
      type="button"
      className={cn('dyn-rich__tool', className)}
      title={title}
      aria-label={title}
      onMouseDown={(e) => e.preventDefault()}
      onClick={() => run(command, value)}
    >
      {label}
    </button>
  );
  return (
    <div className={cn('dyn-rich', compact && 'dyn-rich--compact')}>
      <div
        ref={ref}
        className="dyn-rich__body"
        contentEditable
        role="textbox"
        aria-multiline="true"
        aria-label={label}
        data-placeholder={placeholder}
        suppressContentEditableWarning
        onInput={emit}
      />
      <div className="dyn-rich__bar">
        {tool('B', 'Bold', 'bold', 'is-bold')}
        {tool('I', 'Italic', 'italic', 'is-italic')}
        {tool('U', 'Underline', 'underline', 'is-underline')}
        {tool('Tx', 'Clear formatting', 'removeFormat')}
        {compact ? (
          <button
            type="button"
            className="dyn-rich__tool"
            aria-haspopup="menu"
            aria-expanded={pop?.kind === 'more'}
            onMouseDown={(e) => e.preventDefault()}
            onClick={(e) => setPop({ kind: 'more', anchor: e.currentTarget })}
          >
            More <CrmIcon name="chevron-down" className="iconSize-14" />
          </button>
        ) : (
          <>
            {tool('•', 'Bulleted list', 'insertUnorderedList')}
            {tool('1.', 'Numbered list', 'insertOrderedList')}
            <select
              className="dyn-rich__select"
              aria-label="Font"
              value=""
              onMouseDown={() => ref.current?.focus()}
              onChange={(e) => e.target.value && run('fontName', e.target.value)}
            >
              <option value="">Font</option>
              {FONT_FACES.map((f) => (
                <option key={f} value={f}>
                  {f}
                </option>
              ))}
            </select>
            <select
              className="dyn-rich__select"
              aria-label="Font size"
              value=""
              onMouseDown={() => ref.current?.focus()}
              onChange={(e) => e.target.value && run('fontSize', e.target.value)}
            >
              <option value="">Size</option>
              {FONT_SIZES.map(([v, label]) => (
                <option key={v} value={v}>
                  {label}
                </option>
              ))}
            </select>
            <label className="dyn-rich__tool dyn-rich__color" title="Text colour">
              <span aria-hidden="true">A</span>
              <input
                type="color"
                aria-label="Text colour"
                defaultValue="#000000"
                onMouseDown={() => ref.current?.focus()}
                onChange={(e) => run('foreColor', e.target.value)}
              />
            </label>
            {tool('❝', 'Quote', 'formatBlock', undefined, 'blockquote')}
            {tool('⇤', 'Align left', 'justifyLeft')}
            {tool('↔', 'Align centre', 'justifyCenter')}
            {tool('⇥', 'Align right', 'justifyRight')}
          </>
        )}
        <button
          type="button"
          className="dyn-rich__tool"
          title="Link"
          aria-label="Link"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => {
            const url = window.prompt('Link address', 'https://');
            if (url && /^https?:\/\//i.test(url)) run('createLink', url);
          }}
        >
          🔗
        </button>
        <button
          type="button"
          className="dyn-rich__tool"
          title="Image"
          aria-label="Image"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => {
            const url = window.prompt('Image address (https://…)', 'https://');
            if (url && /^https:\/\//i.test(url)) run('insertImage', url);
          }}
        >
          🖼
        </button>
        {compact ? (
          <button
            type="button"
            className="dyn-rich__tool"
            title="Snippets"
            aria-label="Snippets"
            aria-haspopup="dialog"
            onMouseDown={(e) => e.preventDefault()}
            onClick={(e) => {
              const sel = window.getSelection();
              savedRange.current =
                sel && sel.rangeCount && ref.current?.contains(sel.anchorNode)
                  ? sel.getRangeAt(0).cloneRange()
                  : null;
              setPop({ kind: 'snippet', anchor: e.currentTarget });
            }}
          >
            Snippets
          </button>
        ) : null}
        <TokenMenu
          label={compact ? 'Personalize' : 'Insert'}
          onPick={(token) => run('insertText', token)}
        />
      </div>
      {pop?.kind === 'more' ? (
        <MtPop anchor={pop.anchor} onClose={() => setPop(null)} role="menu" arrow={false}>
          <div className="mt-menu" role="menu" style={{ width: 200 }}>
            {(
              [
                ['Bulleted list', 'insertUnorderedList'],
                ['Numbered list', 'insertOrderedList'],
              ] as const
            ).map(([text, command]) => (
              <button
                key={command}
                type="button"
                className="mt-menu__item"
                role="menuitem"
                onClick={() => {
                  setPop(null);
                  run(command);
                }}
              >
                <span className="mt-menu__txt">
                  <span>{text}</span>
                </span>
              </button>
            ))}
          </div>
        </MtPop>
      ) : null}
      {pop?.kind === 'snippet' ? (
        <MtPop anchor={pop.anchor} onClose={() => setPop(null)} align="center">
          <div className="mt-insert" style={{ width: 360 }}>
            <SnippetsPanel
              onBack={() => setPop(null)}
              onPick={(snippet) => {
                setPop(null);
                const sel = window.getSelection();
                if (savedRange.current && sel) {
                  sel.removeAllRanges();
                  sel.addRange(savedRange.current);
                }
                run('insertHTML', safeRichHtml(snippet.bodyHtml));
              }}
            />
          </div>
        </MtPop>
      ) : null}
    </div>
  );
}

// --- Template picker -----------------------------------------------------------------------------

export function TemplatePickerDrawer({
  open,
  title,
  templates,
  ownerNameOf,
  onClose,
  onBack,
  currentId,
  tip,
  onPick,
  onTemplateCreated,
}: {
  open: boolean;
  title: string;
  /** HubSpot's "Choose email template" opens from another drawer: a back arrow returns to it. */
  onBack?: () => void;
  /** The template in use (a replacement): greyed in the list, not pickable. */
  currentId?: string | null;
  /** A line under the heading, e.g. the A/B test tip. */
  tip?: ReactNode;
  templates: EmailTemplate[] | null;
  ownerNameOf: (userId: string | undefined) => string | null;
  meName: string;
  onClose: () => void;
  onPick: (template: EmailTemplate) => void;
  onTemplateCreated: (template: EmailTemplate) => void;
}) {
  const [folder, setFolder] = useState('');
  const [search, setSearch] = useState('');
  const [creating, setCreating] = useState(false);

  useEffect(() => {
    if (!open) return;
    setFolder('');
    setSearch('');
  }, [open]);

  const folders = useMemo(
    () =>
      [...new Set((templates ?? []).flatMap((t) => (t.folder ? [t.folder] : [])))].sort((a, b) =>
        a.localeCompare(b),
      ),
    [templates],
  );
  const q = search.trim().toLowerCase();
  const shown = (templates ?? [])
    .filter((t) => (!folder || t.folder === folder) && (!q || t.name.toLowerCase().includes(q)))
    .sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''));

  const id = 'dynTemplatePicker';
  return (
    <>
      <CrmModal id={id} open={open && !creating} onClose={onClose} drawer plainBackdrop>
        {onBack ? (
          <div className="modal__header">
            <button
              type="button"
              className="dyn-back"
              aria-label="Back"
              title="Back"
              onClick={onBack}
            >
              <BackIcon />
            </button>
            <h2 className="modal__title" id={`${id}-title`}>
              {title}
            </h2>
            <button type="button" className="modal__close" aria-label="Close" onClick={onClose}>
              <CrmIcon name="x" className="iconSize-20" />
            </button>
          </div>
        ) : (
          <ModalHeader id={id} title={title} onClose={onClose} />
        )}
        <div className="modal__body">
          {tip ? <p className="crm-fs-8 crm-text-muted">{tip}</p> : null}
          <p className="dyn-group">Choose an existing email template or create a new one</p>
          <div className="dyn-picker__top">
            <select
              className="input"
              value={folder}
              onChange={(e) => setFolder(e.target.value)}
              aria-label="Folder"
            >
              <option value="">All templates</option>
              {folders.map((f) => (
                <option key={f} value={f}>
                  {f}
                </option>
              ))}
            </select>
            <button
              type="button"
              className="btn-crm btn-crm--outline seqm-pill"
              onClick={() => setCreating(true)}
            >
              Create new
            </button>
          </div>
          <div className="seqm-search dyn-picker__search">
            <input
              type="search"
              placeholder="Search templates"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              aria-label="Search templates"
            />
          </div>
          <ul className="dyn-picker__list">
            {templates === null ? (
              <li className="seqm-empty">Loading templates…</li>
            ) : shown.length === 0 ? (
              <li className="seqm-empty">
                {templates.length ? 'No template matches.' : 'No templates yet. Create one.'}
              </li>
            ) : (
              shown.map((t) => {
                const owner = ownerNameOf(t.ownerId);
                return (
                  <li key={t.id}>
                    <button
                      type="button"
                      className="dyn-picker__item"
                      disabled={t.id === currentId}
                      onClick={() => onPick(t)}
                    >
                      <span className="seqm-name">{t.name}</span>
                      <span className="seqm-meta">
                        {t.updatedAt ? `Updated ${timeAgo(t.updatedAt)}` : t.subject}
                        {owner ? ` by ${owner}` : ''}
                      </span>
                    </button>
                  </li>
                );
              })
            )}
          </ul>
        </div>
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </CrmModal>
      {open && creating ? (
        // Sequences #59: "Create new" opens the app's template editor (DES-6).
        <SequenceTemplateEditor
          templateId={null}
          onClose={() => setCreating(false)}
          onSaved={(t) => {
            setCreating(false);
            onTemplateCreated(t);
            onPick(t);
          }}
        />
      ) : null}
    </>
  );
}

// --- Add email / email type ----------------------------------------------------------------------

export function BackIcon() {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
      <path
        d="M19 12H5m6-6-6 6 6 6"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function PencilIcon() {
  return (
    <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
      <path
        d="M4 20h4L19 9a2.8 2.8 0 0 0-4-4L4 16z"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.7"
        strokeLinejoin="round"
      />
    </svg>
  );
}

/** Sequences QA steps BUG-10: HubSpot's "Replace template" button (two arrows). */
export function ReplaceIcon() {
  return (
    <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
      <path
        d="M4 9h13l-3-3M20 15H7l3 3"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.7"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

/** An earlier email a reply can answer: "Step N: <subject>". */
export type EmailStepOption = { id: string; label: string };
/**
 * An email's threading. A sequence stores only whether the email is a reply (it goes into the
 * thread of the last email sent); `replyToStepId` is what the dropdown shows.
 */
export type EmailThreading = { reply: boolean; replyToStepId: string | null };

/** HubSpot's "Email type *": New thread / Reply, and which earlier email a reply answers. */
export function EmailTypeFields({
  idPrefix,
  emailSteps,
  value,
  onChange,
}: {
  idPrefix: string;
  emailSteps: EmailStepOption[];
  value: EmailThreading;
  onChange: (value: EmailThreading) => void;
}) {
  // A reply needs an earlier email; the first one is always a new thread.
  const canReply = emailSteps.length > 0;
  const reply = value.reply && canReply;
  const replyTo =
    emailSteps.find((s) => s.id === value.replyToStepId)?.id ?? emailSteps.at(-1)?.id ?? null;
  return (
    <fieldset className="dyn-emailtype">
      <legend className="dyn-group">Email type *</legend>
      <label className="seq-radio">
        <input
          type="radio"
          name={`${idPrefix}-type`}
          checked={!reply}
          onChange={() => onChange({ reply: false, replyToStepId: null })}
        />
        <span className="seq-radio__dot" aria-hidden="true" />
        <span>
          <strong>New thread</strong>
          <small className="crm-text-muted dyn-emailtype__hint">
            Email will start a new thread.
          </small>
        </span>
      </label>
      <label className={cn('seq-radio', !canReply && 'is-disabled')}>
        <input
          type="radio"
          name={`${idPrefix}-type`}
          checked={reply}
          disabled={!canReply}
          onChange={() => onChange({ reply: true, replyToStepId: replyTo })}
        />
        <span className="seq-radio__dot" aria-hidden="true" />
        <span>
          <strong>Reply</strong>
          <small className="crm-text-muted dyn-emailtype__hint">
            Send this email as a reply to a previous email.
          </small>
        </span>
      </label>
      {reply ? (
        <select
          className="input dyn-emailtype__select"
          aria-label="Reply to"
          value={replyTo ?? ''}
          onChange={(e) => onChange({ reply: true, replyToStepId: e.target.value })}
        >
          {emailSteps.map((s) => (
            <option key={s.id} value={s.id}>
              {s.label}
            </option>
          ))}
        </select>
      ) : null}
    </fieldset>
  );
}

/** HubSpot's "Choose email type" drawer (Edit threading on an email step). */
export function EmailTypeDrawer({
  open,
  title = 'Choose email type',
  emailSteps,
  value,
  onSave,
  onClose,
}: {
  open: boolean;
  title?: string;
  emailSteps: EmailStepOption[];
  value: EmailThreading;
  onSave: (value: EmailThreading) => void;
  onClose: () => void;
}) {
  const [draft, setDraft] = useState<EmailThreading>(value);
  // Starts from the step's own threading each time it opens.
  useEffect(() => {
    if (open) setDraft(value);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);
  const id = 'dynEmailTypeDrawer';
  return (
    <CrmModal id={id} open={open} onClose={onClose} drawer plainBackdrop>
      <ModalHeader id={id} title={title} onClose={onClose} />
      <div className="modal__body dyn-task">
        <EmailTypeFields idPrefix={id} emailSteps={emailSteps} value={draft} onChange={setDraft} />
      </div>
      <div className="modal__footer">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          onClick={() => {
            const reply = draft.reply && emailSteps.length > 0;
            onSave({
              reply,
              replyToStepId: reply ? (draft.replyToStepId ?? emailSteps.at(-1)?.id ?? null) : null,
            });
          }}
        >
          Save
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </CrmModal>
  );
}

/**
 * HubSpot's email template box inside "Add email" / "Add manual email task": the box that opens
 * "Choose email template", or the chosen template with Edit template and Replace template.
 */
export function EmailTemplateBox({
  template,
  onChoose,
  onEdit,
}: {
  template: EmailTemplate | null;
  onChoose: () => void;
  onEdit: () => void;
}) {
  return template ? (
    <div className="dyn-task__template">
      <div>
        <strong>Template: {template.name}</strong>
        <div className="seqm-meta">
          {template.updatedAt ? `Updated ${timeAgo(template.updatedAt)}` : template.subject}
        </div>
      </div>
      <span className="dyn-email__tools">
        <button
          type="button"
          className="dyn-icon-btn"
          aria-label="Edit template"
          title="Edit template"
          onClick={onEdit}
        >
          <PencilIcon />
        </button>
        <button
          type="button"
          className="dyn-icon-btn"
          aria-label="Replace template"
          title="Replace template"
          onClick={onChoose}
        >
          <ReplaceIcon />
        </button>
      </span>
    </div>
  ) : (
    <button type="button" className="dyn-tplbox" onClick={onChoose}>
      <strong>Add email template</strong>
      <small>Choose an existing email template or create a new one</small>
    </button>
  );
}

/**
 * HubSpot's "Add email" drawer for an automated email: Email content (the template box, which
 * opens "Choose email template" with a back arrow), the email type of a follow-up (Reply by
 * default) and Add.
 */
export function AddEmailDrawer({
  open,
  templates,
  ownerNameOf,
  meName,
  emailSteps,
  onTemplateCreated,
  onTemplateUpdated,
  onClose,
  onAdd,
}: {
  open: boolean;
  templates: EmailTemplate[] | null;
  ownerNameOf: (userId: string | undefined) => string | null;
  meName: string;
  /** The emails before this one: none for the first email (always a new thread). */
  emailSteps: EmailStepOption[];
  onTemplateCreated: (template: EmailTemplate) => void;
  onTemplateUpdated?: (template: EmailTemplate) => void;
  onClose: () => void;
  onAdd: (template: EmailTemplate, threading: EmailThreading) => void;
}) {
  const [template, setTemplate] = useState<EmailTemplate | null>(null);
  const [threading, setThreading] = useState<EmailThreading>({ reply: false, replyToStepId: null });
  const [picking, setPicking] = useState(false);
  const [editing, setEditing] = useState(false);
  const followUp = emailSteps.length > 0;

  useEffect(() => {
    if (!open) return;
    setTemplate(null);
    setPicking(false);
    setEditing(false);
    // A follow-up is a reply to the email before it unless it is changed.
    setThreading({ reply: followUp, replyToStepId: emailSteps.at(-1)?.id ?? null });
    // Only when it opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  const id = 'dynAddEmailDrawer';
  const current = template ? (templates?.find((t) => t.id === template.id) ?? template) : null;
  return (
    <>
      <CrmModal id={id} open={open && !picking && !editing} onClose={onClose} drawer plainBackdrop>
        <ModalHeader id={id} title="Add email" onClose={onClose} />
        <div className="modal__body dyn-task">
          <section>
            <p className="dyn-group crm-mb-0">Email content *</p>
            <div className="crm-mt-2">
              <EmailTemplateBox
                template={current}
                onChoose={() => setPicking(true)}
                onEdit={() => setEditing(true)}
              />
            </div>
          </section>
          {followUp ? (
            <EmailTypeFields
              idPrefix={id}
              emailSteps={emailSteps}
              value={threading}
              onChange={setThreading}
            />
          ) : null}
        </div>
        <div className="modal__footer">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={!current}
            onClick={() => current && onAdd(current, threading)}
          >
            Add
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </CrmModal>
      <TemplatePickerDrawer
        open={open && picking}
        title="Choose email template"
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        currentId={template?.id}
        onBack={() => setPicking(false)}
        onClose={() => setPicking(false)}
        onTemplateCreated={onTemplateCreated}
        onPick={(t) => {
          setTemplate(t);
          setPicking(false);
        }}
      />
      {open && editing && template ? (
        <SequenceTemplateEditor
          templateId={template.id}
          onClose={() => setEditing(false)}
          onSaved={(saved, created) => {
            if (created) onTemplateCreated(saved);
            else onTemplateUpdated?.(saved);
            setTemplate(saved);
            setEditing(false);
          }}
        />
      ) : null}
    </>
  );
}

// --- Rep-led task steps --------------------------------------------------------------------------

/**
 * The five rep-led step kinds of the design, and the sequence step each one saves as. Sequences QA
 * steps BUG-01: `label` is HubSpot's name in the step chooser (sentence case, "InMail task");
 * `heading` is its name on the step card ("2. Call Task - Day 3", "LinkedIn InMail Task").
 */
export const REP_KINDS = [
  {
    key: 'manual_email',
    label: 'Manual email task',
    heading: 'Manual Email Task',
    hint: 'Get a task reminder to send an email',
    title: 'Send follow-up email',
  },
  {
    key: 'call_task',
    label: 'Call task',
    heading: 'Call Task',
    hint: 'Get a task reminder to make a call',
    title: 'Call contact to follow up',
  },
  {
    key: 'todo',
    label: 'General task',
    heading: 'General Task',
    hint: 'Set a general task reminder',
    title: 'Task for contact',
  },
  {
    key: 'linkedin_message',
    label: 'InMail task',
    heading: 'LinkedIn InMail Task',
    hint: 'Get a task reminder to send an InMail',
    title: 'Send an InMail',
  },
  {
    key: 'linkedin_connect',
    label: 'Connection request task',
    heading: 'LinkedIn Connect Task',
    hint: 'Get a task reminder to send a request',
    title: 'Send a connection request',
  },
] as const;
export type RepKind = (typeof REP_KINDS)[number]['key'];

export function repKindOf(step: SequenceStep): RepKind | null {
  if (step.type === 'manual_email' || step.type === 'call_task') return step.type;
  if (step.type === 'task') {
    return step.taskType === 'linkedin_message' || step.taskType === 'linkedin_connect'
      ? step.taskType
      : 'todo';
  }
  return null;
}

export function TaskStepDrawer({
  open,
  kind,
  initial,
  templates,
  ownerNameOf,
  meName,
  onTemplateCreated,
  onTemplateUpdated,
  emailSteps,
  onClose,
  onSave,
  standard = false,
}: {
  open: boolean;
  /**
   * A manual email's earlier emails ("Step N: <subject>"): with some, the email has an email
   * type (a follow-up replies by default). Omitted: threading is left as the step has it.
   */
  emailSteps?: EmailStepOption[];
  onTemplateUpdated?: (template: EmailTemplate) => void;
  /** A standard sequence: no lane. Task steps may pause it too (QA 14 Oct #35, #52). */
  standard?: boolean;
  kind: RepKind;
  initial: SequenceStep | null;
  templates: EmailTemplate[] | null;
  ownerNameOf: (userId: string | undefined) => string | null;
  meName: string;
  onTemplateCreated: (template: EmailTemplate) => void;
  onClose: () => void;
  onSave: (step: SequenceStep) => void;
}) {
  const meta = REP_KINDS.find((k) => k.key === kind)!;
  const [pause, setPause] = useState(true);
  // #60: the queue the step's tasks go in.
  const [queueId, setQueueId] = useState<string | null>(null);
  const [queues, setQueues] = useState<TaskQueue[]>([]);
  const me = useCurrentUser();
  const [creatingQueue, setCreatingQueue] = useState(false);
  const { owners } = useOwners(creatingQueue, false);
  const queueUsers: QueueUser[] = useMemo(
    () =>
      owners
        .filter((o) => o.active && o.userId)
        .map((o) => ({ id: o.userId, name: o.name, email: o.email })),
    [owners],
  );
  const [title, setTitle] = useState('');
  const [priority, setPriority] = useState<TaskStepPriority>(null);
  const [notes, setNotes] = useState('');
  const [templateId, setTemplateId] = useState<string | null>(null);
  const [picking, setPicking] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState(false);
  const [threading, setThreading] = useState<EmailThreading>({ reply: false, replyToStepId: null });
  // A new manual email is two steps, as HubSpot's: the email, then the task's details.
  const [stage, setStage] = useState<'email' | 'task'>('task');
  const titleRef = useRef<HTMLInputElement>(null);
  const followUp = (emailSteps?.length ?? 0) > 0;

  // The step's notes, made safe, worked out while rendering: the notes editor reads its start
  // value when it mounts, which is before an effect could set it.
  const initialNotes = useMemo(() => {
    const s = initial as Record<string, unknown> | null;
    return typeof s?.notes === 'string' ? safeRichHtml(s.notes) : '';
  }, [initial]);

  useEffect(() => {
    if (!open) return;
    const s = initial as Record<string, unknown> | null;
    setPause(s ? Boolean(s.pauseUntilDone) : true);
    setQueueId(typeof s?.queueId === 'string' ? s.queueId : null);
    setTitle(typeof s?.title === 'string' ? s.title : meta.title);
    // New steps start with no priority, as in HubSpot (QA 16 Oct #111).
    const saved = s?.priority as TaskStepPriority | undefined;
    setPriority(s ? (saved === undefined ? 'medium' : saved) : null);
    setNotes(initialNotes);
    setTemplateId(typeof s?.templateId === 'string' ? s.templateId : null);
    setPicking(false);
    setEditingTemplate(false);
    const replied = s ? s.threadAsReply === true : followUp;
    setThreading({ reply: replied, replyToStepId: emailSteps?.at(-1)?.id ?? null });
    setStage(kind === 'manual_email' && !initial ? 'email' : 'task');
    // `emailSteps` is a new list on every render; what matters is whether there are any.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, initial, initialNotes, meta.title, kind, followUp]);

  const loadQueues = useCallback(() => {
    listTaskQueues().then(setQueues, () => setQueues([]));
  }, []);
  useEffect(() => {
    if (open) loadQueues();
  }, [open, loadQueues]);

  const template = templates?.find((t) => t.id === templateId) ?? null;
  const isEmail = kind === 'manual_email';
  // Sequences HubSpot parity: a manual email's template is optional; without one the task opens
  // an empty email for the rep to write when they review it. HubSpot also adds a call or manual
  // email task with no title (the API keeps the title of the other tasks required).
  const ready = kind === 'call_task' || isEmail || title.trim().length > 0;

  const save = () => {
    if (!ready) return;
    const common = {
      ...(standard ? {} : { lane: 'rep' as const }),
      pauseUntilDone: pause,
      queueId,
      priority,
      notes: notes.replace(/<[^>]*>|&nbsp;/g, '').trim() ? notes : null,
    };
    // Edits keep what this drawer doesn't show (e.g. a manual email's own subject and body).
    let step: SequenceStep;
    if (kind === 'manual_email') {
      const before = initial?.type === 'manual_email' ? initial : null;
      step = {
        subject: null,
        bodyHtml: null,
        threadAsReply: false,
        ...before,
        // A newly picked template replaces the email's own subject and body (they would win).
        ...(templateId !== null && templateId !== before?.templateId
          ? { subject: null, bodyHtml: null }
          : {}),
        type: 'manual_email',
        title: title.trim() || null,
        templateId,
        ...(followUp ? { threadAsReply: threading.reply } : {}),
        ...common,
      };
    } else if (kind === 'call_task') {
      const before = initial?.type === 'call_task' ? initial : null;
      step = { ...before, type: 'call_task', title: title.trim() || null, ...common };
    } else {
      // A general task keeps its own task type (e.g. a custom one) when edited.
      const before = initial?.type === 'task' ? initial : null;
      const taskType = kind === 'todo' && before ? before.taskType : kind;
      step = { ...before, type: 'task', taskType, title: title.trim(), ...common };
    }
    onSave(step);
  };

  const id = 'dynTaskDrawer';
  // "Add call task", but a name like "InMail" keeps its capitals (QA 16 Oct #128). Sequences
  // #98: only a plain first word is lowered ("InMail task" was read as "Inmail" → "inMail").
  const label = /^[A-Z][a-z]+(\s|$)/.test(meta.label)
    ? `${meta.label.charAt(0).toLowerCase()}${meta.label.slice(1)}`
    : meta.label;
  // Sequences QA steps BUG-01: HubSpot titles the edit drawer of every task step "Edit task".
  const heading = initial ? 'Edit task' : `Add ${label}`;
  const emailStage = isEmail && !initial && stage === 'email';
  const modalOpen = open && !picking && !editingTemplate && !creatingQueue;
  return (
    <>
      <CrmModal id={id} open={modalOpen} onClose={onClose} drawer plainBackdrop>
        {emailStage ? (
          <ModalHeader id={id} title="Add email" onClose={onClose} />
        ) : isEmail && !initial ? (
          <div className="modal__header">
            <button
              type="button"
              className="dyn-back"
              aria-label="Back"
              title="Back"
              onClick={() => setStage('email')}
            >
              <BackIcon />
            </button>
            <h2 className="modal__title" id={`${id}-title`}>
              {heading}
            </h2>
            <button type="button" className="modal__close" aria-label="Close" onClick={onClose}>
              <CrmIcon name="x" className="iconSize-20" />
            </button>
          </div>
        ) : (
          <ModalHeader id={id} title={heading} onClose={onClose} />
        )}
        <div className="modal__body dyn-task">
          {emailStage ? (
            <>
              <section>
                <p className="dyn-group crm-mb-0">Email content</p>
                <p className="crm-fs-8 crm-text-muted crm-mb-2">
                  Optional. Add it now, or write it when you review the task.
                </p>
                <EmailTemplateBox
                  template={template}
                  onChoose={() => setPicking(true)}
                  onEdit={() => setEditingTemplate(true)}
                />
              </section>
              {followUp ? (
                <EmailTypeFields
                  idPrefix={id}
                  emailSteps={emailSteps ?? []}
                  value={threading}
                  onChange={setThreading}
                />
              ) : null}
            </>
          ) : null}
          {isEmail && initial ? (
            <section>
              <p className="dyn-group crm-mb-0">Email template</p>
              <p className="crm-fs-8 crm-text-muted crm-mb-2">
                Attach an email template to this manual email task
              </p>
              <div className="dyn-task__template">
                {template ? (
                  <>
                    <div>
                      <strong>{template.name}</strong>
                      {/* Sequences QA steps BUG-04: tokens as chips, not raw {{...}}. */}
                      <div className="seqm-meta">
                        <TokenText text={template.subject} />
                      </div>
                    </div>
                    <button type="button" className="seqz-back" onClick={() => setPicking(true)}>
                      Change
                    </button>
                    <button type="button" className="seqz-back" onClick={() => setTemplateId(null)}>
                      Remove
                    </button>
                  </>
                ) : (
                  <button type="button" className="dyn-link-btn" onClick={() => setPicking(true)}>
                    Add email template
                  </button>
                )}
              </div>
              {/* Sequences HubSpot parity: HubSpot's words, under the template box. */}
              <p className="crm-fs-8 crm-text-muted crm-mt-2 crm-mb-0">
                Optional. Add it now, or write it when you review the task.
              </p>
            </section>
          ) : null}
          {isEmail && initial && followUp ? (
            <EmailTypeFields
              idPrefix={id}
              emailSteps={emailSteps ?? []}
              value={threading}
              onChange={setThreading}
            />
          ) : null}

          {emailStage ? null : (
            <>
              <section>
                <p className="dyn-group">Task details</p>
                <label className="check-row dyn-task__check">
                  <span className="check">
                    <input
                      type="checkbox"
                      checked={pause}
                      onChange={(e) => setPause(e.target.checked)}
                    />
                    <span className="check__box" aria-hidden />
                  </span>
                  Pause sequence until task is completed
                  <span
                    className="seqa-info"
                    role="img"
                    aria-label="About pausing the sequence"
                    title="If this box is checked, the sequence will be paused until this task is marked as complete."
                  >
                    ⓘ
                  </span>
                </label>
              </section>

              <div className="field">
                <div className="dyn-task__label">
                  <label className="field__label" htmlFor="dynTaskTitle">
                    Task Title *
                  </label>
                  <TokenMenu
                    label="Personalize"
                    onPick={(token) => insertAtCaret(titleRef.current, title, token, setTitle)}
                  />
                </div>
                <input
                  id="dynTaskTitle"
                  ref={titleRef}
                  className="input"
                  value={title}
                  maxLength={255}
                  onChange={(e) => setTitle(e.target.value)}
                />
              </div>

              <div className="dyn-task__row">
                <div className="field">
                  <label className="field__label" htmlFor="dynTaskPriority">
                    Priority *
                  </label>
                  <select
                    id="dynTaskPriority"
                    className={cn('input', 'dyn-prio', `dyn-prio--${priority ?? 'none'}`)}
                    value={priority ?? ''}
                    onChange={(e) => setPriority((e.target.value || null) as TaskStepPriority)}
                  >
                    <option value="">None</option>
                    <option value="low">Low</option>
                    <option value="medium">Medium</option>
                    <option value="high">High</option>
                  </select>
                </div>
                {/* Sequences #60 / #83: next to Priority, "None" first, as in the design and
                HubSpot (Queue: None, the queues you can use, "Create a new queue"). */}
                <div className="field">
                  <label className="field__label" htmlFor="dynTaskQueue">
                    Queue
                  </label>
                  <CustomSelect
                    id="dynTaskQueue"
                    placeholder="None"
                    showPlaceholderOption
                    menuActions={false}
                    searchPlaceholder="Search"
                    emptyText="No queues found"
                    value={queueId ?? ''}
                    options={[
                      ...queues.map((q) => ({ value: q.id, label: q.name })),
                      ...(queueId && !queues.some((q) => q.id === queueId)
                        ? [{ value: queueId, label: 'Unavailable queue' }]
                        : []),
                    ]}
                    onChange={(v) => setQueueId(v || null)}
                    // Same rule as the Tasks queues page: read-only users cannot make queues.
                    footerAction={
                      me.role === 'read_only'
                        ? undefined
                        : { label: 'Create a new queue', onSelect: () => setCreatingQueue(true) }
                    }
                  />
                </div>
              </div>

              <div className="field">
                <span className="field__label">Notes</span>
                <div className="dyn-task__notes">
                  <RichBody
                    key={open ? `${initial ? 'edit' : 'add'}:${initialNotes}` : 'closed'}
                    initialHtml={initialNotes}
                    onChange={setNotes}
                    label="Notes"
                    compact
                  />
                </div>
              </div>
            </>
          )}
        </div>
        <div className="modal__footer">
          {emailStage ? (
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => setStage('task')}
            >
              Next
            </button>
          ) : (
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={save}
              disabled={!ready}
            >
              {initial ? 'Save' : 'Add'}
            </button>
          )}
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </CrmModal>
      <TemplatePickerDrawer
        open={open && picking}
        title="Choose email template"
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        currentId={templateId}
        onBack={() => setPicking(false)}
        onClose={() => setPicking(false)}
        onTemplateCreated={onTemplateCreated}
        onPick={(t) => {
          setTemplateId(t.id);
          setPicking(false);
        }}
      />
      {open && creatingQueue ? (
        <TaskQueueDialog
          queue={null}
          queues={queues}
          users={queueUsers}
          onClose={() => setCreatingQueue(false)}
          onSaved={(saved) => {
            setQueues((cur) => [...cur.filter((q) => q.id !== saved.id), saved]);
            setQueueId(saved.id);
            setCreatingQueue(false);
          }}
        />
      ) : null}
      {open && editingTemplate && templateId ? (
        <SequenceTemplateEditor
          templateId={templateId}
          onClose={() => setEditingTemplate(false)}
          onSaved={(saved, created) => {
            if (created) onTemplateCreated(saved);
            else onTemplateUpdated?.(saved);
            setTemplateId(saved.id);
            setEditingTemplate(false);
          }}
        />
      ) : null}
    </>
  );
}

/**
 * Edit an email step (QA 14 Oct #43, HubSpot's pencil) in the app's template editor (Sequences
 * #59, DES-6): a template step edits its template (Save as new template points the step at the
 * copy; Update existing template changes it everywhere); a step with its own subject and body
 * saves them as a new template for the step.
 */
export function StepEmailEditor({
  steps,
  index,
  templates,
  onClose,
  onTemplateCreated,
  onTemplateUpdated,
  onStepsChange,
}: {
  steps: SequenceStep[];
  /** The step being edited; null: closed. */
  index: number | null;
  templates: EmailTemplate[] | null;
  meName?: string;
  onClose: () => void;
  onTemplateCreated: (template: EmailTemplate) => void;
  onTemplateUpdated?: (template: EmailTemplate) => void;
  onStepsChange: (steps: SequenceStep[]) => void;
}) {
  const step = index === null ? null : steps[index];
  const email = step && 'templateId' in step ? step : null;
  const template = email?.templateId
    ? (templates?.find((t) => t.id === email.templateId) ?? null)
    : null;
  // A template step opens only with its template loaded: never an empty form over it.
  if (!email || (email.templateId && !template)) return null;
  return (
    <SequenceTemplateEditor
      key={index}
      templateId={template?.id ?? null}
      draft={
        template
          ? null
          : { name: 'Sequence email', subject: email.subject ?? '', bodyHtml: email.bodyHtml ?? '' }
      }
      onClose={onClose}
      onSaved={(saved, created) => {
        if (!created) {
          onTemplateUpdated?.(saved);
          onClose();
          return;
        }
        onTemplateCreated(saved);
        onStepsChange(
          steps.map((s, i) =>
            i === index && 'templateId' in s
              ? { ...s, templateId: saved.id, subject: null, bodyHtml: null }
              : s,
          ),
        );
        onClose();
      }}
    />
  );
}
