'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import {
  DEFAULT_BROWSER_NOTIFY_TYPES,
  getExtensionSettings,
  updateExtensionSettings,
  type BrowserNotifyTypes,
  type ExtensionSettingsResponse,
} from '@/features/extension/api.client';
import { syncExtensionNotifications } from '@/features/extension/bridge';
import { SALES_EXTENSION_INSTALL_URL } from '@/features/extension/constants';
import type { MyMailbox } from '@/features/inbox/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { needsReconnect } from '@/lib/utils/connection';
import { updateProfile } from '../api.client';
import type { Profile } from '../types';
import { useApplyProfile } from '../UserPrefs';
import { DialogHead, DrawerForm, SetDialog, SettingsForm, SuField } from './settings-ui';

/**
 * Settings › General › Email (design: settings-profile.php #tab-email).
 * Order: Email → Configure → Never Log → Download extension → Extension settings → Sales Notifications.
 */

const OUTLOOK_ADDIN_URL = 'https://appsource.microsoft.com';
const OUTLOOK_TIP_STORAGE_KEY = 'crm.settings.email.outlookTipDismissed';
const EMAIL_SIGNATURE_MODE_KEY = 'crm.settings.email.defaultSignatureMode';
const EMAIL_INBOX_DISABLED_KEY = 'crm.settings.email.inboxDisabled';

const INBOX_AUTOMATION_TIP =
  'Automatically capture contact details to update your records, and get follow-up task suggestions. You’ll be opted in to new features in the future.';
const DEFAULT_SIGNATURE_TIP =
  'Set the default signature for this account, which is used when composing new messages in CRM. You can choose a specific signature, or use the global default set in Manage email signatures.';

type EmailSignatureMode = 'global' | 'personal' | 'none';

const EMAIL_SIGNATURE_MODE_HELP: Record<EmailSignatureMode, string> = {
  global:
    'This account will always use the signature set as the global default in “Manage email signatures”.',
  personal:
    'This account will use your personal signature from Manage email signatures when composing in CRM.',
  none: 'This account will not include a signature by default. You can still add one when composing.',
};

const EMAIL_SIGNATURE_MODE_LABEL: Record<EmailSignatureMode, string> = {
  global: 'Use global default',
  personal: 'Personal signature',
  none: 'No signature',
};

function readSignatureMode(email: string | null | undefined): EmailSignatureMode {
  if (!email) return 'global';
  try {
    const raw = localStorage.getItem(`${EMAIL_SIGNATURE_MODE_KEY}:${email.toLowerCase()}`);
    if (raw === 'personal' || raw === 'none' || raw === 'global') return raw;
  } catch {
    /* ignore */
  }
  return 'global';
}

function writeSignatureMode(email: string | null | undefined, mode: EmailSignatureMode) {
  if (!email) return;
  try {
    localStorage.setItem(`${EMAIL_SIGNATURE_MODE_KEY}:${email.toLowerCase()}`, mode);
  } catch {
    /* ignore */
  }
}

function readInboxDisabled(email: string | null | undefined): boolean {
  if (!email) return false;
  try {
    return localStorage.getItem(`${EMAIL_INBOX_DISABLED_KEY}:${email.toLowerCase()}`) === '1';
  } catch {
    return false;
  }
}

function writeInboxDisabled(email: string | null | undefined, disabled: boolean) {
  if (!email) return;
  try {
    const key = `${EMAIL_INBOX_DISABLED_KEY}:${email.toLowerCase()}`;
    if (disabled) localStorage.setItem(key, '1');
    else localStorage.removeItem(key);
  } catch {
    /* ignore */
  }
}

const UNSUB_CHOICES = [
  'Is this email not relevant to you? Click here',
  'To stop receiving these emails, click here',
  'Prefer fewer emails from me? Click here',
] as const;

type NeverLogRow = {
  value: string;
  kind: 'email' | 'domain';
  source: 'user' | 'admin';
};

type NeverScopeFilter = 'all' | 'blocked-all' | 'blocked-me';
type NeverKindFilter = 'both' | 'domains' | 'emails';

const NEVER_SCOPE_OPTIONS = [
  { value: 'all', label: 'All' },
  { value: 'blocked-all', label: 'Blocked for all users' },
  { value: 'blocked-me', label: 'Blocked only for me' },
] as const;

const NEVER_KIND_OPTIONS = [
  { value: 'both', label: 'Domains and Emails' },
  { value: 'domains', label: 'Domains' },
  { value: 'emails', label: 'Emails' },
] as const;

function isEmailAddress(value: string) {
  return value.includes('@');
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;
const DOMAIN_RE = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i;
const IPV4_RE = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;

/** IPv4 only, the form the Blocked IP list stores (QA #521). */
function isIpAddress(value: string) {
  return IPV4_RE.test(value);
}

/** Never Log entries that are neither a valid email nor a valid domain (QA #521). */
function invalidNeverLogEntries(raw: string): string[] {
  const bad: string[] = [];
  for (const part of raw.split(/[\n,]+/)) {
    const v = normalizeEntry(part).replace(/^\*@/, '');
    if (!v) continue;
    const ok = v.includes('@') ? EMAIL_RE.test(v) : DOMAIN_RE.test(v);
    if (!ok) bad.push(part.trim());
  }
  return bad;
}

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

function escapeAttr(value: string) {
  return escapeHtml(value);
}

function SigToolIcon({ d }: { d: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      width="16"
      height="16"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d={d} />
    </svg>
  );
}

function normalizeEntry(raw: string) {
  return raw.trim().toLowerCase();
}

function splitNeverLogItems(raw: string): { emails: string[]; domains: string[] } {
  const emails: string[] = [];
  const domains: string[] = [];
  for (const part of raw.split(/[\n,]+/)) {
    const v = normalizeEntry(part).replace(/^\*@/, '');
    if (!v) continue;
    if (isEmailAddress(v)) emails.push(v);
    else domains.push(v);
  }
  return { emails, domains };
}

/** Merge effective Never Log with user vs admin source labels. */
function buildNeverLogRows(ext: ExtensionSettingsResponse): NeverLogRow[] {
  const userEmails = new Set(ext.user.neverLogEmails.map((e) => e.toLowerCase()));
  const userDomains = new Set(ext.user.neverLogDomains.map((d) => d.toLowerCase()));
  const seen = new Set<string>();
  const rows: NeverLogRow[] = [];

  for (const email of ext.effective.neverLogEmails) {
    const value = email.toLowerCase();
    if (seen.has(`e:${value}`)) continue;
    seen.add(`e:${value}`);
    rows.push({
      value,
      kind: 'email',
      source: userEmails.has(value) ? 'user' : 'admin',
    });
  }
  for (const domain of ext.effective.neverLogDomains) {
    const value = domain.toLowerCase();
    if (seen.has(`d:${value}`)) continue;
    seen.add(`d:${value}`);
    rows.push({
      value: `*@${value}`,
      kind: 'domain',
      source: userDomains.has(value) ? 'user' : 'admin',
    });
  }
  return rows;
}

export function GeneralEmailTab({
  mailbox,
  profile,
  onProfileUpdated,
  onConnect,
  onUpgradeConsent,
  onDisconnect,
}: {
  mailbox: MyMailbox | null;
  profile: Profile | null;
  onProfileUpdated: (p: Profile) => void;
  onConnect: () => void;
  /** Switch Limited → All Features without re-OAuth. */
  onUpgradeConsent?: () => void;
  onDisconnect: () => void;
}) {
  const toast = useToast();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const applyProfile = useApplyProfile();

  const [aliases, setAliases] = useState<string[]>([]);
  const [includeUnsub, setIncludeUnsub] = useState(true);
  const [unsubText, setUnsubText] = useState<string>(UNSUB_CHOICES[0]);
  const [bccList, setBccList] = useState<string[]>([]);
  const [blockedIps, setBlockedIps] = useState<string[]>([]);

  const [neverRows, setNeverRows] = useState<NeverLogRow[]>([]);
  const [userNeverEmails, setUserNeverEmails] = useState<string[]>([]);
  const [userNeverDomains, setUserNeverDomains] = useState<string[]>([]);
  const [neverSearch, setNeverSearch] = useState('');
  const [neverScope, setNeverScope] = useState<NeverScopeFilter>('all');
  const [neverKind, setNeverKind] = useState<NeverKindFilter>('both');
  const [neverBusy, setNeverBusy] = useState(false);

  const [notifyEnabled, setNotifyEnabled] = useState(false);
  const [notifyTypes, setNotifyTypes] = useState<BrowserNotifyTypes>(DEFAULT_BROWSER_NOTIFY_TYPES);
  const [browserPerm, setBrowserPerm] = useState<NotificationPermission | 'unsupported'>('default');
  const [inboxAutomation, setInboxAutomation] = useState(true);
  const [inboxAutomationLocked, setInboxAutomationLocked] = useState(false);
  const [inboxAutomationBusy, setInboxAutomationBusy] = useState(false);
  const [accountActionsOpen, setAccountActionsOpen] = useState(false);
  const [accountActionsPos, setAccountActionsPos] = useState<{ top: number; left: number } | null>(
    null,
  );
  const [accountTip, setAccountTip] = useState<string | null>(null);
  const accountActionsRef = useRef<HTMLDivElement>(null);
  const accountActionsMenuRef = useRef<HTMLDivElement>(null);
  const accountTipRef = useRef<HTMLDivElement>(null);

  const [aliasOpen, setAliasOpen] = useState(false);
  const [sigOpen, setSigOpen] = useState(false);
  const [unsubOpen, setUnsubOpen] = useState(false);
  const [neverOpen, setNeverOpen] = useState(false);
  const [bccOpen, setBccOpen] = useState(false);
  const [ipsOpen, setIpsOpen] = useState(false);
  const [outlookTipDismissed, setOutlookTipDismissed] = useState(false);
  const [outlookAddinOpen, setOutlookAddinOpen] = useState(false);
  const [outlookAddinChecking, setOutlookAddinChecking] = useState(false);
  const [emailInstallClient, setEmailInstallClient] = useState<'gmail' | 'outlook' | null>(null);
  const [emailClientChooserOpen, setEmailClientChooserOpen] = useState(false);
  const [signatureDefaultOpen, setSignatureDefaultOpen] = useState(false);
  const [signatureDefaultMode, setSignatureDefaultMode] = useState<EmailSignatureMode>('global');
  const [signatureDefaultBusy, setSignatureDefaultBusy] = useState(false);
  const [signatureModeLabel, setSignatureModeLabel] = useState<EmailSignatureMode>('global');
  const [inboxDisabled, setInboxDisabled] = useState(false);
  const [disableInboxOpen, setDisableInboxOpen] = useState(false);
  const [removeInboxOpen, setRemoveInboxOpen] = useState(false);

  useEffect(() => {
    try {
      if (localStorage.getItem(OUTLOOK_TIP_STORAGE_KEY) === '1') setOutlookTipDismissed(true);
    } catch {
      /* ignore private-mode / blocked storage */
    }
  }, []);

  const dismissOutlookTip = () => {
    setOutlookTipDismissed(true);
    try {
      localStorage.setItem(OUTLOOK_TIP_STORAGE_KEY, '1');
    } catch {
      /* ignore private-mode / blocked storage */
    }
  };

  const startOutlookAddinInstall = () => {
    setOutlookAddinOpen(true);
  };

  const checkOutlookAddinInstalled = () => {
    setOutlookAddinChecking(true);
    window.setTimeout(() => {
      setOutlookAddinChecking(false);
      setOutlookAddinOpen(false);
      toast('The CRM Sales add-in for Outlook was installed.', 'success');
    }, 400);
  };

  const openEmailInstallDialog = (client: 'gmail' | 'outlook' = 'gmail') => {
    setEmailClientChooserOpen(false);
    setEmailInstallClient(client);
  };

  const closeEmailInstallDialog = () => setEmailInstallClient(null);

  const openEmailClientChooser = () => {
    setEmailInstallClient(null);
    setEmailClientChooserOpen(true);
  };

  const downloadEmailInstall = () => {
    if (emailInstallClient === 'outlook') {
      window.open(OUTLOOK_ADDIN_URL, '_blank', 'noopener,noreferrer');
      setEmailInstallClient(null);
      setOutlookAddinOpen(true);
      return;
    }
    if (!SALES_EXTENSION_INSTALL_URL) {
      toast('The Sales extension install link is not available yet.', 'info');
      return;
    }
    window.open(SALES_EXTENSION_INSTALL_URL, '_blank', 'noopener,noreferrer');
    setEmailInstallClient(null);
  };

  const chooseEmailClient = (client: 'gmail' | 'outlook' | 'other') => {
    if (client === 'other') {
      setEmailClientChooserOpen(false);
      toast(
        'For other email clients, connect your inbox from Email settings to send and log messages in CRM.',
        'info',
      );
      return;
    }
    openEmailInstallDialog(client);
  };

  useEffect(() => {
    setSignatureModeLabel(readSignatureMode(mailbox?.emailAddress));
    setInboxDisabled(readInboxDisabled(mailbox?.emailAddress));
  }, [mailbox?.emailAddress]);

  const confirmDisableInbox = () => {
    writeInboxDisabled(mailbox?.emailAddress, true);
    setInboxDisabled(true);
    setDisableInboxOpen(false);
    toast('Connected inbox disabled', 'success');
  };

  const enableInbox = () => {
    writeInboxDisabled(mailbox?.emailAddress, false);
    setInboxDisabled(false);
    toast('Connected inbox enabled', 'success');
  };

  const openSignatureDefaultDialog = () => {
    setSignatureDefaultMode(readSignatureMode(mailbox?.emailAddress));
    setSignatureDefaultOpen(true);
  };

  const saveSignatureDefault = async () => {
    if (!profile) return;
    setSignatureDefaultBusy(true);
    try {
      if (signatureDefaultMode === 'none' && profile.emailSignature?.trim()) {
        const p = await updateProfile({
          emailSignature: null,
          updatedAt: profile.updatedAt,
        });
        onProfileUpdated(p);
        applyProfile(p);
      }
      // Design: Personal signature only updates the default preference — do not open
      // the Manage email signatures drawer from this dialog.
      // else if (signatureDefaultMode === 'personal' && !profile.emailSignature?.trim()) {
      //   writeSignatureMode(mailbox?.emailAddress, signatureDefaultMode);
      //   setSignatureModeLabel(signatureDefaultMode);
      //   setSignatureDefaultOpen(false);
      //   toast('Create a personal signature in Manage email signatures.', 'info');
      //   setSigOpen(true);
      //   return;
      // }
      writeSignatureMode(mailbox?.emailAddress, signatureDefaultMode);
      setSignatureModeLabel(signatureDefaultMode);
      setSignatureDefaultOpen(false);
      toast('Default email signature updated', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSignatureDefaultBusy(false);
    }
  };

  useEffect(() => {
    if (!accountActionsOpen) return;
    const onDoc = (e: MouseEvent) => {
      const target = e.target as Node;
      if (accountActionsRef.current?.contains(target)) return;
      if (accountActionsMenuRef.current?.contains(target)) return;
      setAccountActionsOpen(false);
      setAccountActionsPos(null);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setAccountActionsOpen(false);
        setAccountActionsPos(null);
      }
    };
    const onReposition = () => {
      const trigger = accountActionsRef.current?.querySelector('.email-actions-trigger');
      if (!(trigger instanceof HTMLElement)) return;
      const rect = trigger.getBoundingClientRect();
      const menuWidth = 200;
      const left = Math.min(Math.max(8, rect.right - menuWidth), window.innerWidth - menuWidth - 8);
      setAccountActionsPos({ top: rect.bottom + 6, left });
    };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    window.addEventListener('resize', onReposition);
    window.addEventListener('scroll', onReposition, true);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', onReposition);
      window.removeEventListener('scroll', onReposition, true);
    };
  }, [accountActionsOpen]);

  useEffect(() => {
    if (!accountTip) return;
    const onDoc = (e: MouseEvent) => {
      const target = e.target as Node;
      if (accountTipRef.current?.contains(target)) return;
      if (target instanceof Element && target.closest('.email-account-table__head .set-info')) {
        return;
      }
      setAccountTip(null);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setAccountTip(null);
    };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, [accountTip]);

  const toggleAccountTip = (text: string) => {
    setAccountTip((prev) => (prev === text ? null : text));
  };

  const toggleAccountActions = () => {
    if (accountActionsOpen) {
      setAccountActionsOpen(false);
      setAccountActionsPos(null);
      return;
    }
    const trigger = accountActionsRef.current?.querySelector('.email-actions-trigger');
    if (trigger instanceof HTMLElement) {
      const rect = trigger.getBoundingClientRect();
      const menuWidth = 200;
      const left = Math.min(Math.max(8, rect.right - menuWidth), window.innerWidth - menuWidth - 8);
      setAccountActionsPos({ top: rect.bottom + 6, left });
    } else {
      setAccountActionsPos(null);
    }
    setAccountActionsOpen(true);
  };

  const [sigMode, setSigMode] = useState<'simple' | 'html'>('simple');
  const [sigHtml, setSigHtml] = useState('');
  const [sigName, setSigName] = useState('Unnamed signature');
  const [sigPop, setSigPop] = useState<null | 'link' | 'image'>(null);
  const [sigPopPos, setSigPopPos] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
  const [linkText, setLinkText] = useState('');
  const [linkUrl, setLinkUrl] = useState('');
  const [linkBlank, setLinkBlank] = useState(true);
  const [imageUrl, setImageUrl] = useState('');
  const sigEditorRef = useRef<HTMLDivElement>(null);
  const sigHtmlRef = useRef<HTMLTextAreaElement>(null);
  const sigRangeRef = useRef<Range | null>(null);
  const linkToolRef = useRef<HTMLButtonElement>(null);
  const imageToolRef = useRef<HTMLButtonElement>(null);
  const imageFileRef = useRef<HTMLInputElement>(null);

  const [bccDraft, setBccDraft] = useState('');
  const [ipDraft, setIpDraft] = useState('');
  const [bccWorking, setBccWorking] = useState<string[]>([]);
  const [ipsWorking, setIpsWorking] = useState<string[]>([]);

  useEffect(() => {
    if (!profile) return;
    setAliases(profile.preferences.emailAliases ?? []);
    setIncludeUnsub(profile.preferences.includeUnsubscribeLink !== false);
    const text = profile.preferences.unsubscribeText;
    setUnsubText(
      text && (UNSUB_CHOICES as readonly string[]).includes(text) ? text : UNSUB_CHOICES[0],
    );
  }, [profile]);

  useEffect(() => {
    if (typeof Notification === 'undefined') setBrowserPerm('unsupported');
    else setBrowserPerm(Notification.permission);

    getExtensionSettings().then(
      (ext) => {
        setUserNeverEmails(ext.user.neverLogEmails.map((e) => e.toLowerCase()));
        setUserNeverDomains(ext.user.neverLogDomains.map((d) => d.toLowerCase()));
        setNeverRows(buildNeverLogRows(ext));
        setNotifyEnabled(ext.user.notificationsEnabled);
        setNotifyTypes({
          ...DEFAULT_BROWSER_NOTIFY_TYPES,
          ...ext.user.browserNotifyTypes,
        });
        setBccList(ext.user.bccAddresses ?? []);
        setBlockedIps(ext.user.excludedIps ?? []);
        setInboxAutomation(ext.effective.autoLog);
        setInboxAutomationLocked(ext.effective.logLocked || ext.effective.logTrackLocked);
      },
      () => {},
    );
  }, []);

  const toggleInboxAutomation = async (next: boolean) => {
    if (inboxAutomationLocked || inboxAutomationBusy) return;
    const prev = inboxAutomation;
    setInboxAutomation(next);
    setInboxAutomationBusy(true);
    try {
      const ext = await updateExtensionSettings({ autoLog: next });
      setInboxAutomation(ext.effective.autoLog);
      setInboxAutomationLocked(ext.effective.logLocked || ext.effective.logTrackLocked);
      toast('Your inbox automation preference was updated', 'success');
    } catch (err) {
      setInboxAutomation(prev);
      toast(errorText(err), 'danger');
    } finally {
      setInboxAutomationBusy(false);
    }
  };

  useEffect(() => {
    if (!sigOpen || !profile) return;
    const html =
      profile.emailSignature?.trim() ||
      `<p>Best regards,<br>${profile.name || 'Your name'}<br>Your Company</p>`;
    setSigHtml(html);
    setSigName('Unnamed signature');
    setSigMode('simple');
    setSigPop(null);
    requestAnimationFrame(() => {
      if (sigEditorRef.current) sigEditorRef.current.innerHTML = html;
      if (sigHtmlRef.current) sigHtmlRef.current.value = html;
    });
  }, [sigOpen, profile]);

  const saveSigRange = useCallback(() => {
    const editor = sigEditorRef.current;
    const sel = window.getSelection();
    if (!editor || !sel || sel.rangeCount === 0) return;
    const range = sel.getRangeAt(0);
    if (editor.contains(range.commonAncestorContainer)) {
      sigRangeRef.current = range.cloneRange();
    }
  }, []);

  const restoreSigRange = useCallback(() => {
    const editor = sigEditorRef.current;
    if (!editor) return;
    editor.focus();
    let range = sigRangeRef.current;
    if (!range || !editor.contains(range.commonAncestorContainer)) {
      range = document.createRange();
      range.selectNodeContents(editor);
      range.collapse(false);
      sigRangeRef.current = range;
    }
    const sel = window.getSelection();
    if (!sel) return;
    sel.removeAllRanges();
    sel.addRange(range);
  }, []);

  const insertSigHtml = useCallback(
    (html: string) => {
      restoreSigRange();
      document.execCommand('insertHTML', false, html);
      saveSigRange();
      if (sigEditorRef.current && sigHtmlRef.current) {
        sigHtmlRef.current.value = sigEditorRef.current.innerHTML;
        setSigHtml(sigEditorRef.current.innerHTML);
      }
    },
    [restoreSigRange, saveSigRange],
  );

  const filteredNeverRows = useMemo(() => {
    const q = neverSearch.trim().toLowerCase();
    return neverRows.filter((row) => {
      if (neverScope === 'blocked-all' && row.source !== 'admin') return false;
      if (neverScope === 'blocked-me' && row.source !== 'user') return false;
      if (neverKind === 'domains' && row.kind !== 'domain') return false;
      if (neverKind === 'emails' && row.kind !== 'email') return false;
      if (q && !row.value.toLowerCase().includes(q)) return false;
      return true;
    });
  }, [neverKind, neverRows, neverScope, neverSearch]);

  const saveAliases = useCallback(
    async (list: string[]) => {
      if (!profile) return false;
      try {
        const next = await updateProfile({
          preferences: { emailAliases: list },
          updatedAt: profile.updatedAt,
        });
        onProfileUpdated(next);
        setAliases(next.preferences.emailAliases ?? list);
        return true;
      } catch (err) {
        toast(errorText(err), 'danger');
        return false;
      }
    },
    [onProfileUpdated, profile, toast],
  );

  const saveNeverLists = useCallback(
    async (emails: string[], domains: string[]) => {
      setNeverBusy(true);
      try {
        const ext = await updateExtensionSettings({
          neverLogEmails: emails,
          neverLogDomains: domains,
        });
        setUserNeverEmails(ext.user.neverLogEmails.map((e) => e.toLowerCase()));
        setUserNeverDomains(ext.user.neverLogDomains.map((d) => d.toLowerCase()));
        setNeverRows(buildNeverLogRows(ext));
        return true;
      } catch (err) {
        toast(errorText(err), 'danger');
        return false;
      } finally {
        setNeverBusy(false);
      }
    },
    [toast],
  );

  const addNeverLog = useCallback(
    async (data: FormData) => {
      const raw = String(data.get('never_log_items') || '');
      const bad = invalidNeverLogEntries(raw);
      if (bad.length) {
        toast(`Not a valid email or domain: ${bad.join(', ')}`, 'danger');
        return false;
      }
      const { emails, domains } = splitNeverLogItems(raw);
      if (!emails.length && !domains.length) {
        toast('Enter at least one email or domain.', 'danger');
        return false;
      }
      const nextEmails = [...new Set([...userNeverEmails, ...emails])];
      const nextDomains = [...new Set([...userNeverDomains, ...domains])];
      const ok = await saveNeverLists(nextEmails, nextDomains);
      return ok ? 'Added to Never Log list' : false;
    },
    [saveNeverLists, toast, userNeverDomains, userNeverEmails],
  );

  const removeNeverLog = useCallback(
    async (row: NeverLogRow) => {
      if (row.source !== 'user' || neverBusy) return;
      const confirmed = await confirm({
        title: 'Remove from Never Log?',
        message: `${row.value} will be logged again from the next email or meeting.`,
        confirmLabel: 'Remove',
        danger: true,
      });
      if (!confirmed) return;
      const value = row.value.replace(/^\*@/, '').toLowerCase();
      const nextEmails =
        row.kind === 'email' ? userNeverEmails.filter((e) => e !== value) : userNeverEmails;
      const nextDomains =
        row.kind === 'domain' ? userNeverDomains.filter((d) => d !== value) : userNeverDomains;
      const ok = await saveNeverLists(nextEmails, nextDomains);
      if (ok) toast('Removed from Never Log', 'info');
    },
    [confirm, neverBusy, saveNeverLists, toast, userNeverDomains, userNeverEmails],
  );

  const saveSignature = useCallback(async () => {
    if (!profile) return false;
    const html =
      sigMode === 'html'
        ? (sigHtmlRef.current?.value ?? sigHtml).trim()
        : (sigEditorRef.current?.innerHTML ?? sigHtml).trim();
    try {
      const p = await updateProfile({
        emailSignature: html || null,
        updatedAt: profile.updatedAt,
      });
      onProfileUpdated(p);
      applyProfile(p);
      return 'Email signature saved';
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  }, [applyProfile, onProfileUpdated, profile, sigHtml, sigMode, toast]);

  const saveUnsub = useCallback(
    async (data: FormData) => {
      if (!profile) return false;
      const choice = String(data.get('unsub_choice') || UNSUB_CHOICES[0]);
      if (!(UNSUB_CHOICES as readonly string[]).includes(choice)) {
        toast('Choose one of the unsubscribe sentences.', 'danger');
        return false;
      }
      try {
        const next = await updateProfile({
          preferences: { unsubscribeText: choice },
          updatedAt: profile.updatedAt,
        });
        onProfileUpdated(next);
        setUnsubText(choice);
        return 'Unsubscribe link updated';
      } catch (err) {
        toast(errorText(err), 'danger');
        return false;
      }
    },
    [onProfileUpdated, profile, toast],
  );

  const saveConfigureSettings = useCallback(
    async (form: HTMLFormElement) => {
      if (!profile) return false;
      const input = form.elements.namedItem('include_unsubscribe');
      const checked = input instanceof HTMLInputElement ? input.checked : includeUnsub;
      try {
        const next = await updateProfile({
          preferences: { includeUnsubscribeLink: checked },
          updatedAt: profile.updatedAt,
        });
        onProfileUpdated(next);
        setIncludeUnsub(checked);
      } catch (err) {
        toast(errorText(err), 'danger');
        return false;
      }
    },
    [includeUnsub, onProfileUpdated, profile, toast],
  );

  const turnOnNotifications = useCallback(async () => {
    if (typeof Notification === 'undefined') {
      toast('This browser does not support notifications.', 'danger');
      return;
    }
    const perm = await Notification.requestPermission();
    setBrowserPerm(perm);
    if (perm !== 'granted') {
      toast('Allow notifications in your browser settings to turn these on.', 'danger');
      return;
    }
    try {
      const ext = await updateExtensionSettings({
        notificationsEnabled: true,
        browserNotifyTypes: notifyTypes,
      });
      setNotifyEnabled(ext.user.notificationsEnabled);
      await syncExtensionNotifications(true);
      toast('Notifications are on', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  }, [notifyTypes, toast]);

  const patchNotifyType = useCallback(
    async (key: keyof BrowserNotifyTypes, checked: boolean) => {
      const next = { ...notifyTypes, [key]: checked };
      setNotifyTypes(next);
      try {
        await updateExtensionSettings({ browserNotifyTypes: next });
        await syncExtensionNotifications(notifyEnabled);
      } catch (err) {
        setNotifyTypes(notifyTypes);
        toast(errorText(err), 'danger');
      }
    },
    [notifyEnabled, notifyTypes, toast],
  );

  const openBcc = () => {
    setBccWorking([...bccList]);
    setBccDraft('');
    setBccOpen(true);
  };
  const openIps = () => {
    setIpsWorking([...blockedIps]);
    setIpDraft('');
    setIpsOpen(true);
  };

  const saveBcc = useCallback(async () => {
    const bad = bccWorking.filter((addr) => !EMAIL_RE.test(addr));
    if (bad.length) {
      toast(`Not a valid email: ${bad.join(', ')}`, 'danger');
      return false;
    }
    try {
      const ext = await updateExtensionSettings({ bccAddresses: bccWorking });
      setBccList(ext.user.bccAddresses ?? bccWorking);
      return 'BCC settings saved';
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  }, [bccWorking, toast]);

  const saveIps = useCallback(async () => {
    const bad = ipsWorking.filter((ip) => !isIpAddress(ip));
    if (bad.length) {
      toast(`Not a valid IP address: ${bad.join(', ')}`, 'danger');
      return false;
    }
    try {
      const ext = await updateExtensionSettings({ excludedIps: ipsWorking });
      setBlockedIps(ext.user.excludedIps ?? ipsWorking);
      return 'Blocked IP addresses saved';
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  }, [ipsWorking, toast]);

  const runSigCmd = (cmd: string) => {
    restoreSigRange();
    document.execCommand(cmd, false);
    saveSigRange();
    if (sigEditorRef.current && sigHtmlRef.current) {
      sigHtmlRef.current.value = sigEditorRef.current.innerHTML;
      setSigHtml(sigEditorRef.current.innerHTML);
    }
  };

  const placeSigPop = (anchor: HTMLElement | null) => {
    if (!anchor) return;
    const rect = anchor.getBoundingClientRect();
    const left = Math.min(Math.max(8, rect.left), window.innerWidth - 320);
    const top = Math.min(rect.bottom + 8, window.innerHeight - 280);
    setSigPopPos({ top, left });
  };

  const openLinkPop = () => {
    saveSigRange();
    const text = sigRangeRef.current?.toString() ?? '';
    setLinkText(text);
    setLinkUrl('');
    setLinkBlank(true);
    placeSigPop(linkToolRef.current);
    setSigPop('link');
  };

  const openImagePop = () => {
    saveSigRange();
    setImageUrl('');
    placeSigPop(imageToolRef.current);
    setSigPop('image');
  };

  const insertLink = () => {
    let url = linkUrl.trim();
    if (!url) return;
    if (!/^(https?:|mailto:|tel:|#|\/)/i.test(url)) url = `https://${url}`;
    const label = linkText.trim() || url;
    const target = linkBlank ? ' target="_blank" rel="noopener"' : '';
    setSigPop(null);
    insertSigHtml(`<a href="${escapeAttr(url)}"${target}>${escapeHtml(label)}</a>&nbsp;`);
  };

  const insertImageFromUrl = () => {
    const url = imageUrl.trim();
    if (!url) return;
    setSigPop(null);
    insertSigHtml(`<img src="${escapeAttr(url)}" alt="" style="max-width: 100%; height: auto;">`);
  };

  const insertImageFromFile = (file: File) => {
    const reader = new FileReader();
    reader.onload = () => {
      setSigPop(null);
      insertSigHtml(
        `<img src="${String(reader.result)}" alt="${escapeAttr(file.name)}" style="max-width: 100%; height: auto;">`,
      );
    };
    reader.readAsDataURL(file);
  };

  return (
    <>
      <p className="set-preferences-note">
        These preferences only apply to you. For account level email management, go to{' '}
        <Link
          className="link crm-fw-semibold set-link-inline"
          href="/settings/objects?object=activities"
          target="_self"
          rel="noreferrer"
        >
          email logging settings <CrmIcon name="external" className="iconSize-14" />
        </Link>
        .
      </p>

      {/* 1. Email */}
      <div className="card set-card">
        {!outlookTipDismissed ? (
          <div className="set-email-pro-tip" role="note">
            <span className="set-email-pro-tip__icon" aria-hidden="true">
              <CrmIcon name="pin" className="iconSize-16" />
            </span>
            <p className="set-email-pro-tip__text">
              <strong>Pro tip</strong> Install the add-in for Outlook (Windows/PC) to use CRM in
              your Outlook.
            </p>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm set-email-pro-tip__action"
              onClick={startOutlookAddinInstall}
            >
              Install add-in
            </button>
            <button
              type="button"
              className="set-email-pro-tip__close"
              aria-label="Dismiss tip"
              onClick={dismissOutlookTip}
            >
              <CrmIcon name="x" className="iconSize-14" />
            </button>
          </div>
        ) : null}

        <div className="set-card__head set-card__head--email">
          <div>
            <h2 className="set-card__title">Email</h2>
            <p className="set-card__sub">
              Connect your individual work email accounts to CRM to log, track, send, and receive
              emails in the CRM. To manage any team emails, go to{' '}
              <Link
                className="link set-link-inline"
                href="/settings/inboxes"
                target="_self"
                rel="noreferrer"
              >
                inbox settings <CrmIcon name="external" className="iconSize-14" />
              </Link>
              .
            </p>
          </div>
        </div>

        {mailbox?.connected ? (
          <div className="email-account-block">
            <div className="email-account-table-wrap">
              <table className="email-account-table">
                <thead>
                  <tr className="email-account-table__head">
                    <th scope="col">Email</th>
                    <th scope="col">Status</th>
                    <th scope="col">
                      Inbox automation{' '}
                      <span
                        className={cn(
                          'set-info set-info--wide set-info--panel',
                          accountTip === INBOX_AUTOMATION_TIP && 'is-open',
                        )}
                        tabIndex={0}
                        role="button"
                        aria-expanded={accountTip === INBOX_AUTOMATION_TIP}
                        aria-controls="email-account-tip"
                        aria-label="Inbox automation info"
                        onClick={() => toggleAccountTip(INBOX_AUTOMATION_TIP)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            toggleAccountTip(INBOX_AUTOMATION_TIP);
                          }
                        }}
                      >
                        <CrmIcon name="info" className="iconSize-14" />
                      </span>
                    </th>
                    <th scope="col">
                      Default signature{' '}
                      <span
                        className={cn(
                          'set-info set-info--wide set-info--panel',
                          accountTip === DEFAULT_SIGNATURE_TIP && 'is-open',
                        )}
                        tabIndex={0}
                        role="button"
                        aria-expanded={accountTip === DEFAULT_SIGNATURE_TIP}
                        aria-controls="email-account-tip"
                        aria-label="Default signature info"
                        onClick={() => toggleAccountTip(DEFAULT_SIGNATURE_TIP)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            toggleAccountTip(DEFAULT_SIGNATURE_TIP);
                          }
                        }}
                      >
                        <CrmIcon name="info" className="iconSize-14" />
                      </span>
                    </th>
                    <th scope="col" aria-label="Actions" />
                  </tr>
                </thead>
                <tbody>
                  <tr
                    className={cn('email-account-row', accountActionsOpen && 'is-actions-open')}
                    data-email={mailbox.emailAddress ?? undefined}
                    data-provider="Google"
                    data-enabled={
                      !inboxDisabled && !needsReconnect(mailbox) && mailbox.status !== 'error'
                        ? 'true'
                        : 'false'
                    }
                  >
                    <td className="email-account-identity">
                      <span className="email-account-logo">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src="/crm/assets/img/gmail.svg" alt="Gmail" />
                      </span>
                      <span className="email-account-identity__copy">
                        <strong>{mailbox.emailAddress ?? 'Connected account'}</strong>
                        <span>Inbox type: G Suite</span>
                      </span>
                    </td>
                    <td>
                      <div
                        className={cn(
                          'email-account-status',
                          (inboxDisabled ||
                            needsReconnect(mailbox) ||
                            mailbox.status === 'error') &&
                            'is-warn',
                        )}
                      >
                        <span className="email-status-dot" aria-hidden="true" />
                        <span>
                          {inboxDisabled
                            ? 'Disabled'
                            : needsReconnect(mailbox)
                              ? 'Needs reconnect'
                              : mailbox.status === 'error'
                                ? 'Error'
                                : mailbox.status === 'syncing'
                                  ? 'Syncing'
                                  : 'Enabled'}
                        </span>
                      </div>
                    </td>
                    <td>
                      <div className="email-account-automation">
                        <label className="switch" aria-label="Inbox automation">
                          <input
                            type="checkbox"
                            checked={inboxAutomation}
                            disabled={inboxAutomationLocked || inboxAutomationBusy}
                            onChange={(e) => void toggleInboxAutomation(e.target.checked)}
                          />
                          <span className="switch__track" />
                        </label>
                      </div>
                    </td>
                    <td>
                      <div className="email-account-signature">
                        <span>{EMAIL_SIGNATURE_MODE_LABEL[signatureModeLabel]}</span>
                      </div>
                    </td>
                    <td className="email-account-actions-cell">
                      <div
                        ref={accountActionsRef}
                        className={cn('email-account-actions', accountActionsOpen && 'is-open')}
                      >
                        <button
                          type="button"
                          className="btn-crm btn-crm--outline btn-crm--sm email-actions-trigger"
                          aria-haspopup="menu"
                          aria-expanded={accountActionsOpen}
                          onClick={toggleAccountActions}
                        >
                          Actions{' '}
                          <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
                            <path
                              d="m4 6 4 4 4-4"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="1.8"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            />
                          </svg>
                        </button>
                        {accountActionsOpen && accountActionsPos && typeof document !== 'undefined'
                          ? createPortal(
                              <div
                                ref={accountActionsMenuRef}
                                className="email-actions-menu is-fixed"
                                role="menu"
                                style={{
                                  top: accountActionsPos.top,
                                  left: accountActionsPos.left,
                                }}
                              >
                                <button
                                  type="button"
                                  role="menuitem"
                                  onClick={() => {
                                    setAccountActionsOpen(false);
                                    setAccountActionsPos(null);
                                    openEmailInstallDialog('gmail');
                                  }}
                                >
                                  Install extension
                                </button>
                                <button
                                  type="button"
                                  role="menuitem"
                                  onClick={() => {
                                    setAccountActionsOpen(false);
                                    setAccountActionsPos(null);
                                    if (inboxDisabled) enableInbox();
                                    else setDisableInboxOpen(true);
                                  }}
                                >
                                  {inboxDisabled ? 'Enable' : 'Disable'}
                                </button>
                                <button
                                  type="button"
                                  role="menuitem"
                                  onClick={() => {
                                    setAccountActionsOpen(false);
                                    setAccountActionsPos(null);
                                    openSignatureDefaultDialog();
                                  }}
                                >
                                  Edit default signature
                                </button>
                                {mailbox.gmailConsent === 'limited' && onUpgradeConsent ? (
                                  <button
                                    type="button"
                                    role="menuitem"
                                    onClick={() => {
                                      setAccountActionsOpen(false);
                                      setAccountActionsPos(null);
                                      onUpgradeConsent();
                                    }}
                                  >
                                    Update Permissions
                                  </button>
                                ) : null}
                                {needsReconnect(mailbox) ? (
                                  <button
                                    type="button"
                                    role="menuitem"
                                    onClick={() => {
                                      setAccountActionsOpen(false);
                                      setAccountActionsPos(null);
                                      onConnect();
                                    }}
                                  >
                                    Reconnect
                                  </button>
                                ) : null}
                                <span className="email-actions-menu__divider" />
                                <button
                                  type="button"
                                  className="is-danger"
                                  role="menuitem"
                                  onClick={() => {
                                    setAccountActionsOpen(false);
                                    setAccountActionsPos(null);
                                    setRemoveInboxOpen(true);
                                  }}
                                >
                                  Remove
                                </button>
                              </div>,
                              document.body,
                            )
                          : null}
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            {accountTip ? (
              <div
                id="email-account-tip"
                ref={accountTipRef}
                className="email-account-tip"
                role="tooltip"
              >
                {accountTip}
              </div>
            ) : null}

            <div className="email-account-table-actions">
              <button type="button" className="btn-crm btn-crm--outline" onClick={onConnect}>
                Connect email account
              </button>
            </div>
          </div>
        ) : (
          <div className="set-email-connect">
            <ul className="set-email-connect__benefits">
              <li>
                <CrmIcon name="check" className="iconSize-16" />
                <span>Send and schedule emails from CRM</span>
              </li>
              <li>
                <CrmIcon name="check" className="iconSize-16" />
                <span>Log email replies to CRM automatically</span>
              </li>
              <li>
                <CrmIcon name="check" className="iconSize-16" />
                <div>
                  <span>Suggest follow-up tasks and capture contact details from your email</span>
                  <small>Requires inbox automation</small>
                </div>
              </li>
            </ul>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={onConnect}
              disabled={mailbox === null}
            >
              {mailbox === null ? 'Loading…' : 'Connect email account'}
            </button>
          </div>
        )}
      </div>

      {/* 2. Configure — form fields (unsubscribe) use the bottom save bar */}
      <SettingsForm
        onSave={saveConfigureSettings}
        onReset={() => {
          setIncludeUnsub(profile?.preferences.includeUnsubscribeLink !== false);
        }}
      >
        <div className="card set-card">
          <h2 className="set-card__title crm-mb-4">Configure</h2>
          <div className="crm-d-flex crm-flex-column crm-gap-4">
            <div className="crm-d-flex crm-flex-column crm-gap-1">
              <h3 className="crm-m-0 crm-fs-7 crm-fw-semibold">
                <button type="button" className="link" onClick={() => setAliasOpen(true)}>
                  Add email alias
                </button>
              </h3>
              <p className="crm-m-0 crm-fs-7 crm-text-muted crm-lh-base">
                An email alias allows emails sent outside of CRM to be associated with your user.
              </p>
              {aliases.length > 0 ? (
                <div className="crm-mt-3">
                  <p className="crm-fs-8 crm-fw-bold crm-text-dark crm-m-0 crm-mb-2">
                    CURRENT EMAIL ALIASES:
                  </p>
                  <div className="crm-d-flex crm-flex-column crm-gap-2">
                    {aliases.map((email) => (
                      <div key={email} className="crm-d-flex crm-align-items-center crm-gap-2">
                        <span className="crm-fs-7 crm-text-dark">{email}</span>
                        <button
                          type="button"
                          className="icon-btn crm-rounded-circle h-32 w-32"
                          aria-label={`Delete alias ${email}`}
                          onClick={() => {
                            void (async () => {
                              const confirmed = await confirm({
                                title: 'Remove email alias?',
                                message: `${email} will no longer be linked to your user.`,
                                confirmLabel: 'Remove',
                                danger: true,
                              });
                              if (!confirmed) return;
                              const ok = await saveAliases(aliases.filter((a) => a !== email));
                              if (ok) toast('Alias removed', 'info');
                            })();
                          }}
                        >
                          <CrmIcon name="trash" className="iconSize-16" />
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              ) : null}
            </div>

            <div className="crm-d-flex crm-flex-column crm-gap-1">
              <h3 className="crm-m-0 crm-fs-7 crm-fw-semibold">
                <button
                  type="button"
                  className="link"
                  aria-haspopup="dialog"
                  aria-expanded={sigOpen}
                  onClick={() => setSigOpen(true)}
                >
                  Manage email signatures
                </button>
              </h3>
              <p className="crm-m-0 crm-fs-7 crm-text-muted crm-lh-base">
                Your signature will be used in one-on-one emails through the CRM and as a
                personalization token for marketing emails.
              </p>
            </div>

            <div className="crm-d-flex crm-flex-column crm-gap-1">
              <div className="crm-d-flex crm-align-items-center crm-gap-2">
                <label className="check">
                  <input
                    key={profile?.updatedAt ?? 'include-unsubscribe'}
                    type="checkbox"
                    name="include_unsubscribe"
                    id="chk-unsubscribe"
                    defaultChecked={includeUnsub}
                    onChange={(e) => setIncludeUnsub(e.target.checked)}
                  />
                  <span className="check__box" aria-hidden="true" />
                  <span className="crm-text-dark crm-fw-medium">Include unsubscribe link</span>
                </label>
                <span className="badge crm-bg-indigo-subtle crm-text-indigo">Recommended</span>
              </div>
              <p className="crm-m-0 crm-fs-7 crm-text-muted crm-lh-base crm-ps-4">
                Include a link at the bottom of your emails allowing recipients to unsubscribe. It
                will help you stay compliant with local spam laws and improve deliverability.
              </p>
              <div className="crm-ps-4 crm-mt-2">
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  id="btn-unsubscribe-edit"
                  disabled={!includeUnsub}
                  onClick={() => setUnsubOpen(true)}
                >
                  Edit unsubscribe link
                </button>
              </div>
            </div>
          </div>
        </div>
      </SettingsForm>

      {/* 3. Never Log */}
      <div className="card set-card">
        <h2 className="set-card__title">Never Log</h2>
        <p className="set-card__sub">
          The Never Log list ensures emails and meetings with specified domains or email addresses
          are not automatically logged to your CRM. Admins can manage Never Log for all users in{' '}
          <Link className="link" href="/settings/account-defaults">
            email logging settings <CrmIcon name="external" className="iconSize-14" />
          </Link>
          .
        </p>

        <div className="set-toolbar never-log-toolbar crm-mt-4">
          <label className="settings-nav__search">
            <CrmIcon name="search" className="iconSize-16" />
            <input
              type="search"
              placeholder="Search emails or domains"
              value={neverSearch}
              onChange={(e) => setNeverSearch(e.target.value)}
              aria-label="Search emails or domains"
            />
          </label>
          <span className="never-log-filter-label">View:</span>
          <CustomSelect
            className="never-log-filter-select"
            placeholder="View"
            value={neverScope}
            options={[...NEVER_SCOPE_OPTIONS]}
            searchable={false}
            menuActions={false}
            menuMinWidth={200}
            onChange={(value) => setNeverScope((value || 'all') as NeverScopeFilter)}
          />
          <CustomSelect
            className="never-log-filter-select"
            placeholder="Domains and Emails"
            value={neverKind}
            options={[...NEVER_KIND_OPTIONS]}
            searchable={false}
            menuActions={false}
            menuMinWidth={190}
            onChange={(value) => setNeverKind((value || 'both') as NeverKindFilter)}
          />
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm crm-ms-auto crm-rounded-md"
            onClick={() => setNeverOpen(true)}
          >
            Add emails or domains
          </button>
        </div>

        {filteredNeverRows.length > 0 ? (
          <div className="card set-table-card crm-mt-3">
            <table className="set-table" id="never-log-table">
              <thead>
                <tr>
                  <th>
                    Domains and Email Addresses <span className="set-sort-icon">⇅</span>
                  </th>
                  <th aria-hidden="true" />
                  <th className="crm-text-end">
                    Blocked for <span className="set-sort-icon">⇅</span>
                  </th>
                </tr>
              </thead>
              <tbody id="never-log-rows">
                {filteredNeverRows.map((row) => (
                  <tr key={`${row.source}-${row.value}`}>
                    <td className="crm-fw-semibold">{row.value}</td>
                    <td />
                    <td className="crm-text-end never-log-row-actions">
                      {row.source === 'user' ? (
                        <button
                          type="button"
                          className="never-log-remove"
                          disabled={neverBusy}
                          onClick={() => void removeNeverLog(row)}
                        >
                          Remove
                        </button>
                      ) : null}
                      <span className="badge badge--neutral">
                        {row.source === 'admin' ? 'All Users' : 'You'}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : null}

        <div className="never-log-empty" id="never-log-empty" hidden={filteredNeverRows.length > 0}>
          <p>
            All Never Log items will be
            <br />
            shown here.
          </p>
          <svg
            className="never-log-empty__art"
            viewBox="0 0 180 150"
            role="img"
            aria-label="Empty list illustration"
          >
            <path
              d="M10 112 86 68a12 12 0 0 1 12 0l72 42a7 7 0 0 1 0 12l-72 42a12 12 0 0 1-12 0l-76-42a6 6 0 0 1 0-10Z"
              fill="#eef3f8"
            />
            <path
              d="m68 66-18 46a8 8 0 0 0 4 10l28 16a8 8 0 0 0 8 0l29-16a8 8 0 0 0 4-10L104 66"
              fill="#fff"
              stroke="#cbd8e8"
              strokeDasharray="3 3"
            />
            <ellipse
              cx="85"
              cy="43"
              rx="30"
              ry="21"
              transform="rotate(-14 85 43)"
              fill="#fff"
              stroke="#c5d4e7"
              strokeWidth="4"
            />
            <ellipse
              cx="85"
              cy="43"
              rx="22"
              ry="15"
              transform="rotate(-14 85 43)"
              fill="#f8fbff"
              stroke="#d5e0ee"
              strokeWidth="2"
            />
            <path
              d="m107 56 18 13a7 7 0 0 1-8 11L99 67"
              fill="#e9f0f8"
              stroke="#c5d4e7"
              strokeWidth="3"
            />
            <path
              d="m122 16 5-10m9 22 10-4m-18 17 11 5"
              fill="none"
              stroke="#c5d4e7"
              strokeWidth="2"
              strokeLinecap="round"
            />
            <path
              d="M56 35c9-12 23-15 34-11"
              fill="none"
              stroke="#e1e9f3"
              strokeWidth="2"
              strokeLinecap="round"
            />
          </svg>
        </div>
      </div>

      {/* 4. Download the email extension */}
      <div className="card set-card crm-p-0 crm-overflow-hidden">
        <details className="set-accordion" open>
          <summary className="set-accordion__summary crm-d-flex crm-align-items-center crm-gap-2 crm-p-3 crm-fs-7 crm-fw-semibold crm-text-dark crm-user-select-none">
            <span className="set-accordion__icon crm-text-muted">
              <CrmIcon name="chevron-down" className="iconSize-16" />
            </span>
            <span>Download the email extension</span>
          </summary>
          <div className="crm-px-4 crm-pb-4">
            <div className="crm-d-flex crm-flex-column crm-gap-4">
              {/* Gmail Chrome */}
              <div className="crm-d-flex crm-align-items-start crm-gap-3">
                <div className="crm-flex-shrink-0 crm-d-flex crm-align-items-center crm-justify-content-center crm-mt-1">
                  <svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">
                    <path
                      fill="#EA4335"
                      d="M12 13.5L2 6V18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6l-10 7.5z"
                    />
                    <path fill="#4285F4" d="M20 4H4c-1.1 0-2 .9-2 2l10 7.5L22 6c0-1.1-.9-2-2-2z" />
                  </svg>
                </div>
                <div className="crm-flex-grow-1">
                  <h3 className="crm-m-0 crm-fs-7 crm-fw-semibold">
                    {/* SEQ-R-M1 / GAP-r59: our own extension's listing, never HubSpot's (as
                        Sequences' banner); until it exists the link says so instead. */}
                    {SALES_EXTENSION_INSTALL_URL ? (
                      <a
                        href={SALES_EXTENSION_INSTALL_URL}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="link"
                      >
                        Install CRM Sales Extension for Gmail (Chrome)
                      </a>
                    ) : (
                      <button
                        type="button"
                        className="link"
                        disabled
                        title="The Sales extension is not published yet"
                      >
                        Install CRM Sales Extension for Gmail (Chrome)
                      </button>
                    )}
                  </h3>
                  <p className="crm-m-0 crm-mt-1 crm-fs-7 crm-text-muted crm-lh-base">
                    The Chrome Extension works with Gmail to track email opens, log emails in your
                    CRM automatically, and use templates in your inbox.
                  </p>
                </div>
              </div>

              {/* Office 365 */}
              <div className="crm-d-flex crm-align-items-start crm-gap-3">
                <div className="crm-flex-shrink-0 crm-d-flex crm-align-items-center crm-justify-content-center crm-mt-1">
                  <svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">
                    <rect x="3" y="3" width="8" height="8" fill="#F25022" />
                    <rect x="13" y="3" width="8" height="8" fill="#7FBA00" />
                    <rect x="3" y="13" width="8" height="8" fill="#00A4EF" />
                    <rect x="13" y="13" width="8" height="8" fill="#FFB900" />
                  </svg>
                </div>
                <div className="crm-flex-grow-1">
                  <h3 className="crm-m-0 crm-fs-7 crm-fw-semibold">
                    <a
                      href={OUTLOOK_ADDIN_URL}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="link"
                    >
                      Download CRM Sales add-in for Office 365
                    </a>
                  </h3>
                  <p className="crm-m-0 crm-mt-1 crm-fs-7 crm-text-muted crm-lh-base">
                    The Office 365 add-in works with Outlook to track email opens, log emails in
                    your CRM automatically, and use templates in your inbox. This is the recommended
                    choice for Office 365 users on all platforms.
                  </p>
                </div>
              </div>

              {/* Outlook Windows/PC */}
              <div className="crm-d-flex crm-align-items-start crm-gap-3">
                <div className="crm-flex-shrink-0 crm-d-flex crm-align-items-center crm-justify-content-center crm-mt-1">
                  <svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">
                    <path
                      fill="#0078D4"
                      d="M2 5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5z"
                    />
                    <path fill="#FFFFFF" d="M12 13L4 7h16l-8 6z" />
                  </svg>
                </div>
                <div className="crm-flex-grow-1">
                  <h3 className="crm-m-0 crm-fs-7 crm-fw-semibold">
                    <button type="button" className="link" onClick={startOutlookAddinInstall}>
                      Download CRM Sales add-in for Outlook (Windows/PC)
                    </button>
                  </h3>
                  <p className="crm-m-0 crm-mt-1 crm-fs-7 crm-text-muted crm-lh-base">
                    The Outlook for Windows desktop add-in is now in maintenance mode, and we only
                    recommend using this if you do not have an inbox compatible with Office 365.
                    This add-in is able to track email opens, log emails in your CRM, and can use
                    templates.{' '}
                    <a
                      href="https://appsource.microsoft.com"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="link"
                    >
                      System requirements <CrmIcon name="external" className="iconSize-14" />
                    </a>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </details>
      </div>

      {/* 5. Extension settings */}
      <div className="card set-card crm-p-0 crm-overflow-hidden">
        <details className="set-accordion" open>
          <summary className="set-accordion__summary crm-d-flex crm-align-items-center crm-gap-2 crm-p-3 crm-fs-7 crm-fw-semibold crm-text-dark crm-user-select-none">
            <span className="set-accordion__icon crm-text-muted">
              <CrmIcon name="chevron-down" className="iconSize-16" />
            </span>
            <span>Extension settings</span>
          </summary>
          <div className="crm-px-4 crm-pb-4">
            <div className="crm-d-flex crm-flex-column crm-gap-4">
              <div className="crm-d-flex crm-flex-column crm-gap-1">
                <h3 className="crm-m-0 crm-fs-7 crm-fw-semibold">
                  <button type="button" className="link" onClick={openBcc}>
                    Manage additional BCC addresses
                  </button>
                </h3>
                <p className="crm-m-0 crm-fs-7 crm-text-muted crm-lh-base">
                  Log emails you send to an external CRM in addition to your CRM. Only works for
                  emails sent using a sales extension.
                </p>
              </div>
              <div className="crm-d-flex crm-flex-column crm-gap-1">
                <h3 className="crm-m-0 crm-fs-7 crm-fw-semibold">
                  <button type="button" className="link" onClick={openIps}>
                    Manage blocked IP addresses
                  </button>
                </h3>
                <p className="crm-m-0 crm-fs-7 crm-text-muted crm-lh-base">
                  Don&apos;t track email opens or clicks from specific IP addresses.
                </p>
              </div>
              <div className="crm-d-flex crm-flex-column crm-gap-1">
                <h3 className="crm-m-0 crm-fs-7 crm-fw-semibold">
                  <Link href="/settings/sales-extension-views?tab=email" className="link">
                    Customize Sales Extension Views
                  </Link>
                </h3>
                <p className="crm-m-0 crm-fs-7 crm-text-muted crm-lh-base">
                  Configure the card layout for each object type and location in your CRM Sales
                  Extension sidebar.
                </p>
              </div>
            </div>
          </div>
        </details>
      </div>

      {/* 6. Sales Notifications */}
      <div className="card set-card">
        <h2 className="set-card__title crm-mb-3">Sales Notifications</h2>
        {!notifyEnabled || browserPerm !== 'granted' ? (
          <div className="crm-p-4 crm-rounded-4 crm-bg-warning-subtle crm-border crm-border-warning-subtle crm-fs-7">
            <strong className="crm-d-block crm-fw-semibold crm-text-dark crm-mb-1">
              Notifications are off.
            </strong>
            <p className="crm-m-0 crm-text-muted crm-fs-7">
              Give CRM permission to send notifications to this browser.
            </p>
            <div className="crm-mt-3">
              <button
                type="button"
                className="btn-crm btn-crm--primary btn-crm--sm"
                onClick={() => void turnOnNotifications()}
              >
                Turn on
              </button>
            </div>
          </div>
        ) : (
          <div className="sales-notifications-settings">
            <div className="sales-notifications-status">
              <h3>Notifications</h3>
              <p className="sales-notifications-enabled">
                <span className="sales-notifications-dot" aria-hidden="true" />
                Notifications are on.
              </p>
              <Link className="sales-notifications-manage" href="/settings/notifications">
                Manage notifications <span aria-hidden="true">↗</span>
              </Link>
            </div>
            <div className="sales-notifications-options" id="browser-notifications">
              <h3>Browser Notifications</h3>
              <p>Choose what you get notified about.</p>
              {(
                [
                  ['email_open', 'Email opens'],
                  ['email_click', 'Email clicks'],
                  ['document_view', 'Document views'],
                  ['lead_visit', 'Lead revisits'],
                ] as const
              ).map(([key, label]) => (
                <label key={key} className="check sales-notification-option">
                  <input
                    type="checkbox"
                    checked={notifyTypes[key]}
                    onChange={(e) => void patchNotifyType(key, e.target.checked)}
                  />
                  <span className="check__box" aria-hidden="true" />
                  <span>{label}</span>
                </label>
              ))}
              <label
                className="check sales-notification-option is-disabled sales-notification-tooltip"
                data-tooltip="To enable, you must create at least one saved view."
                tabIndex={0}
                aria-label="Prospector revisits. To enable, you must create at least one saved view."
              >
                <input type="checkbox" disabled checked={false} />
                <span className="check__box" aria-hidden="true" />
                <span>Prospector revisits</span>
              </label>
            </div>
          </div>
        )}
      </div>

      {/* Alias drawer */}
      <DrawerForm
        id="alias-dialog"
        title="Add email alias"
        open={aliasOpen}
        onClose={() => setAliasOpen(false)}
        submitLabel="Add alias"
        success="Alias added"
        onSave={async (data) => {
          const email = String(data.get('alias_email') || '')
            .trim()
            .toLowerCase();
          if (!EMAIL_RE.test(email)) {
            toast('Enter a valid email address.', 'danger');
            return false;
          }
          if (aliases.includes(email)) {
            toast('That alias is already on your list.', 'danger');
            return false;
          }
          const ok = await saveAliases([...aliases, email]);
          return ok ? 'Alias added' : false;
        }}
      >
        <SuField
          label="Email alias"
          htmlFor="alias-email"
          help="Emails sent from this address outside CRM can still be associated with you."
          error="Enter a valid email address, for example alias@company.com."
        >
          <input
            className="input"
            id="alias-email"
            name="alias_email"
            type="email"
            required
            placeholder="alias@company.com"
          />
        </SuField>
      </DrawerForm>

      {/* Manage email signatures — centred modal (design: sig-manage-modal) */}
      <SetDialog
        open={sigOpen}
        onClose={() => {
          setSigPop(null);
          setSigOpen(false);
        }}
        labelledBy="sig-title"
        className="sig-manage-modal"
      >
        <form
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            void (async () => {
              const result = await saveSignature();
              if (result === false) return;
              toast(typeof result === 'string' ? result : 'Email signature saved', 'success');
              setSigPop(null);
              setSigOpen(false);
            })();
          }}
        >
          <DialogHead
            id="sig-title"
            title="Manage email signatures"
            onClose={() => {
              setSigPop(null);
              setSigOpen(false);
            }}
          />
          <div className="set-modal__body sig-manage-modal__body">
            <div className="field sig-manage-modal__field">
              <label className="field__label" htmlFor="sig-choose">
                Choose signature to edit
              </label>
              <select
                className="input"
                id="sig-choose"
                name="signature_choice"
                disabled
                aria-disabled="true"
                defaultValue="new"
              >
                <option value="new">Add new signature</option>
              </select>
            </div>

            <div className="field sig-manage-modal__field">
              <label className="field__label" htmlFor="sig-name">
                Signature name *
              </label>
              <input
                className="input"
                id="sig-name"
                name="signature_name"
                value={sigName}
                required
                onChange={(e) => setSigName(e.target.value)}
              />
            </div>

            <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-mb-3 sig-manage-modal__signature-head">
              <label className="crm-fs-7 crm-fw-bold crm-text-dark crm-m-0">Signature</label>
              <div className="sig-mode-pills" role="radiogroup" aria-label="Signature format">
                <button
                  type="button"
                  className={cn('sig-mode-btn', sigMode === 'simple' && 'is-active')}
                  data-sig-mode="simple"
                  aria-checked={sigMode === 'simple'}
                  role="radio"
                  onClick={() => {
                    if (sigMode === 'html' && sigHtmlRef.current && sigEditorRef.current) {
                      sigEditorRef.current.innerHTML = sigHtmlRef.current.value;
                    }
                    setSigPop(null);
                    setSigMode('simple');
                  }}
                >
                  Simple
                </button>
                <button
                  type="button"
                  className={cn('sig-mode-btn', sigMode === 'html' && 'is-active')}
                  data-sig-mode="html"
                  aria-checked={sigMode === 'html'}
                  role="radio"
                  onClick={() => {
                    if (sigMode === 'simple' && sigEditorRef.current && sigHtmlRef.current) {
                      sigHtmlRef.current.value = sigEditorRef.current.innerHTML;
                      setSigHtml(sigEditorRef.current.innerHTML);
                    }
                    setSigPop(null);
                    setSigMode('html');
                  }}
                >
                  HTML
                </button>
              </div>
            </div>

            <div
              className={cn(
                'sig-editor-wrap crm-border crm-rounded-3 crm-overflow-hidden crm-d-flex crm-flex-column',
                sigMode === 'html' && 'crm-d-none',
              )}
            >
              <div
                className="sig-editor-area"
                ref={sigEditorRef}
                contentEditable
                role="textbox"
                aria-multiline
                data-placeholder="Start typing your signature…"
                suppressContentEditableWarning
                onInput={() => {
                  saveSigRange();
                  if (sigEditorRef.current && sigHtmlRef.current) {
                    sigHtmlRef.current.value = sigEditorRef.current.innerHTML;
                    setSigHtml(sigEditorRef.current.innerHTML);
                  }
                }}
                onKeyUp={saveSigRange}
                onMouseUp={saveSigRange}
                onPaste={(e) => {
                  const text = e.clipboardData.getData('text/plain');
                  if (text == null) return;
                  e.preventDefault();
                  document.execCommand('insertText', false, text);
                }}
              />
              <div
                className="sig-toolbar crm-d-flex crm-align-items-center crm-gap-1 crm-px-2 crm-py-2 crm-border-top"
                role="toolbar"
                aria-label="Text formatting"
              >
                <button
                  type="button"
                  className="sig-tool"
                  title="Bold (Ctrl+B)"
                  aria-label="Bold"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => runSigCmd('bold')}
                >
                  <SigToolIcon d="M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z" />
                </button>
                <button
                  type="button"
                  className="sig-tool"
                  title="Italic (Ctrl+I)"
                  aria-label="Italic"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => runSigCmd('italic')}
                >
                  <SigToolIcon d="M19 4h-9M14 20H5M15 4 9 20" />
                </button>
                <button
                  type="button"
                  className="sig-tool"
                  title="Underline (Ctrl+U)"
                  aria-label="Underline"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => runSigCmd('underline')}
                >
                  <SigToolIcon d="M6 4v6a6 6 0 0 0 12 0V4M4 21h16" />
                </button>
                <button
                  type="button"
                  className="sig-tool"
                  title="Clear formatting"
                  aria-label="Clear formatting"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => runSigCmd('removeFormat')}
                >
                  <SigToolIcon d="M4 7V5h11v2M9.5 5 7 19M4 19h7M15 15l6 6M21 15l-6 6" />
                </button>
                <button
                  type="button"
                  className="sig-tool"
                  title="Bulleted list"
                  aria-label="Bulleted list"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => runSigCmd('insertUnorderedList')}
                >
                  <svg
                    viewBox="0 0 24 24"
                    width="16"
                    height="16"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M9 6h11M9 12h11M9 18h11" />
                    <circle cx="4.5" cy="6" r="1" fill="currentColor" />
                    <circle cx="4.5" cy="12" r="1" fill="currentColor" />
                    <circle cx="4.5" cy="18" r="1" fill="currentColor" />
                  </svg>
                </button>
                <button
                  type="button"
                  className="sig-tool"
                  title="Numbered list"
                  aria-label="Numbered list"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => runSigCmd('insertOrderedList')}
                >
                  <SigToolIcon d="M10 6h10M10 12h10M10 18h10M4 5h1v4M4 9h2M4 14h2l-2 3h2" />
                </button>
                <button
                  ref={imageToolRef}
                  type="button"
                  className="sig-tool"
                  title="Insert image"
                  aria-label="Insert image"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={openImagePop}
                >
                  <svg
                    viewBox="0 0 24 24"
                    width="16"
                    height="16"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    aria-hidden="true"
                  >
                    <rect x="3" y="4" width="18" height="16" rx="2" />
                    <circle cx="8.5" cy="9.5" r="1.5" />
                    <path d="m21 16-5-5-9 9" />
                  </svg>
                </button>
                <button
                  ref={linkToolRef}
                  type="button"
                  className="sig-tool"
                  title="Insert link (Ctrl+K)"
                  aria-label="Insert link"
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={openLinkPop}
                >
                  <SigToolIcon d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7" />
                </button>
              </div>
            </div>

            <textarea
              className={cn('sig-html-area crm-p-3', sigMode !== 'html' && 'crm-d-none')}
              ref={sigHtmlRef}
              rows={8}
              spellCheck={false}
              placeholder="<p>Enter HTML signature…</p>"
              defaultValue={sigHtml}
              onInput={(e) => {
                const value = e.currentTarget.value;
                setSigHtml(value);
                if (sigEditorRef.current) sigEditorRef.current.innerHTML = value;
              }}
            />

            <div
              className={cn('sig-html-preview-wrap', sigMode === 'html' && 'is-visible')}
              aria-live="polite"
            >
              <label className="field__label">Preview</label>
              <div
                className="sig-html-preview"
                // Preview mirrors the HTML editor; content is user-authored signature HTML.
                dangerouslySetInnerHTML={{ __html: sigHtml }}
              />
            </div>

            <label className="check sig-global-default">
              <input
                type="checkbox"
                name="global_default_signature"
                id="sig-global-default"
                defaultChecked
                disabled
                aria-disabled="true"
              />
              <span className="check__box" aria-hidden="true" />
              <span>
                Use as my global default signature{' '}
                <span
                  className="set-info"
                  tabIndex={0}
                  data-tip-text="This signature will be used by default in your one-on-one emails."
                  aria-label="Global default signature info"
                >
                  <CrmIcon name="info" className="iconSize-14" />
                </span>
              </span>
            </label>

            {sigPop === 'link' ? (
              <div
                className="sig-pop is-open"
                role="dialog"
                aria-label="Insert link"
                style={{ top: sigPopPos.top, left: sigPopPos.left }}
              >
                <form
                  className="sig-pop-form"
                  onSubmit={(e) => {
                    e.preventDefault();
                    insertLink();
                  }}
                >
                  <div className="sig-pop-field">
                    <label htmlFor="sig-link-text">Text to display</label>
                    <input
                      id="sig-link-text"
                      name="text"
                      autoComplete="off"
                      value={linkText}
                      onChange={(e) => setLinkText(e.target.value)}
                    />
                  </div>
                  <div className="sig-pop-field">
                    <label htmlFor="sig-link-url">URL</label>
                    <input
                      id="sig-link-url"
                      name="url"
                      placeholder="https://"
                      autoComplete="off"
                      autoFocus
                      required
                      value={linkUrl}
                      onChange={(e) => setLinkUrl(e.target.value)}
                    />
                  </div>
                  <label className="sig-pop-check">
                    <input
                      type="checkbox"
                      name="blank"
                      checked={linkBlank}
                      onChange={(e) => setLinkBlank(e.target.checked)}
                    />
                    <span>Open in a new tab</span>
                  </label>
                  <div className="sig-pop-actions">
                    <button type="submit" className="btn-crm btn-crm--primary btn-crm--sm">
                      Insert
                    </button>
                    <button
                      type="button"
                      className="btn-crm btn-crm--outline btn-crm--sm"
                      onClick={() => setSigPop(null)}
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              </div>
            ) : null}

            {sigPop === 'image' ? (
              <div
                className="sig-pop is-open"
                role="dialog"
                aria-label="Insert image"
                style={{ top: sigPopPos.top, left: sigPopPos.left }}
              >
                <form
                  className="sig-pop-form"
                  onSubmit={(e) => {
                    e.preventDefault();
                    insertImageFromUrl();
                  }}
                >
                  <div className="sig-pop-field">
                    <label htmlFor="sig-image-url">Image URL</label>
                    <input
                      id="sig-image-url"
                      name="url"
                      placeholder="https://"
                      autoComplete="off"
                      autoFocus
                      value={imageUrl}
                      onChange={(e) => setImageUrl(e.target.value)}
                    />
                  </div>
                  <div className="sig-pop-or">or</div>
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline btn-crm--sm w-100"
                    onClick={() => imageFileRef.current?.click()}
                  >
                    Upload from computer
                  </button>
                  <input
                    ref={imageFileRef}
                    type="file"
                    accept="image/*"
                    hidden
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (file) insertImageFromFile(file);
                      e.currentTarget.value = '';
                    }}
                  />
                  <div className="sig-pop-actions">
                    <button type="submit" className="btn-crm btn-crm--primary btn-crm--sm">
                      Insert
                    </button>
                    <button
                      type="button"
                      className="btn-crm btn-crm--outline btn-crm--sm"
                      onClick={() => setSigPop(null)}
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              </div>
            ) : null}

            {/* Multiple signatures / upgrade CTA is represented in design by the disabled
                "Choose signature to edit" select (Add new signature). Keep that UI only. */}
          </div>
          <div className="set-modal__foot crm-d-flex crm-align-items-center crm-gap-2">
            <button type="submit" className="btn-crm btn-crm--primary">
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => {
                setSigPop(null);
                setSigOpen(false);
              }}
            >
              Cancel
            </button>
          </div>
        </form>
      </SetDialog>

      {/* Unsubscribe drawer */}
      <DrawerForm
        id="unsub-dialog"
        title="Text for unsubscribe link"
        open={unsubOpen}
        onClose={() => setUnsubOpen(false)}
        keep
        onSave={saveUnsub}
      >
        <p className="crm-m-0 crm-fs-7 crm-text-dark crm-lh-base crm-mb-4">
          This unsubscribe link will be shown below your email signature in all CRM and sequence
          emails.
        </p>
        <div className="crm-d-flex crm-flex-column crm-gap-3">
          {UNSUB_CHOICES.map((choice) => (
            <label key={choice} className="set-radio">
              <input
                type="radio"
                name="unsub_choice"
                value={choice}
                defaultChecked={unsubText === choice}
              />
              <span className="set-radio__circle" aria-hidden="true" />
              <span>
                {choice.replace(/click here$/i, '')}
                <strong className="crm-text-primary">click here</strong>
              </span>
            </label>
          ))}
        </div>
      </DrawerForm>

      {/* Never log drawer */}
      <DrawerForm
        id="neverlog-dialog"
        title="Add emails or domains to Never Log"
        open={neverOpen}
        onClose={() => setNeverOpen(false)}
        submitLabel="Add to list"
        success="Added to Never Log list"
        onSave={addNeverLog}
      >
        <p className="field__help crm-mb-3">
          Specify domains (e.g. <code>example.com</code>) or exact email addresses to block from
          automatic logging.
        </p>
        <SuField
          label="Domains or emails"
          htmlFor="nl-items"
          help="Separate multiple entries with commas or newlines."
        >
          <textarea
            className="input"
            name="never_log_items"
            id="nl-items"
            rows={4}
            required
            placeholder={'competitor.com\npersonal@domain.com'}
          />
        </SuField>
      </DrawerForm>

      {/* BCC drawer */}
      <SetDialog open={bccOpen} onClose={() => setBccOpen(false)} drawer labelledBy="bcc-title">
        <form
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            void (async () => {
              const msg = await saveBcc();
              if (msg === false) return;
              toast(msg, 'success');
              setBccOpen(false);
            })();
          }}
        >
          <DialogHead
            id="bcc-title"
            title="Additional BCC address"
            onClose={() => setBccOpen(false)}
          />
          <div className="set-modal__body">
            <p className="crm-m-0 crm-fs-7 crm-text-dark crm-lh-base crm-mb-3">
              Log emails you send to an external CRM in addition to your CRM. Only works for emails
              sent using a sales extension.
            </p>
            <div className="crm-p-3 crm-rounded-3 crm-bg-warning-subtle crm-border crm-border-warning-subtle crm-fs-7 crm-text-dark crm-lh-base crm-mb-4">
              This feature can&apos;t be used for BCC addresses of other CRM accounts
            </div>
            <div className="crm-d-flex crm-gap-2 crm-mb-3">
              <input
                className="input crm-flex-grow-1"
                type="email"
                placeholder="Enter a BCC address"
                value={bccDraft}
                onChange={(e) => setBccDraft(e.target.value)}
              />
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                disabled={!bccDraft.includes('@')}
                onClick={() => {
                  const v = bccDraft.trim().toLowerCase();
                  if (!EMAIL_RE.test(v) || bccWorking.includes(v)) {
                    if (!bccWorking.includes(v)) {
                      toast('Enter a valid email address.', 'danger');
                    }
                    return;
                  }
                  setBccWorking([...bccWorking, v]);
                  setBccDraft('');
                }}
              >
                Add
              </button>
            </div>
            {bccWorking.length > 0 ? (
              <div>
                <p className="crm-fs-7 crm-fw-bold crm-text-dark crm-mb-2">BCC Addresses:</p>
                <div className="crm-d-flex crm-flex-column crm-gap-2">
                  {bccWorking.map((addr) => (
                    <div key={addr} className="crm-d-flex crm-align-items-center crm-gap-2">
                      <span className="crm-fs-7 crm-text-dark">{addr}</span>
                      <button
                        type="button"
                        className="icon-btn crm-rounded-circle h-32 w-32"
                        aria-label={`Delete BCC ${addr}`}
                        onClick={() => setBccWorking(bccWorking.filter((a) => a !== addr))}
                      >
                        <CrmIcon name="trash" className="iconSize-16" />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            ) : null}
          </div>
          <div className="set-modal__foot">
            <button type="submit" className="btn-crm btn-crm--primary">
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setBccOpen(false)}
            >
              Cancel
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--ghost crm-text-dark crm-fw-semibold"
              onClick={() => setBccWorking([])}
            >
              Reset
            </button>
          </div>
        </form>
      </SetDialog>

      {/* Actions › Remove connected inbox */}
      <SetDialog
        open={removeInboxOpen}
        onClose={() => setRemoveInboxOpen(false)}
        labelledBy="email-remove-title"
        className="email-action-dialog email-remove-dialog"
      >
        <div>
          <DialogHead
            id="email-remove-title"
            title="Do you really want to remove this connected inbox?"
            onClose={() => setRemoveInboxOpen(false)}
          />
          <div className="set-modal__body">
            <p className="crm-m-0">
              By removing this connection, you&apos;re taking away CRM&apos;s access to your inbox.
              Are you sure you want to remove{' '}
              <strong>{mailbox?.emailAddress ?? 'this inbox'}</strong>?
            </p>
          </div>
          <div className="set-modal__foot email-action-foot">
            <button
              type="button"
              className="btn-crm btn-crm--danger"
              onClick={() => {
                setRemoveInboxOpen(false);
                onDisconnect();
              }}
            >
              Yes, remove inbox
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setRemoveInboxOpen(false)}
            >
              Cancel
            </button>
          </div>
        </div>
      </SetDialog>

      {/* Actions › Disable connected inbox */}
      <SetDialog
        open={disableInboxOpen}
        onClose={() => setDisableInboxOpen(false)}
        labelledBy="email-disable-title"
        className="email-action-dialog email-disable-dialog"
      >
        <div>
          <DialogHead
            id="email-disable-title"
            title="Do you really want to disable this connected inbox?"
            onClose={() => setDisableInboxOpen(false)}
          />
          <div className="set-modal__body">
            <p className="crm-m-0">
              Disabling a connected inbox may affect your work in CRM in a few ways:
            </p>
            <ul className="email-action-list">
              <li>Emailing from CRM will be disabled</li>
              <li>Replies to existing conversations will stop logging to CRM</li>
              <li>Some CRM tools in Gmail or Outlook will not be available</li>
            </ul>
          </div>
          <div className="set-modal__foot email-action-foot">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={confirmDisableInbox}
            >
              Yes, disable it
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDisableInboxOpen(false)}
            >
              Cancel
            </button>
          </div>
        </div>
      </SetDialog>

      {/* Actions › Edit default signature */}
      <SetDialog
        open={signatureDefaultOpen}
        onClose={() => setSignatureDefaultOpen(false)}
        labelledBy="email-signature-title"
        className="email-action-dialog email-signature-dialog"
      >
        <div>
          <DialogHead
            id="email-signature-title"
            title={
              <>
                Set default email signature for{' '}
                <span>{mailbox?.emailAddress ?? 'this account'}</span>
              </>
            }
            onClose={() => setSignatureDefaultOpen(false)}
          />
          <div className="set-modal__body">
            <div className="field">
              <label className="field__label" htmlFor="email-default-signature">
                Which signature should this account use by default?
              </label>
              <p className="field__help">
                You will be able to change this on each email sent from CRM. This will be the
                signature when used in email personalization tokens.
              </p>
              <select
                className="input"
                id="email-default-signature"
                value={signatureDefaultMode}
                onChange={(e) => setSignatureDefaultMode(e.target.value as EmailSignatureMode)}
              >
                <option value="global">Use global default</option>
                <option value="personal">Personal signature</option>
                <option value="none">No signature</option>
              </select>
              <p className="field__help">{EMAIL_SIGNATURE_MODE_HELP[signatureDefaultMode]}</p>
            </div>
          </div>
          <div className="set-modal__foot email-action-foot">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={signatureDefaultBusy || !profile}
              onClick={() => void saveSignatureDefault()}
            >
              {signatureDefaultBusy ? 'Saving…' : 'Set as default'}
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setSignatureDefaultOpen(false)}
            >
              Cancel
            </button>
          </div>
        </div>
      </SetDialog>

      {/* Actions › Install extension */}
      <SetDialog
        open={emailInstallClient !== null}
        onClose={closeEmailInstallDialog}
        labelledBy="email-install-title"
        className="email-action-dialog email-install-dialog"
      >
        <div>
          <DialogHead
            id="email-install-title"
            title={
              emailInstallClient === 'outlook'
                ? 'Download CRM’s Outlook add-in'
                : 'Download CRM’s Sales extension'
            }
            onClose={closeEmailInstallDialog}
          />
          <div className="set-modal__body">
            <div className="email-install-brand">
              {emailInstallClient === 'gmail' ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src="/crm/assets/img/gmail.svg" alt="Gmail" />
              ) : null}
              <strong>
                {emailInstallClient === 'outlook'
                  ? 'Microsoft Outlook add-in for CRM'
                  : 'Google Chrome extension for Gmail'}
              </strong>
            </div>
            <ul className="email-action-list email-install-benefits">
              <li>Get alerts when a lead opens your emails</li>
              <li>Your emails will be logged automatically in CRM</li>
              <li>Use your email templates directly in your inbox</li>
            </ul>
          </div>
          <div className="set-modal__foot email-install-foot">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={downloadEmailInstall}
            >
              Download <CrmIcon name="external" className="iconSize-14" />
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={openEmailClientChooser}
            >
              I use another email client
            </button>
          </div>
        </div>
      </SetDialog>

      <SetDialog
        open={emailClientChooserOpen}
        onClose={() => setEmailClientChooserOpen(false)}
        labelledBy="email-client-title"
        className="email-action-dialog email-client-dialog"
      >
        <div>
          <DialogHead
            id="email-client-title"
            title="Choose your email client"
            onClose={() => setEmailClientChooserOpen(false)}
          />
          <div className="set-modal__body">
            <div className="email-client-options">
              <button
                type="button"
                className="email-client-option"
                onClick={() => chooseEmailClient('gmail')}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src="/crm/assets/img/gmail.svg" alt="" />
                <strong>Gmail</strong>
              </button>
              <button
                type="button"
                className="email-client-option"
                onClick={() => chooseEmailClient('outlook')}
              >
                <span className="email-client-outlook" aria-hidden="true">
                  <svg viewBox="0 0 48 48">
                    <path fill="#1674d1" d="M4 12 26 5v38L4 36z" />
                    <path fill="#25a7e8" d="M26 12h17v24H26z" />
                    <path fill="#0b5cad" d="M26 12 43 8v8H26z" />
                    <path fill="#fff" d="M11 18h9v13h-9z" />
                  </svg>
                </span>
                <strong>Outlook</strong>
              </button>
              <button
                type="button"
                className="email-client-option"
                onClick={() => chooseEmailClient('other')}
              >
                <span className="email-client-other" aria-hidden="true">
                  <svg viewBox="0 0 48 48">
                    <path d="M5 16 24 5l19 11v23H5zM5 16l19 15 19-15" />
                  </svg>
                </span>
                <strong>Other</strong>
              </button>
            </div>
          </div>
        </div>
      </SetDialog>

      {/* Outlook add-in install follow-up */}
      <SetDialog
        open={outlookAddinOpen}
        onClose={() => setOutlookAddinOpen(false)}
        labelledBy="outlook-addin-title"
      >
        <div>
          <DialogHead
            id="outlook-addin-title"
            title="Finish your add-in installation"
            onClose={() => setOutlookAddinOpen(false)}
          />
          <div className="set-modal__body">
            <p className="crm-m-0 crm-fs-7 crm-text-dark crm-lh-base">
              Download and run the installer file in the bottom left corner before checking if
              installation was successful.
            </p>
          </div>
          <div className="set-modal__foot set-modal__foot--danger-confirm">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={outlookAddinChecking}
              onClick={checkOutlookAddinInstalled}
            >
              {outlookAddinChecking ? 'Checking…' : 'Check if installed'}
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setOutlookAddinOpen(false)}
            >
              Close
            </button>
          </div>
        </div>
      </SetDialog>

      {/* Blocked IPs drawer */}
      <SetDialog
        open={ipsOpen}
        onClose={() => setIpsOpen(false)}
        drawer
        labelledBy="blocked-ips-title"
      >
        <form
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            void (async () => {
              const msg = await saveIps();
              if (msg === false) return;
              toast(msg, 'success');
              setIpsOpen(false);
            })();
          }}
        >
          <DialogHead
            id="blocked-ips-title"
            title="Blocked IP Addresses"
            onClose={() => setIpsOpen(false)}
          />
          <div className="set-modal__body">
            <p className="crm-m-0 crm-fs-7 crm-text-dark crm-lh-base crm-mb-3">
              Don&apos;t track email opens or clicks from specific IP addresses.
            </p>
            <div className="crm-d-flex crm-gap-2 crm-mb-3">
              <input
                className="input crm-flex-grow-1"
                type="text"
                placeholder="Enter an IP address (e.g. 192.0.2.10)"
                value={ipDraft}
                onChange={(e) => setIpDraft(e.target.value)}
              />
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                disabled={!ipDraft.trim()}
                onClick={() => {
                  const v = ipDraft.trim();
                  if (!v || ipsWorking.includes(v)) return;
                  if (!isIpAddress(v)) {
                    toast('Enter a valid IP address, for example 192.0.2.10.', 'danger');
                    return;
                  }
                  setIpsWorking([...ipsWorking, v]);
                  setIpDraft('');
                }}
              >
                Add
              </button>
            </div>
            <div>
              <p className="crm-fs-7 crm-text-dark crm-m-0">
                <strong>Blocked IPs:</strong> {ipsWorking.length === 0 ? 'none' : null}
              </p>
              {ipsWorking.length > 0 ? (
                <div className="crm-d-flex crm-flex-column crm-gap-2 crm-mt-2">
                  {ipsWorking.map((ip) => (
                    <div key={ip} className="crm-d-flex crm-align-items-center crm-gap-2">
                      <span className="crm-fs-7 crm-text-dark">{ip}</span>
                      <button
                        type="button"
                        className="icon-btn crm-rounded-circle h-32 w-32"
                        aria-label={`Remove IP ${ip}`}
                        onClick={() => setIpsWorking(ipsWorking.filter((x) => x !== ip))}
                      >
                        <CrmIcon name="trash" className="iconSize-16" />
                      </button>
                    </div>
                  ))}
                </div>
              ) : null}
            </div>
          </div>
          <div className="set-modal__foot">
            <button type="submit" className="btn-crm btn-crm--primary">
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setIpsOpen(false)}
            >
              Cancel
            </button>
          </div>
        </form>
      </SetDialog>
      {confirmDialog}
    </>
  );
}
