'use client';

import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { htmlIsEmpty } from '@/components/crm/ComposeRichText';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { getContactEmails } from '@/features/contacts/api.client';
import type { ContactEmailThread } from '@/features/contacts/types';
import { listBookingPages } from '@/features/meetings/api.client';
import { bookingUrl } from '@/features/meetings/scheduler';
import { useOwners } from '@/features/owners/useOwners';
import { listPicklist, type PicklistOption } from '@/features/picklists/api.client';
import { listQuotes } from '@/features/quotes/api.client';
import { getProfile } from '@/features/settings/api.client';
import { applySnippet, listSnippets } from '@/features/snippets/api.client';
import { readySnippet } from '@/features/snippets/model';
import { createTask } from '@/features/tasks/api.client';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { needsReconnect } from '@/lib/utils/connection';
import {
  addComment,
  attachmentProblem,
  bulkUpdateThreads,
  cancelScheduledEmail,
  connectGmail,
  deleteAttachment,
  findContactByEmail,
  findThreadOfMessage,
  getMyAvailability,
  getMyMailbox,
  getThread,
  getThreadCounts,
  listComments,
  listEmailTemplates,
  listSharedInboxes,
  listThreadTickets,
  listThreads,
  markThreads,
  nextOpenTask,
  openStageIds,
  previewEmailTemplate,
  replyToThread,
  searchContacts,
  sendEmail,
  setMyAvailability,
  updateThread,
  uploadAttachment,
  type Availability,
} from '../api.client';
import {
  linkHtml,
  mergeConversations,
  otherConversations,
  sendableQuotes,
  withChange,
} from '../compose';
import { defaultReplyTo, mentionedIds, type Mentionable } from '../conversation';
import {
  CHANNELS,
  dayBoundary,
  forwardedHtml,
  STATUS_LABELS,
  timeAgo,
  widthClasses,
} from '../design';
import {
  chatReplyNote,
  displayName,
  htmlToText,
  isStandInAddress,
  messageTime,
  newIdempotencyKey,
} from '../format';
import { savedSidePanel, saveSidePanel, sidePanelOpen } from '../panels';
import { draftOwner, readDraft, writeDraft } from '../drafts';
import type {
  ContactDetail,
  EmailTemplate,
  EmailTemplatePreview,
  EmailUpload,
  InboxChannel,
  InboxComment,
  InboxMessage,
  InboxThread,
  InboxThreadBox,
  InboxThreadCounts,
  InboxThreadDetail,
  InboxThreadStatus,
  InboxTicketCard,
  MyMailbox,
  RecipientWarning,
  SharedInbox,
  SharedInboxList,
  TaskSummary,
  ThreadChange,
} from '../types';
import { useNewMailAlerts } from '../useNewMailAlerts';
import { presenceText, useThreadPresence } from '../useThreadPresence';
import { ComposeWindow, type ComposeContext, type NewEmail } from './ComposeWindow';
import { InboxCallDrawer } from './InboxCallDrawer';
import { InboxEditor, InboxTools, type InboxEditorHandle, type InsertItem } from './InboxEditor';
import { InboxList } from './InboxList';
import { InboxMessages } from './InboxMessages';
import { InboxRail, type InboxViewChoice } from './InboxRail';
import { InboxSidebar } from './InboxSidebar';
import { InboxTicketDrawer } from './InboxTicketDrawer';
import { MentionTextarea } from './MentionTextarea';
import { RecipientRows, type RecipientChoice, type Recipients } from './RecipientRows';
import {
  DEFAULT_SEND_CHOICES,
  SchedulePopover,
  SendOptions,
  sendFields,
  type RecordChoice,
  type SendChoices,
} from './SendOptions';
import { ASSIGN_NEEDS_PERMISSION, ASSIGN_PERSONAL, OwnerPicker, ThreadOwner } from './ThreadOwner';
import { IxIcon, IxPopover, Tri, ixInitials } from './ix';

/**
 * Inbox (design: design.admedia.com/crm/inbox.php, styles in inbox-hs.css), on the CRM API:
 * the left menu, the user's Gmail conversations linked to CRM records (`folder=crm`), the
 * conversation with its reply box, and the CRM contact of the conversation. HUB-366.
 *
 * The panes fold as the inbox gets narrower, as the design's script does. What the design shows
 * but the API cannot do yet is drawn turned off ("Coming soon").
 */

/** What the list shows: a view of the left menu, or a search, in one inbox. */
interface ListFilter extends InboxViewChoice {
  /** A team inbox's id; absent: my own email. */
  inbox?: string;
  unread: boolean;
  oldestFirst: boolean;
  /** The design's search mode: conversations matching what is typed and picked below it. */
  searching: boolean;
  q: string;
  searchStatus: InboxThreadStatus | '';
  searchChannel: InboxChannel | '';
  /** Days ("2026-11-20"): the last email on or after `from`, on or before `to`. */
  from: string;
  to: string;
}

const NO_SEARCH = {
  searching: false,
  q: '',
  searchStatus: '',
  searchChannel: '',
  from: '',
  to: '',
} as const;

const FIRST_LIST: ListFilter = {
  view: 'all',
  status: 'open',
  box: 'inbox',
  sent: false,
  channel: undefined,
  unread: false,
  oldestFirst: false,
  ...NO_SEARCH,
};

const listParams = (f: ListFilter) => {
  const sort = f.oldestFirst ? ('oldest' as const) : undefined;
  if (f.searching) {
    return {
      inbox: f.inbox,
      folder: 'crm' as const,
      q: f.q.trim() || undefined,
      status: f.searchStatus || undefined,
      channel: f.searchChannel || undefined,
      lastMessageFrom: dayBoundary(f.from),
      lastMessageBefore: dayBoundary(f.to, true),
      sort,
    };
  }
  // Spam, Trash and Sent hold open and closed conversations alike
  const anyStatus = f.box !== 'inbox' || f.sent;
  return {
    inbox: f.inbox,
    folder: 'crm' as const,
    status: anyStatus ? undefined : f.status,
    box: f.box === 'inbox' ? undefined : f.box,
    channel: f.channel,
    sent: f.sent ? ('true' as const) : undefined,
    ...(f.view === 'unassigned' ? { assignee: 'none' as const } : {}),
    ...(f.view === 'mine' ? { assignee: 'me' as const } : {}),
    unread: f.unread ? ('true' as const) : undefined,
    sort,
  };
};

/** A search with nothing typed or picked lists nothing. */
const listsNothing = (f: ListFilter) =>
  f.searching && !f.q.trim() && !f.searchStatus && !f.searchChannel && !f.from && !f.to;

/** Whether a conversation still belongs in the list after it changed. */
const inList = (t: InboxThread, f: ListFilter, meId: string) => {
  if (f.searching) return true;
  if (t.box !== f.box) return false;
  const status =
    f.box !== 'inbox' || f.sent
      ? true
      : f.status === 'open'
        ? t.status !== 'closed'
        : t.status === f.status;
  return (
    status &&
    (!f.channel || t.channel === f.channel) &&
    (f.view !== 'unassigned' || (!t.assignee && !t.assigneeTeam)) &&
    (f.view !== 'mine' || t.assignee?.id === meId)
  );
};

const noRecipients = (): Recipients => ({
  to: [],
  cc: [],
  bcc: [],
  showCc: false,
  showBcc: false,
});

const PAGE_SIZE = 30;
/** A live chat is being waited on: the open one and the list are checked this often. */
const CHAT_REFRESH_MS = 3000;
const CHAT_LIST_REFRESH_MS = 5000;
const POLL_MS = 3000;
const POLL_TRIES = 10;
/** The API checks Gmail for new mail every 30 s (GMAIL_INCREMENTAL_SYNC_MS); the list follows. */
const REFRESH_MS = 30_000;
const FINAL_SEND_STATUSES = new Set(['sent', 'failed', 'uncertain']);
const SOON = 'Coming soon';
/** POST /inbox/threads/mark takes this many ids at a time. */
const MARK_LIMIT = 100;
const READ_ONLY_TICKET = 'Read-only users can’t create tickets';
/** What the "Insert" menu offers in a chat: text and links, no email templates or signature. */
const CHAT_INSERTS = new Set(['snippets', 'meetings', 'quotes']);
const FROM_TITLE = 'A reply goes from the address the conversation is in';
/** How long after the last keystroke I still count as typing (team conversations). */
const TYPING_MS = 5000;

/** A team inbox that can hold conversations: from Gmail, or from a channel. */
const canRead = (i: SharedInbox) => i.isOpen;
/** One whose Gmail connection works: new email arrives and it can send. */
const canEmail = (i: SharedInbox) =>
  !!i.emailAddress && i.status !== 'disconnected' && !needsReconnect({ ...i, connected: true });
/** One whose Gmail was connected and has stopped working. */
const emailBroken = (i: SharedInbox) => !!i.emailAddress && !canEmail(i);

/** Suppressed recipients still get a 1:1 email (it is only queued yet): tell the sender. */
const warningText = (w: RecipientWarning[]) =>
  `Queued. Note: ${w.map((x) => `${x.email} ${x.status === 'bounced' ? 'bounced before' : 'unsubscribed earlier'}`).join(', ')}.`;

const contactName = (c: ContactDetail) =>
  [c.firstName, c.lastName].filter(Boolean).join(' ') || c.email || 'Contact';

const todayIso = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

const taskDue = (t: TaskSummary) => {
  if (t.dueAt) return messageTime(t.dueAt);
  if (t.dueDate) {
    const [y, m, d] = t.dueDate.split('-').map(Number);
    return new Date(y ?? 0, (m ?? 1) - 1, d ?? 1).toLocaleDateString(undefined, {
      day: 'numeric',
      month: 'short',
    });
  }
  return '';
};

/** "Re: " / "Fwd: " in front of the subject, unless it is there: what the API will send. */
const replySubject = (subject: string, forwarding: boolean) => {
  const [prefix, already] = forwarding ? ['Fwd:', /^(fwd?|fw):/i] : ['Re:', /^re:/i];
  return already.test(subject) ? subject : `${prefix} ${subject}`;
};

/** Contacts whose name or address matches what is typed in a recipient box. */
const suggestContacts = async (query: string): Promise<RecipientChoice[]> =>
  (await searchContacts(query)).contacts.flatMap((c) =>
    c.email
      ? [
          {
            email: c.email,
            label: [c.displayName, c.email, c.companyName].filter(Boolean).join(' · '),
          },
        ]
      : [],
  );

/** Picked template, with its preview filled in for the conversation's contact. */
interface ChosenTemplate {
  template: EmailTemplate;
  preview: EmailTemplatePreview;
  contactId: string;
  dealId?: string;
}

/** A forward in progress, with the forwarded email's files that go with it. */
interface Forwarding {
  files: InboxMessage['attachments'];
}

export function InboxView() {
  const toast = useToast();
  const me = useCurrentUser();
  const { owners } = useOwners(true, false);

  const [mailbox, setMailbox] = useState<MyMailbox | null>(null);
  const [shared, setShared] = useState<SharedInboxList | null>(null);
  const [typing, setTyping] = useState(false);
  const [threads, setThreads] = useState<InboxThread[]>([]);
  const [cursor, setCursor] = useState<string | null>(null);
  const [listLoading, setListLoading] = useState(true);
  const [list, setList] = useState<ListFilter>(FIRST_LIST);
  const [counts, setCounts] = useState<InboxThreadCounts | null>(null);
  const [currentId, setCurrentId] = useState<string | null>(null);
  const [thread, setThread] = useState<InboxThreadDetail | null>(null);
  const [threadLoading, setThreadLoading] = useState(false);

  /* panes */
  const [rootEl, setRootEl] = useState<HTMLDivElement | null>(null);
  const [widths, setWidths] = useState<string[]>([]);
  const [railOn, setRailOn] = useState(true);
  const [railPeek, setRailPeek] = useState(false);
  /** The user's own choice for the contact panel; null: none yet. */
  const [sideChoice, setSideChoice] = useState<boolean | null>(null);
  const [sidePeek, setSidePeek] = useState(false);
  /** Phones show the list or the conversation: true once the user opened one. */
  const [reading, setReading] = useState(false);

  /* selecting conversations */
  const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
  const [bulkBusy, setBulkBusy] = useState(false);

  const [comments, setComments] = useState<InboxComment[]>([]);
  const [tickets, setTickets] = useState<InboxTicketCard[]>([]);
  /** The design's composer tabs: an email reply, or an internal comment. */
  const [mode, setMode] = useState<'email' | 'comment'>('email');
  const [recipients, setRecipients] = useState<Recipients>(noRecipients);
  const recipientsFor = useRef<string | null>(null);
  const [commentText, setCommentText] = useState('');
  const [picked, setPicked] = useState<Mentionable[]>([]);
  const [commenting, setCommenting] = useState(false);
  const [ticketOpen, setTicketOpen] = useState(false);

  /** The reply as the editor's HTML. */
  const [reply, setReply] = useState('');
  /** A new value gives the reply editor a fresh start (its content is not React's). */
  const [editorVersion, setEditorVersion] = useState(0);
  const [forwarding, setForwarding] = useState<Forwarding | null>(null);
  const [replyKey, setReplyKey] = useState(newIdempotencyKey);
  const [sending, setSending] = useState(false);
  const [choices, setChoices] = useState<SendChoices>(DEFAULT_SEND_CHOICES);
  const [availability, setAvailability] = useState<Availability | null>(null);
  const [uploads, setUploads] = useState<EmailUpload[]>([]);
  const [uploading, setUploading] = useState(false);
  const [chosen, setChosen] = useState<ChosenTemplate | null>(null);
  const [insertOpenAt, setInsertOpenAt] = useState<string | null>(null);
  const [signature, setSignature] = useState<string | null>(null);
  const [useSignature, setUseSignature] = useState(true);
  const [showFields, setShowFields] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [composerHeight, setComposerHeight] = useState<number | null>(null);
  const [menu, setMenu] = useState<'more' | 'channel' | 'send' | 'schedule' | null>(null);

  const [contact, setContact] = useState<ContactDetail | null>(null);
  const [contactLoading, setContactLoading] = useState(false);
  const [nextTask, setNextTask] = useState<TaskSummary | null>(null);
  const [past, setPast] = useState<{ data: ContactEmailThread[]; more: boolean } | null>(null);
  const [stages, setStages] = useState<PicklistOption[]>([]);
  const [leadStatuses, setLeadStatuses] = useState<PicklistOption[]>([]);
  const [taskTypes, setTaskTypes] = useState<PicklistOption[]>([]);
  const [openStages, setOpenStages] = useState<Set<string> | null>(null);

  const [composeOpen, setComposeOpen] = useState(false);
  const [callOpen, setCallOpen] = useState(false);
  const [taskOpen, setTaskOpen] = useState(false);

  const messagesRef = useRef<HTMLDivElement>(null);
  const editorRef = useRef<InboxEditorHandle>(null);
  const composerRef = useRef<HTMLFormElement>(null);
  const imageRef = useRef<HTMLInputElement>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const taskTitleRef = useRef<HTMLInputElement>(null);
  const moreRef = useRef<HTMLButtonElement>(null);
  const channelRef = useRef<HTMLButtonElement>(null);
  const sendMoreRef = useRef<HTMLButtonElement>(null);
  const templatesRef = useRef<EmailTemplate[]>([]);
  const typingTimer = useRef<number | undefined>(undefined);
  const scrollPending = useRef(false);
  const currentIdRef = useRef<string | null>(null);
  const listRequest = useRef(0);
  const searchTimer = useRef<number | undefined>(undefined);
  const pollTimers = useRef(new Set<number>());
  const listRef = useRef<ListFilter>(FIRST_LIST);
  const draftsOf = draftOwner(me.user.id, me.business.id);
  const [bulkAssign, setBulkAssign] = useState(false);
  const bulkAssignRef = useRef<HTMLButtonElement>(null);
  const threadsRef = useRef<InboxThread[]>([]);
  const listLoadingRef = useRef(true);

  const linkedId = useSearchParams().get('conversation');
  /** The linked conversation already opened (the first one by the first load). */
  const handledLink = useRef(linkedId);

  const team = shared?.data.find((i) => i.id === list.inbox) ?? null;
  const myUsable = !!mailbox?.connected && !needsReconnect(mailbox);
  const presence = useThreadPresence(list.inbox && thread ? thread.id : null, typing);
  const noteTyping = () => {
    setTyping(true);
    window.clearTimeout(typingTimer.current);
    typingTimer.current = window.setTimeout(() => setTyping(false), TYPING_MS);
  };

  const current = threads.find((t) => t.id === currentId) ?? null;
  const subject = thread?.subject ?? current?.subject ?? '(no subject)';
  const otherParty = thread?.participants[0] ?? current?.participants[0] ?? null;
  const uploadedBytes = uploads.reduce((n, u) => n + u.sizeBytes, 0);
  const closeMenu = useCallback(() => setMenu(null), []);
  const closeInsert = useCallback(() => setInsertOpenAt(null), []);

  useEffect(() => {}, [uploads]);
  useEffect(() => {
    listRef.current = list;
  }, [list]);
  useEffect(() => {
    threadsRef.current = threads;
  }, [threads]);
  useEffect(() => {
    listLoadingRef.current = listLoading;
  }, [listLoading]);

  useEffect(() => setSideChoice(savedSidePanel()), []);

  /* the design's width steps, from the inbox's own width */
  useEffect(() => {
    if (!rootEl) return;
    const apply = () => setWidths(widthClasses(rootEl.clientWidth));
    apply();
    if (typeof ResizeObserver === 'undefined') return;
    const observer = new ResizeObserver(apply);
    observer.observe(rootEl);
    return () => observer.disconnect();
  }, [rootEl]);

  /* ------------------------------------------------------------ loading */

  /** The numbers next to the views; quiet when they fail (the list still works). */
  const loadCounts = useCallback(() => {
    const inbox = listRef.current.inbox;
    getThreadCounts('crm', inbox).then(
      // not when another inbox was opened meanwhile
      (next) => listRef.current.inbox === inbox && setCounts(next),
      () => {},
    );
  }, []);

  const loadThreads = useCallback(
    async (next: ListFilter, after?: string) => {
      const request = ++listRequest.current;
      if (listsNothing(next)) {
        setThreads([]);
        setCursor(null);
        setListLoading(false);
        return [];
      }
      setListLoading(true);
      if (!after) loadCounts();
      try {
        const page = await listThreads({ ...listParams(next), limit: PAGE_SIZE, cursor: after });
        if (request !== listRequest.current) return []; // a newer list request won
        setThreads((list) => (after ? [...list, ...page.data] : page.data));
        setCursor(page.nextCursor);
        return page.data;
      } catch (err) {
        if (request !== listRequest.current) return [];
        if (isApiError(err) && err.isConflict) {
          // 409: not connected. For a team inbox the notice above the inbox says so.
          if (!next.inbox) setMailbox((m) => (m ? { ...m, connected: false } : m));
          setThreads([]);
          setCursor(null);
        } else {
          toast(errorText(err), 'danger');
        }
        return [];
      } finally {
        if (request === listRequest.current) setListLoading(false);
      }
    },
    [toast, loadCounts],
  );

  /** Loads the open conversation; `markRead` only when the user opened it. */
  const loadThread = useCallback(
    async (id: string, { markRead = false, quiet = false } = {}) => {
      if (!quiet) setThreadLoading(true);
      try {
        // Internal comments are shown in the timeline; a failure there leaves the emails shown.
        const [detail, notes] = await Promise.all([
          getThread(id),
          listComments(id).catch(() => null),
        ]);
        if (currentIdRef.current !== id) return null;
        setThread(detail);
        if (notes) setComments(notes);
        if (!quiet) scrollPending.current = true;
        if (markRead && detail.isUnread) {
          await markThreads([id], false);
          setThreads((list) => list.map((t) => (t.id === id ? { ...t, isUnread: false } : t)));
        }
        return detail;
      } catch (err) {
        if (!quiet) toast(errorText(err), 'danger');
        return null;
      } finally {
        if (!quiet) setThreadLoading(false);
      }
    },
    [toast],
  );

  const selectThread = useCallback(
    (id: string, markRead: boolean) => {
      currentIdRef.current = id;
      setCurrentId(id);
      setThread(null);
      setComments([]);
      setTickets([]);
      // what was being written in this conversation comes back
      const draft = readDraft(draftsOf, id);
      setMode(draft?.mode ?? 'email');
      setRecipients(draft?.recipients ?? noRecipients());
      // a draft keeps its own recipients instead of the default ones
      recipientsFor.current = draft ? id : null;
      setCommentText(draft?.commentText ?? '');
      setPicked(draft?.picked ?? []);
      setReply(draft?.reply ?? '');
      setForwarding(draft?.forwarding ?? null);
      setUploads(draft?.uploads ?? []);
      setEditorVersion((v) => v + 1);
      setChosen(null);
      setChoices(DEFAULT_SEND_CHOICES);
      setInsertOpenAt(null);
      setMenu(null);
      setTyping(false);
      setReplyKey(newIdempotencyKey());
      void loadThread(id, { markRead });
    },
    [loadThread, draftsOf],
  );

  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        // a notification links to one conversation, which may be in a team inbox
        const wanted = handledLink.current;
        const [box, teams, linked] = await Promise.all([
          getMyMailbox(),
          listSharedInboxes().catch(() => null),
          wanted ? getThread(wanted).catch(() => null) : null,
        ]);
        if (!alive) return;
        if (wanted && !linked) toast('That conversation is not available to you', 'danger');
        const mine = box.connected && !needsReconnect(box);
        // without my own Gmail, a team inbox still has email to show
        const inbox = linked
          ? (linked.inboxId ?? undefined)
          : mine
            ? undefined
            : teams?.data.find(canRead)?.id;
        const next = { ...listRef.current, inbox };
        listRef.current = next;
        setList(next);
        setShared(teams);
        setMailbox(box);
        if (!inbox && !mine) {
          setListLoading(false);
          return;
        }
        const first = await loadThreads(next);
        if (!alive) return;
        if (linked) {
          setReading(true);
          selectThread(linked.id, true);
        } else if (first[0]) {
          // shown, but not marked read: that is synced to Gmail
          selectThread(first[0].id, false);
        }
      } catch (err) {
        if (alive) {
          setListLoading(false);
          setMailbox({
            connected: false,
            emailAddress: null,
            status: 'error',
            lastSyncedAt: null,
            lastError: errorText(err),
          });
          toast(errorText(err), 'danger');
        }
      }
    })();
    listPicklist('contact', 'lifecycleStage').then(setStages, () => {});
    listPicklist('contact', 'leadStatus').then(setLeadStatuses, () => {});
    listPicklist('activity', 'taskType').then(setTaskTypes, () => {});
    openStageIds().then(setOpenStages, () => setOpenStages(null));
    getProfile().then(
      (p) => setSignature(p.emailSignature),
      () => {},
    );
    getMyAvailability().then(
      (mine) => alive && setAvailability(mine.availability),
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [loadThreads, selectThread, toast]);

  /* stop polling when leaving the page (unsent attachments stay with their draft) */
  useEffect(
    () => () => {
      const polls = pollTimers.current;
      polls.forEach((t) => window.clearTimeout(t));
      window.clearTimeout(searchTimer.current);
      window.clearTimeout(typingTimer.current);
    },
    [],
  );

  /**
   * Quietly picks up email the sync brought in since the list was loaded: the first page again,
   * without a spinner, and without a toast when it fails (the next refresh tries again).
   * Skipped while another list load runs, and dropped if one starts meanwhile (that one wins).
   */
  const refreshThreads = useCallback(async () => {
    if (listLoadingRef.current || listsNothing(listRef.current)) return;
    const request = listRequest.current;
    let page: Awaited<ReturnType<typeof listThreads>>;
    try {
      page = await listThreads({ ...listParams(listRef.current), limit: PAGE_SIZE });
    } catch {
      return;
    }
    if (request !== listRequest.current || listLoadingRef.current) return;
    loadCounts();

    const before = threadsRef.current;
    if (before.length > PAGE_SIZE) {
      // More pages are loaded: keep them and where "load more" goes on from; a conversation
      // with new mail moves up to its place in the first page.
      const fresh = new Set(page.data.map((t) => t.id));
      setThreads(
        [...page.data, ...before.filter((t) => !fresh.has(t.id))].sort((a, b) =>
          b.lastMessageAt.localeCompare(a.lastMessageAt),
        ),
      );
    } else {
      setThreads(page.data);
      setCursor(page.nextCursor);
    }

    // New messages in the open conversation: show them, without marking it read.
    const id = currentIdRef.current;
    const was = before.find((t) => t.id === id);
    const now = page.data.find((t) => t.id === id);
    if (id && was && now && now.lastMessageAt !== was.lastMessageAt) {
      void loadThread(id, { quiet: true });
    }
  }, [loadThread, loadCounts]);

  /* refresh every REFRESH_MS while the tab is visible, and at once when it comes back */
  const canRefresh = list.inbox ? !!team && canRead(team) : myUsable;
  const refreshMs = team?.channels.chat.enabled ? CHAT_LIST_REFRESH_MS : REFRESH_MS;
  useEffect(() => {
    if (!canRefresh) return;
    const tick = () => {
      if (document.visibilityState === 'visible') void refreshThreads();
    };
    const timer = window.setInterval(tick, refreshMs);
    document.addEventListener('visibilitychange', tick);
    return () => {
      window.clearInterval(timer);
      document.removeEventListener('visibilitychange', tick);
    };
  }, [canRefresh, refreshThreads, refreshMs]);

  /*
   * An open live chat: what the visitor writes shows within seconds. I have it on screen, so
   * it counts as read (nothing goes to Gmail for a chat).
   */
  const chatId = thread?.channel === 'chat' ? thread.id : null;
  const chatCount = useRef(0);
  useEffect(() => {
    chatCount.current = thread?.messages.length ?? 0;
  }, [thread]);
  useEffect(() => {
    if (!chatId) return;
    const timer = window.setInterval(async () => {
      if (document.visibilityState !== 'visible') return;
      const detail = await getThread(chatId).catch(() => null);
      if (!detail || currentIdRef.current !== chatId) return;
      if (detail.messages.length !== chatCount.current) {
        scrollPending.current = true;
        setThread(detail);
      }
      if (detail.isUnread) {
        await markThreads([chatId], false).catch(() => {});
        setThreads((rows) => rows.map((t) => (t.id === chatId ? { ...t, isUnread: false } : t)));
        loadCounts();
      }
    }, CHAT_REFRESH_MS);
    return () => window.clearInterval(timer);
  }, [chatId, loadCounts]);

  const alerts = useNewMailAlerts(canRefresh, refreshMs, list.inbox);

  /* the CRM contact of the conversation */
  const partyEmail = otherParty && !isStandInAddress(otherParty.email) ? otherParty.email : null;
  useEffect(() => {
    setContact(null);
    setNextTask(null);
    // set both ways: a lookup cut off by a switch to someone without an address never ends itself
    setContactLoading(Boolean(partyEmail));
    if (!partyEmail) return;
    let alive = true;
    findContactByEmail(partyEmail)
      .then(async (c) => {
        if (!alive) return;
        setContact(c);
        if (c) {
          const task = await nextOpenTask(c.id).catch(() => null);
          if (alive) setNextTask(task);
        }
      })
      .catch(() => {})
      .finally(() => {
        if (alive) setContactLoading(false);
      });
    return () => {
      alive = false;
    };
  }, [partyEmail]);

  /* the contact's other conversations (only the user's own email) */
  const contactId = contact?.id ?? null;
  const contactAddress = contact?.email ?? null;
  const teamInbox = list.inbox;
  useEffect(() => {
    setPast(null);
    if (!contactId || (teamInbox && !contactAddress)) return;
    let alive = true;
    // in a team inbox: its conversations with them on every channel; else my own email, both
    // those logged on the contact and those with their address in them.
    // One more than shown: the open conversation is usually among them
    const byAddress = contactAddress
      ? listThreads({ inbox: teamInbox, folder: 'all', q: contactAddress, limit: 6 })
      : null;
    const load: Promise<{ data: ContactEmailThread[]; nextCursor: string | null }> =
      teamInbox && byAddress
        ? byAddress
        : Promise.all([getContactEmails(contactId, { limit: 6 }), byAddress]).then(
            ([logged, found]) => ({
              data: mergeConversations<ContactEmailThread>(logged.data, found?.data ?? []),
              nextCursor: logged.nextCursor ?? found?.nextCursor ?? null,
            }),
          );
    load.then(
      (page) => {
        if (alive) setPast({ data: page.data, more: !!page.nextCursor });
      },
      () => {}, // the section is left out
    );
    return () => {
      alive = false;
    };
  }, [contactId, contactAddress, teamInbox, currentId]);

  useLayoutEffect(() => {
    if (!scrollPending.current || !messagesRef.current) return;
    scrollPending.current = false;
    messagesRef.current.scrollTop = messagesRef.current.scrollHeight;
  }, [thread, comments]);

  /* what is being written is kept as it changes */
  useEffect(() => {
    if (!currentId) return;
    const written = !htmlIsEmpty(reply) || !!commentText.trim() || uploads.length > 0;
    writeDraft(
      draftsOf,
      currentId,
      written ? { reply, commentText, picked, mode, recipients, forwarding, uploads } : null,
    );
  }, [draftsOf, currentId, reply, commentText, picked, mode, recipients, forwarding, uploads]);

  /* the reply's To chips start with whom the reply goes to by default */
  useEffect(() => {
    if (!thread || recipientsFor.current === thread.id) return;
    recipientsFor.current = thread.id;
    setRecipients({ ...noRecipients(), to: defaultReplyTo(thread) });
  }, [thread]);

  /* the sidebar's ticket cards */
  const loadTickets = useCallback(async (id: string) => {
    const cards = await listThreadTickets(id).catch(() => null);
    if (cards && currentIdRef.current === id) setTickets(cards);
  }, []);
  useEffect(() => {
    if (currentId) void loadTickets(currentId);
  }, [currentId, loadTickets]);

  /* ------------------------------------------------------------ actions */

  const openThread = (id: string) => {
    setRailPeek(false);
    setReading(true);
    if (id !== currentId) selectThread(id, true);
    else if (current?.isUnread) void loadThread(id, { markRead: true, quiet: true });
  };

  const applyList = async (change: Partial<ListFilter>) => {
    const next = { ...listRef.current, ...change };
    listRef.current = next;
    setList(next);
    setSelected(new Set());
    return loadThreads(next);
  };

  /** A view of the left menu or the Open / Closed toggle: leaves search. */
  const showView = (change: Partial<ListFilter>) => {
    setRailPeek(false);
    setReading(false);
    window.clearTimeout(searchTimer.current);
    void applyList({ ...change, ...NO_SEARCH });
  };

  /** Opens another inbox on its "All open" view; resolves to its conversations. */
  const openInbox = async (inbox: string | undefined) => {
    window.clearTimeout(searchTimer.current);
    setRailPeek(false);
    setReading(false);
    // nothing of the other inbox stays on screen
    currentIdRef.current = null;
    setCurrentId(null);
    setThread(null);
    setUploads([]);
    setCounts(null);
    setThreads([]);
    setCursor(null);
    return applyList({ ...FIRST_LIST, inbox });
  };

  const switchInbox = async (inbox: string | undefined) => {
    if (inbox === listRef.current.inbox) return;
    const first = await openInbox(inbox);
    if (listRef.current.inbox === inbox && !currentIdRef.current && first[0]) {
      selectThread(first[0].id, false);
    }
  };

  /** A conversation linked to while the inbox is already open (a notification). */
  const openLinked = async (id: string) => {
    const linked = await getThread(id).catch(() => null);
    if (!linked) {
      toast('That conversation is not available to you', 'danger');
      return;
    }
    const inbox = linked.inboxId ?? undefined;
    if (inbox !== listRef.current.inbox) await openInbox(inbox);
    setReading(true);
    selectThread(id, true);
  };
  const openLinkedRef = useRef(openLinked);
  useEffect(() => {
    openLinkedRef.current = openLinked;
  });
  useEffect(() => {
    if (linkedId === handledLink.current) return;
    handledLink.current = linkedId;
    if (linkedId) void openLinkedRef.current(linkedId);
  }, [linkedId]);

  const setSearching = (on: boolean) => {
    window.clearTimeout(searchTimer.current);
    setRailPeek(false);
    setReading(false);
    void applyList({ ...NO_SEARCH, searching: on });
  };

  /** Searches once typing pauses. */
  const onSearchText = (q: string) => {
    const next = { ...listRef.current, q };
    listRef.current = next;
    setList(next);
    setSelected(new Set());
    window.clearTimeout(searchTimer.current);
    searchTimer.current = window.setTimeout(() => void loadThreads(listRef.current), 300);
  };

  /** What the server saved, shown in the open pane and the list. */
  const showThreadState = (id: string, st: Awaited<ReturnType<typeof updateThread>>) => {
    const apply = <T extends InboxThread>(t: T): T => ({
      ...t,
      status: st.status,
      box: st.box,
      closedAt: st.closedAt,
      assignee: st.assignee,
      assigneeTeam: st.assigneeTeam,
      // the response-time target of a closed or moved conversation is over
      sla: st.status === 'closed' || st.box !== 'inbox' ? null : t.sla,
    });
    setThread((d) => (d && d.id === id ? apply(d) : d));
    setThreads((rows) =>
      rows.flatMap((t) => {
        if (t.id !== id) return [t];
        const next = apply(t);
        return inList(next, listRef.current, me.user.id) ? [next] : [];
      }),
    );
    loadCounts();
  };

  /** Changes a conversation and shows the change in the open pane and the list. */
  const changeThreadById = async (id: string, change: ThreadChange) => {
    showThreadState(id, await updateThread(id, change));
  };

  /** Changes are sent one after another, in the order they were made. */
  const changeQueue = useRef<Promise<unknown>>(Promise.resolve());
  const changesWaiting = useRef(0);

  /**
   * Status, folder and owner. The change shows at once and the controls stay usable while the
   * server saves it; if saving fails, what the server has is loaded again. The conversation stays
   * open in the pane (so the change can be undone there); it leaves the list when the list's view
   * no longer includes it.
   */
  const changeThread = async (change: ThreadChange, done: string) => {
    if (!currentId) return;
    const id = currentId;
    const known = [me.user, ...teammates];
    const apply = <T extends InboxThread>(t: T): T =>
      withChange(t, change, known, new Date().toISOString(), team?.teams ?? []);
    setThread((d) => (d && d.id === id ? apply(d) : d));
    changesWaiting.current += 1;
    const saved = changeQueue.current.then(async () => {
      const state = await updateThread(id, change);
      changesWaiting.current -= 1;
      // a later change is still on its way: its own answer will be shown
      if (!changesWaiting.current) showThreadState(id, state);
    });
    changeQueue.current = saved.catch(() => {});
    try {
      await saved;
      toast(done);
    } catch (err) {
      changesWaiting.current -= 1;
      toast(errorText(err), 'danger');
      if (currentIdRef.current === id) void loadThread(id, { quiet: true });
      void loadThreads(listRef.current);
    }
  };

  const moveTo = (box: InboxThreadBox) =>
    changeThread(
      { box },
      box === 'inbox' ? 'Moved to the inbox' : `Moved to ${box === 'spam' ? 'Spam' : 'Trash'}`,
    );

  /* selected conversations */
  const selectedWord = `${selected.size} conversation${selected.size === 1 ? '' : 's'}`;

  /** The same change for every selected conversation, then the list again. */
  const changeSelected = async (change: ThreadChange, done: string) => {
    setBulkBusy(true);
    const ids = [...selected];
    try {
      for (let i = 0; i < ids.length; i += MARK_LIMIT) {
        await bulkUpdateThreads(ids.slice(i, i + MARK_LIMIT), change);
      }
      toast(`${done} ${selectedWord}`);
      // the open conversation may be one of them
      if (currentId && ids.includes(currentId)) void loadThread(currentId, { quiet: true });
      setSelected(new Set());
      await loadThreads(listRef.current);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBulkBusy(false);
    }
  };

  const markSelected = async (unread: boolean) => {
    setBulkBusy(true);
    const ids = [...selected];
    try {
      for (let i = 0; i < ids.length; i += MARK_LIMIT) {
        await markThreads(ids.slice(i, i + MARK_LIMIT), unread);
      }
      setThreads((rows) => rows.map((t) => (selected.has(t.id) ? { ...t, isUnread: unread } : t)));
      toast(`Marked ${selectedWord} as ${unread ? 'unread' : 'read'}`, 'info');
      setSelected(new Set());
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBulkBusy(false);
    }
  };

  const changeAvailability = async (next: Availability) => {
    try {
      setAvailability((await setMyAvailability(next)).availability);
      toast(next === 'away' ? 'You’re set to away' : 'You’re available');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const cancelScheduled = async (m: InboxMessage) => {
    if (!currentId) return;
    const id = currentId;
    try {
      await cancelScheduledEmail(m.id);
      toast('Scheduled email cancelled');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
    // gone with it: a conversation that held nothing else
    const detail = await loadThread(id, { quiet: true });
    if (!detail && currentIdRef.current === id) setThread(null);
    await loadThreads(listRef.current);
  };

  /* composer: internal comment */
  const onComment = async () => {
    if (!currentId || commenting) return;
    const body = commentText.trim();
    if (!body) return;
    setCommenting(true);
    try {
      const c = await addComment(currentId, {
        body,
        mentionUserIds: mentionedIds(body, picked),
      });
      if (currentIdRef.current === c.threadId) {
        setComments((rows) => [...rows, c]);
        scrollPending.current = true;
      }
      if (currentIdRef.current === c.threadId) {
        setCommentText('');
        setPicked([]);
      } else {
        const kept = readDraft(draftsOf, c.threadId);
        if (kept) {
          const rest = { ...kept, commentText: '', picked: [] };
          writeDraft(
            draftsOf,
            c.threadId,
            htmlIsEmpty(rest.reply) && !rest.uploads.length ? null : rest,
          );
        }
      }
      const named = c.mentions.map((m) => m.name);
      toast(
        named.length
          ? `Comment added. ${named.join(', ')} ${named.length > 1 ? 'were' : 'was'} notified`
          : 'Comment added',
      );
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setCommenting(false);
    }
  };

  const onConnect = async () => {
    try {
      const { authUrl } = await connectGmail({ consent: 'all' });
      window.location.assign(authUrl);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const setUnread = async (unread: boolean) => {
    if (!currentId) return;
    try {
      await markThreads([currentId], unread);
      setThreads((list) => list.map((t) => (t.id === currentId ? { ...t, isUnread: unread } : t)));
      toast(unread ? 'Marked as unread' : 'Marked as read', 'info');
      loadCounts();
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  /* composer: reply to or forward one email of the conversation */
  const clearDraft = () => {
    setReply('');
    setEditorVersion((v) => v + 1);
  };

  /** Leaving a forward drops the quoted email with it. */
  const backToReply = () => {
    if (!thread) return;
    setForwarding(null);
    clearDraft();
    setRecipients({ ...noRecipients(), to: defaultReplyTo(thread) });
  };

  const replyToMessage = (m: InboxMessage) => {
    if (forwarding) {
      setForwarding(null);
      clearDraft();
    }
    setMode('email');
    setRecipients({ ...noRecipients(), to: defaultReplyTo({ messages: [m] }) });
    window.setTimeout(() => editorRef.current?.focus(), 0);
  };

  const forwardMessage = (m: InboxMessage) => {
    const quoted = forwardedHtml({
      fromName: m.from.name,
      fromEmail: m.from.email,
      sentAt: m.sentAt,
      subject: m.subject,
      text: m.bodyText ?? (m.bodyHtmlSafe ? htmlToText(m.bodyHtmlSafe) : ''),
    });
    // what was typed stays above the forwarded email; an earlier forward is replaced
    setReply((forwarding ? '' : reply) + quoted);
    setEditorVersion((v) => v + 1);
    setMode('email');
    setChosen(null);
    setForwarding({ files: m.attachments.filter((a) => !a.isInline) });
    setRecipients(noRecipients());
  };

  /** The server fills the template's merge fields for the contact when it sends. */
  const applyTemplate = async (tpl: EmailTemplate) => {
    if (!contact) return;
    const threadAt = currentIdRef.current;
    const dealId = contact.deals.find((d) => !openStages || openStages.has(d.stage.id))?.id;
    try {
      const preview = await previewEmailTemplate(tpl.id, { contactId: contact.id, dealId });
      // the user opened another conversation meanwhile: this preview is for the old contact
      if (currentIdRef.current !== threadAt) return;
      setChosen({ template: tpl, preview, contactId: contact.id, dealId });
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  /**
   * The same for a "/" that arrived as text with no key press (some phone keyboards and input
   * tools): true when the templates are being opened, so the editor takes the "/" out again.
   */
  const onSlashTyped = () => {
    if (!contact || forwarding) return false;
    setInsertOpenAt('templates');
    return true;
  };

  /**
   * "/" at the start of a line or after a space opens the templates, as the placeholder says.
   * (The design mock uses "/" for AI commands, which this app does not have.)
   */
  const onReplyKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    if (e.key !== '/' || !contact || forwarding) return;
    const selection = window.getSelection();
    const node = selection?.anchorNode;
    const before =
      node?.nodeType === Node.TEXT_NODE
        ? (node.textContent ?? '').slice(0, selection?.anchorOffset ?? 0)
        : '';
    if (htmlIsEmpty(reply) || /(^|\s)$/.test(before)) {
      e.preventDefault();
      setInsertOpenAt('templates');
    }
  };

  /** New email: a template is filled in for the first person in To, who must be a contact. */
  const fillForRecipient = async (tpl: EmailTemplate, email: ComposeContext) => {
    const address = email.to[0];
    if (!address) return;
    try {
      const found = await findContactByEmail(address);
      if (!found) {
        toast(
          `${address} is not a CRM contact. A template fills in a contact’s details, so add them as a contact first.`,
          'danger',
        );
        return;
      }
      const dealId = found.deals.find((d) => !openStages || openStages.has(d.stage.id))?.id;
      const preview = await previewEmailTemplate(tpl.id, { contactId: found.id, dealId });
      if (preview.missingFields.length) {
        toast(
          `No value for: ${preview.missingFields.join(', ')}. Fill these in on ${address} first.`,
          'danger',
        );
        return;
      }
      email.fillTemplate({
        templateId: tpl.id,
        contactId: found.id,
        dealId,
        address,
        subject: preview.subject,
        bodyHtml: preview.bodyHtml,
      });
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  /**
   * The design's "Insert" menu. Some entries need the conversation's contact; New email has no
   * conversation, so there they need none, or (templates) take the one in To.
   */
  const insertItems = (
    editor: () => InboxEditorHandle | null,
    target: 'reply' | 'compose',
    email?: ComposeContext,
  ): InsertItem[] => {
    const forContact = target === 'reply' ? contact : null;
    // Snippets need no contact. In a chat the visitor only typed their address, so the contact
    // it matches may not be them: its fields are never filled into what they are sent.
    const isChatReply = (thread?.channel ?? current?.channel) === 'chat';
    const snippetTarget = forContact && !isChatReply ? { contactId: forContact.id } : {};
    const needsContact =
      target === 'compose'
        ? 'Needs a contact: use the reply box of a conversation'
        : 'Needs a CRM contact in this conversation';
    const templatesOff = target === 'reply' && !!forwarding;
    const templatesUsable = email ? email.to.length > 0 : !!forContact && !templatesOff;
    return [
      { id: 'kb', label: 'Knowledge base articles', icon: 'book', why: SOON },
      {
        id: 'snippets',
        label: 'Snippets',
        icon: 'snippet',
        searchable: true,
        load: async () =>
          (await listSnippets()).data.map((s) => ({
            id: s.id,
            label: `${s.name} (#${s.shortcut})`,
            group: s.folder,
          })),
        onPick: async (option) => {
          const into = editor();
          try {
            const filled = await applySnippet(option.id, snippetTarget);
            const ready = readySnippet(filled);
            into?.insertHtml(ready.html);
            if (ready.notice) toast(ready.notice, 'danger', { durationMs: 8000 });
          } catch (err) {
            toast(errorText(err), 'danger');
          }
        },
        emptyText: 'No snippets yet',
        manage: { href: '/snippets', label: 'Manage snippets' },
      },
      { id: 'video', label: 'Video', icon: 'video', why: SOON },
      {
        id: 'meetings',
        label: 'Meetings',
        icon: 'meet',
        load: async () =>
          (await listBookingPages('me')).data
            .filter((page) => page.active)
            .map((page) => ({
              id: page.id,
              label: page.title,
              html: linkHtml(bookingUrl(window.location.origin, page.slug), page.title),
            })),
        onPick: (option) => editor()?.insertHtml(option.html ?? ''),
        emptyText: 'You have no active booking pages',
        manage: { href: '/meeting-scheduler', label: 'Manage booking pages' },
      },
      { id: 'documents', label: 'Documents', icon: 'doc', why: SOON },
      {
        id: 'quotes',
        label: 'Quotes',
        icon: 'quote',
        why: needsContact,
        load: forContact
          ? async () =>
              sendableQuotes((await listQuotes({ contactId: forContact.id })).data).map((q) => {
                const name = `${q.numberDisplay} · ${q.title}`;
                return { id: q.id, label: name, html: linkHtml(q.publicUrl ?? '', name) };
              })
          : undefined,
        onPick: (option) => editor()?.insertHtml(option.html ?? ''),
        emptyText: 'No published quotes for this contact',
        manage: { href: '/quotes', label: 'Go to Quotes' },
      },
      {
        id: 'templates',
        label: 'Templates',
        icon: 'tpl',
        why: email
          ? 'Add a recipient in To first'
          : templatesOff
            ? 'A template would replace the forwarded email'
            : needsContact,
        searchable: true,
        load: templatesUsable
          ? async () => {
              templatesRef.current = (await listEmailTemplates()).data;
              return templatesRef.current.map((t) => ({
                id: t.id,
                label: t.name,
                group: t.folder,
              }));
            }
          : undefined,
        onPick: async (option) => {
          const tpl = templatesRef.current.find((t) => t.id === option.id);
          if (!tpl) return;
          if (email) await fillForRecipient(tpl, email);
          else await applyTemplate(tpl);
        },
        emptyText: 'No templates yet',
        manage: { href: '/templates', label: 'Manage templates' },
      },
      { id: 'invoices', label: 'Invoices', icon: 'invoice', why: SOON },
      {
        id: 'signature',
        label: 'Signature',
        icon: 'sign',
        why: 'Add your signature in Settings first',
        load: signature
          ? async () => [
              {
                id: 'toggle',
                label: useSignature ? 'Don’t add my signature' : 'Add my signature when sending',
              },
            ]
          : undefined,
        onPick: () => setUseSignature((on) => !on),
        manage: { href: '/settings/profile#tab-email', label: 'Edit signature' },
      },
    ];
  };

  /* composer: attachments */
  const addReplyFiles = async (files: File[]) => {
    if (!files.length) return;
    const threadAt = currentIdRef.current;
    setUploading(true);
    let bytes = uploadedBytes;
    for (const file of files) {
      const problem = attachmentProblem(file, bytes);
      if (problem) {
        toast(`${file.name}: ${problem}`, 'danger');
        continue;
      }
      try {
        const up = await uploadAttachment(file);
        if (currentIdRef.current !== threadAt) {
          // finished after the user left that conversation: don't attach it to another
          void deleteAttachment(up.attachmentId).catch(() => {});
          continue;
        }
        bytes += up.sizeBytes;
        setUploads((list) => [...list, up]);
      } catch (err) {
        toast(`${file.name}: ${errorText(err)}`, 'danger');
      }
    }
    setUploading(false);
  };

  const onFiles = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.currentTarget.files ?? []);
    e.currentTarget.value = '';
    void addReplyFiles(files);
  };

  const removeUpload = async (id: string) => {
    setUploads((list) => list.filter((u) => u.attachmentId !== id));
    await deleteAttachment(id).catch(() => {});
  };

  /* composer: the design's grip drags the reply box taller or shorter */
  const onGrip = (e: React.PointerEvent) => {
    const box = composerRef.current;
    if (!box) return;
    e.preventDefault();
    const from = { y: e.clientY, height: box.offsetHeight };
    const limit = (box.parentElement?.clientHeight ?? window.innerHeight) * 0.7;
    const move = (ev: PointerEvent) => {
      const height = Math.min(limit, Math.max(190, from.height + from.y - ev.clientY));
      setComposerHeight(Math.round(height));
    };
    const up = () => {
      window.removeEventListener('pointermove', move);
      window.removeEventListener('pointerup', up);
    };
    window.addEventListener('pointermove', move);
    window.addEventListener('pointerup', up);
  };

  /* composer: send */
  const withSignature = (html: string) =>
    useSignature && signature ? `${html}<p><br></p>${signature}` : html;

  /**
   * After sending, check the queued email until Gmail has it (or it failed). A reply
   * knows its thread; a new email finds it first. Shown in the open conversation.
   */
  const pollSend = (
    target: { threadId: string | null; messageId: string; inbox?: string },
    tries = 0,
  ) => {
    const timer = window.setTimeout(async () => {
      pollTimers.current.delete(timer);
      const threadId =
        target.threadId ??
        (await findThreadOfMessage(target.messageId, target.inbox).catch(() => null));
      let status: string | null | undefined;
      if (threadId) {
        const detail = await getThread(threadId).catch(() => null);
        if (detail && currentIdRef.current === threadId) setThread(detail);
        status = detail?.messages.find((m) => m.id === target.messageId)?.sendStatus;
      }
      if (status && FINAL_SEND_STATUSES.has(status)) {
        if (status === 'failed') {
          toast('The email could not be sent', 'danger', { durationMs: null });
        }
        if (status === 'uncertain') {
          toast('The email may not have been sent; check Gmail', 'danger', { durationMs: null });
        }
        void loadThreads(listRef.current);
      } else if (tries + 1 < POLL_TRIES) {
        pollSend({ ...target, threadId }, tries + 1);
      } else {
        toast('Still sending. It shows as sent once Gmail confirms.', 'info', { durationMs: 8000 });
        const later = window.setTimeout(() => {
          pollTimers.current.delete(later);
          void loadThreads(listRef.current);
          if (threadId && currentIdRef.current === threadId) {
            void loadThread(threadId, { quiet: true });
          }
        }, 30_000);
        pollTimers.current.add(later);
      }
    }, POLL_MS);
    pollTimers.current.add(timer);
  };

  /** Closes the conversation after a "Send and close". */
  const closeAfterSend = (id: string) =>
    // what was written is sent either way: a failure here only leaves the conversation open
    changeThreadById(id, { status: 'closed' }).then(
      () => toast('Conversation closed'),
      (err) => toast(errorText(err), 'danger'),
    );

  const sendChat = async (id: string, thenClose: boolean) => {
    if (htmlIsEmpty(reply)) {
      editorRef.current?.focus();
      toast('Write a message first', 'danger');
      return;
    }
    setSending(true);
    try {
      await replyToThread(id, { mode: 'reply', bodyHtml: reply, idempotencyKey: replyKey });
      writeDraft(draftsOf, id, null);
      // another conversation was opened meanwhile: its own box stays as it is
      if (currentIdRef.current !== id) return;
      clearDraft();
      setTyping(false);
      setReplyKey(newIdempotencyKey());
      scrollPending.current = true;
      await loadThread(id, { quiet: true });
      scrollPending.current = true;
      if (thenClose) await closeAfterSend(id);
      else void refreshThreads();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSending(false);
    }
  };

  /** Sends the reply or forward; `thenClose` is the design's "Send and close". */
  const sendReply = async ({
    thenClose = false,
    sendAt,
  }: { thenClose?: boolean; sendAt?: string } = {}) => {
    if (!currentId || sending || uploading) return;
    if (thread?.channel === 'chat') return sendChat(currentId, thenClose);
    if (!chosen && htmlIsEmpty(reply)) {
      editorRef.current?.focus();
      toast('Write a reply first', 'danger');
      return;
    }
    if (chosen?.preview.missingFields.length) {
      toast(`Fill in before sending: ${chosen.preview.missingFields.join(', ')}`, 'danger');
      return;
    }
    if (!recipients.to.length) {
      toast('Add a recipient', 'danger');
      return;
    }
    const id = currentId;
    const uploaded = uploads.map((u) => u.attachmentId);
    setSending(true);
    try {
      const res = await replyToThread(id, {
        mode: forwarding ? 'forward' : 'reply',
        to: recipients.to,
        cc: recipients.cc,
        bcc: recipients.bcc,
        ...(chosen
          ? {
              template: {
                templateId: chosen.template.id,
                contactId: chosen.contactId,
                dealId: chosen.dealId,
              },
            }
          : { bodyHtml: withSignature(reply) }),
        idempotencyKey: replyKey,
        ...sendFields(choices),
        ...(sendAt ? { sendAt } : {}),
        // a forward names its files, even none: otherwise the API adds the last email's
        attachmentIds: forwarding
          ? [...forwarding.files.map((f) => f.id), ...uploaded]
          : uploaded.length
            ? uploaded
            : undefined,
      });
      writeDraft(draftsOf, id, null);
      if (currentIdRef.current !== id) {
        // another conversation was opened meanwhile: its own box stays as it is
        toast(sendAt ? `Scheduled for ${new Date(sendAt).toLocaleString()}` : 'Reply queued');
        if (!sendAt) pollSend({ threadId: id, messageId: res.id });
        if (thenClose) await closeAfterSend(id);
        return;
      }
      clearDraft();
      setTyping(false);
      setForwarding(null);
      setChosen(null);
      setRecipients((r) => ({ ...noRecipients(), to: forwarding ? [] : r.to }));
      setUploads([]); // sent with the email: no longer pending
      setReplyKey(newIdempotencyKey());
      setChoices(DEFAULT_SEND_CHOICES);
      if (res.warnings.length) toast(warningText(res.warnings), 'info', { durationMs: null });
      else if (sendAt) toast(`Scheduled for ${new Date(sendAt).toLocaleString()}`);
      else toast(forwarding ? 'Forward queued' : 'Reply queued');
      await loadThread(id, { quiet: true });
      scrollPending.current = true;
      // a scheduled email is not waited for
      if (!sendAt) pollSend({ threadId: id, messageId: res.id });
      if (thenClose) await closeAfterSend(id);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSending(false);
    }
  };

  /* New email */
  const sendNewEmail = async (email: NewEmail) => {
    if (!email.subject.trim()) {
      toast('Add a subject', 'danger');
      return false;
    }
    try {
      const res = await sendEmail({
        to: email.to,
        ...(email.cc.length ? { cc: email.cc } : {}),
        ...(email.bcc.length ? { bcc: email.bcc } : {}),
        subject: email.subject,
        bodyHtml: withSignature(email.bodyHtml),
        idempotencyKey: email.idempotencyKey,
        ...(email.inboxId ? { inboxId: email.inboxId } : {}),
        ...sendFields(email.choices),
        ...(email.sendAt ? { sendAt: email.sendAt } : {}),
        ...(email.template ? { template: email.template } : {}),
        ...(email.attachmentIds ? { attachmentIds: email.attachmentIds } : {}),
      });
      if (res.warnings.length) toast(warningText(res.warnings), 'info', { durationMs: null });
      else if (email.sendAt) {
        toast(`Scheduled for ${new Date(email.sendAt).toLocaleString()}`);
      } else toast(`Email queued to ${email.to.join(', ')}`);
      if (email.sendAt) void loadThreads(listRef.current);
      else pollSend({ threadId: null, messageId: res.id, inbox: email.inboxId });
      return true;
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  const invalidAddress = (text: string) => toast(`"${text}" is not an email address`, 'danger');

  /* task */
  const openTask = () => {
    if (taskTitleRef.current) {
      taskTitleRef.current.value = `Follow up: ${subject.replace(/^Re:\s*/i, '')}`;
    }
    setTaskOpen(true);
  };

  const onCreateTask = async (d: Record<string, string>) => {
    try {
      await createTask({
        title: d.title ?? '',
        taskType: d.type || undefined,
        dueDate: d.date || undefined,
        links: contact ? [{ objectType: 'contact', id: contact.id }] : [],
      });
      toast(contact ? `Task created for ${contactName(contact)}` : 'Task created');
      if (contact) setNextTask(await nextOpenTask(contact.id).catch(() => null));
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  const closeTask = useCallback(() => setTaskOpen(false), []);

  /* ------------------------------------------------------------ render */

  if (!mailbox) {
    return (
      <>
        <h1 className="crm-visually-hidden">Inbox</h1>
        <p className="crm-text-muted">Loading your inbox…</p>
      </>
    );
  }

  if (!list.inbox && !myUsable) {
    const teams = shared?.data.filter(canRead) ?? [];
    const reconnect = needsReconnect(mailbox);
    return (
      <>
        <h1 className="crm-visually-hidden">Inbox</h1>
        <section className="sales-card crm-text-center" style={{ padding: 48 }}>
          <h2 className="sales-card__title crm-mb-2">
            {reconnect ? 'Reconnect your Gmail' : 'Connect your Gmail to use the Inbox'}
          </h2>
          <p className="crm-text-muted crm-mb-4">
            {reconnect
              ? `Your Gmail connection (${mailbox.emailAddress ?? 'Gmail'}) stopped working. Reconnect it to see and send email.`
              : 'Email you exchange with CRM contacts shows up here, and you can reply from the CRM.'}
          </p>
          <button type="button" className="btn-crm btn-crm--primary" onClick={onConnect}>
            <CrmIcon name="mail" className="iconSize-16" />
            {reconnect ? 'Reconnect Gmail' : 'Connect Gmail'}
          </button>
          {teams.length ? (
            <p className="crm-mt-4">
              Or open a team inbox:{' '}
              {teams.map((i) => (
                <button
                  key={i.id}
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm crm-mr-2"
                  onClick={() => void switchInbox(i.id)}
                >
                  {i.name}
                </button>
              ))}
            </p>
          ) : null}
        </section>
      </>
    );
  }

  const labelOf = (options: PicklistOption[], value: string | null | undefined) =>
    value ? (options.find((s) => s.value === value)?.label ?? value) : '--';
  const readOnly = me.role === 'read_only';
  const colleagues = owners
    .filter((o) => o.active && o.userId !== me.user.id)
    .map((o) => ({ id: o.userId, name: o.name, email: o.email }));
  const mentionable: Mentionable[] = colleagues.map((t) => ({ id: t.id, name: t.name }));
  // in a team inbox a conversation goes to its members; elsewhere colleagues are only shown
  const teammates = list.inbox
    ? (team?.members ?? []).filter((m) => m.id !== me.user.id)
    : colleagues;
  const canReassign =
    me.role === 'admin' ||
    me.permissionSet.rules.app.reassign_conversations ||
    me.permissionSet.rules.app.manage_inboxes;
  /** Why a teammate can't be picked; null: they can. */
  const othersWhy = !list.inbox ? ASSIGN_PERSONAL : canReassign ? null : ASSIGN_NEEDS_PERMISSION;
  /** Someone else's team conversation stays theirs without the permission to move it. */
  const assignLocked =
    !!list.inbox && !canReassign && !!thread?.assignee && thread.assignee.id !== me.user.id;
  const inboxTeams = list.inbox ? (team?.teams ?? []) : [];
  /** The open team inbox can't send email (no Gmail, or its connection stopped). */
  const teamOff = !!list.inbox && (!team || !canEmail(team));
  const channel = thread?.channel ?? current?.channel ?? 'email';
  const isChat = channel === 'chat';
  /** The address the open conversation is in. */
  const address = list.inbox ? (team?.emailAddress ?? null) : mailbox.emailAddress;
  /** Where it arrived: that address, or the team inbox's name when it has none. */
  const arrivedVia = address ?? (list.inbox ? (team?.name ?? 'the team inbox') : null);
  const fromName = list.inbox ? (team?.name ?? 'Team inbox') : me.user.name;
  /** "From" choices of a new email: my own Gmail and the team inboxes that work. */
  const fromChoices = [
    ...(myUsable
      ? [{ inboxId: '', label: `${me.user.name} (${mailbox.emailAddress ?? ''})` }]
      : []),
    ...(shared?.data ?? [])
      .filter(canEmail)
      .map((i) => ({ inboxId: i.id, label: `${i.name} (${i.emailAddress ?? ''})` })),
  ];
  const canSetUpTeams = !!shared && (shared.canManage || shared.canConnect);
  const missing = chosen?.preview.missingFields ?? [];
  // my own Gmail's consent says nothing about a team inbox's
  const limitedFeatures = !list.inbox && mailbox.gmailConsent === 'limited';

  const folded = widths.includes('is-fold');
  const compact = widths.includes('is-compact');
  const railShown = folded ? railPeek : railOn;
  const sideOn = sidePanelOpen(sideChoice, widths.includes('is-snug'));
  const sideShown = compact ? sidePeek : sideOn;
  const bulk = selected.size > 0;
  // A chat visitor only typed their email address: the contact it matches may not be them, so
  // the heading keeps the name they gave and names no company. The side panel says why.
  const known = isChat ? null : contact;
  const partyName = known ? contactName(known) : otherParty ? displayName(otherParty) : '(unknown)';
  const company = known?.companies[0] ?? null;
  const createdAt = thread?.messages[0]?.sentAt ?? null;
  const replyChoices: RecipientChoice[] = (thread?.participants ?? []).map((p) => ({
    email: p.email.toLowerCase(),
    label: p.name ? `${p.name} · ${p.email}` : p.email,
  }));
  // a chat needs no Gmail: it is answered in the chat
  const cannotSend = !currentId || (isChat ? readOnly : limitedFeatures || teamOff);
  const presenceLine = presenceText(presence);
  const recordChoices: RecordChoice[] = contact
    ? [
        { type: 'contact', id: contact.id, label: `Contact: ${contactName(contact)}` },
        ...contact.companies.map((c) => ({
          type: 'company',
          id: c.id,
          label: `Company: ${c.name}`,
        })),
        ...contact.deals.map((d) => ({ type: 'deal', id: d.id, label: `Deal: ${d.name}` })),
      ]
    : [];
  const sendReady = isChat
    ? !cannotSend && !sending && !htmlIsEmpty(reply)
    : !cannotSend &&
      !sending &&
      !uploading &&
      !missing.length &&
      recipients.to.length > 0 &&
      (!!chosen || !htmlIsEmpty(reply));
  const sendBlocked = isChat
    ? 'Write a message to send'
    : uploading
      ? 'Wait for the attachment to finish uploading'
      : missing.length
        ? 'Fill in the missing fields first'
        : !recipients.to.length
          ? 'Add a recipient'
          : 'Write a message to send';

  const toggleRail = () => {
    if (folded) setRailPeek((v) => !v);
    else setRailOn((v) => !v);
  };
  const toggleSide = () => {
    if (compact) {
      setSidePeek((v) => !v);
      return;
    }
    setSideChoice(!sideOn);
    saveSidePanel(!sideOn);
  };

  return (
    <>
      <h1 className="crm-visually-hidden">Inbox</h1>

      {limitedFeatures ? (
        <div className="alert alert--warning crm-mb-3" role="status">
          Gmail is on <strong>Limited Features</strong> — you can read and log email, but sending
          and replies from the CRM Inbox need All Features.{' '}
          <Link className="link" href="/extension/popup/setup-permissions?mode=upgrade">
            Update Permissions
          </Link>
        </div>
      ) : null}
      {team && (!canRead(team) || emailBroken(team)) ? (
        <div className="alert alert--warning crm-mb-3" role="status">
          {emailBroken(team)
            ? `The Gmail connection of ${team.name} stopped working: new email isn’t arriving and nothing can be sent from it.`
            : `${team.name} has no Gmail address or channel set up yet.`}{' '}
          {canSetUpTeams ? (
            <Link className="link" href="/settings/inboxes">
              Inbox Settings
            </Link>
          ) : (
            'Ask someone who manages inboxes to connect it.'
          )}
        </div>
      ) : null}

      <div
        ref={setRootEl}
        className={cn(
          'ix',
          widths.join(' '),
          !folded && !railOn && 'is-rail-off',
          folded && railPeek && 'is-rail-peek',
          !compact && !sideOn && 'is-side-off',
          compact && sidePeek && 'is-side-peek',
          (!currentId || bulk) && 'is-nothread',
          list.searching && 'is-search',
          reading && 'is-reading',
          bulk && 'is-bulk',
        )}
      >
        <InboxRail
          current={list}
          inboxes={shared?.data ?? []}
          inbox={list.inbox}
          onInbox={(id) => void switchInbox(id)}
          availability={availability}
          onAvailability={(next) => void changeAvailability(next)}
          alerts={alerts.choices}
          onToggleAlert={(key) =>
            void alerts.toggle(key).then((allowed) => {
              if (!allowed) toast('Your browser is not allowing desktop notifications', 'danger');
            })
          }
          counts={counts}
          searching={list.searching}
          canManageSettings={me.permissionSet.rules.app.manage_settings}
          canSetUpTeams={canSetUpTeams}
          onLogCall={
            team && canRead(team) && team.channels.calls.enabled && !readOnly
              ? () => setCallOpen(true)
              : undefined
          }
          onSelect={showView}
          onHide={toggleRail}
          onSearch={setSearching}
          onCompose={() => {
            if (fromChoices.length) setComposeOpen(true);
            else toast('No connected address can send right now', 'danger');
          }}
        />

        {list.searching ? (
          <div className="ix-searchbar ix-searchbar--filters">
            <label className="ix-sbox">
              <span className="crm-visually-hidden">Search Inbox</span>
              <input
                type="search"
                placeholder="Search subject, sender, email text or attachment name"
                autoComplete="off"
                autoFocus
                maxLength={191}
                value={list.q}
                onChange={(e) => onSearchText(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Escape') setSearching(false);
                }}
              />
              <IxIcon name="search" />
            </label>
            <div className="ix-sfilters">
              <label>
                <span>Status</span>
                <select
                  className="input"
                  value={list.searchStatus}
                  onChange={(e) =>
                    void applyList({ searchStatus: e.target.value as ListFilter['searchStatus'] })
                  }
                >
                  <option value="">Any status</option>
                  {Object.entries(STATUS_LABELS).map(([value, label]) => (
                    <option key={value} value={value}>
                      {value === 'open' ? 'Not closed' : label}
                    </option>
                  ))}
                </select>
              </label>
              <label>
                <span>From date</span>
                <input
                  className="input"
                  type="date"
                  value={list.from}
                  max={list.to || undefined}
                  onChange={(e) => void applyList({ from: e.target.value })}
                />
              </label>
              <label>
                <span>To date</span>
                <input
                  className="input"
                  type="date"
                  value={list.to}
                  min={list.from || undefined}
                  onChange={(e) => void applyList({ to: e.target.value })}
                />
              </label>
              <label>
                <span>Channel</span>
                <select
                  className="input"
                  value={list.searchChannel}
                  disabled={!list.inbox}
                  title={list.inbox ? undefined : 'Your own mailbox holds email only'}
                  onChange={(e) =>
                    void applyList({
                      searchChannel: e.target.value as ListFilter['searchChannel'],
                    })
                  }
                >
                  <option value="">Any channel</option>
                  {Object.entries(CHANNELS).map(([value, { label }]) => (
                    <option key={value} value={value}>
                      {label}
                    </option>
                  ))}
                </select>
              </label>
            </div>
          </div>
        ) : null}

        <InboxList
          threads={threads}
          loading={listLoading}
          hasMore={!!cursor}
          currentId={currentId}
          selected={selected}
          status={list.status}
          unreadOnly={list.unread}
          searching={list.searching}
          hasQuery={!listsNothing(list)}
          oldestFirst={list.oldestFirst}
          onSort={(oldestFirst) => void applyList({ oldestFirst })}
          railShown={railShown}
          onToggleRail={toggleRail}
          onStatus={(status) => showView({ status, box: 'inbox', sent: false })}
          onUnreadOnly={(unread) => void applyList({ unread })}
          onSelectAll={(on) => setSelected(on ? new Set(threads.map((t) => t.id)) : new Set())}
          onSelect={(id, on) =>
            setSelected((was) => {
              const next = new Set(was);
              if (on) next.add(id);
              else next.delete(id);
              return next;
            })
          }
          onOpen={openThread}
          onLoadMore={() => {
            if (cursor) void loadThreads(list, cursor);
          }}
        />

        {/* ------------------------------------------------------ conversation */}
        <section className="ix-thread" aria-label="Conversation">
          {bulk ? (
            <>
              <header className="ix-th ix-th--bulk">
                <div className="ix-th__acts">
                  {(
                    [
                      [
                        'check',
                        'Close conversation',
                        () => changeSelected({ status: 'closed' }, 'Closed'),
                      ],
                      ['mail', 'Mark as read', () => markSelected(false)],
                      ['mail', 'Mark as unread', () => markSelected(true)],
                      [
                        'user',
                        'Assign to me',
                        () => changeSelected({ assigneeId: me.user.id }, 'Assigned to you:'),
                      ],
                      [
                        'user',
                        'Unassign',
                        () => changeSelected({ assigneeId: null }, 'Unassigned'),
                      ],
                      ...(list.box === 'inbox'
                        ? ([
                            [
                              'spam',
                              'Mark as spam',
                              () => changeSelected({ box: 'spam' }, 'Moved to Spam:'),
                            ],
                            [
                              'trash',
                              'Move to trash',
                              () => changeSelected({ box: 'trash' }, 'Moved to Trash:'),
                            ],
                          ] as const)
                        : ([
                            [
                              'move',
                              'Move to inbox',
                              () => changeSelected({ box: 'inbox' }, 'Moved to the inbox:'),
                            ],
                          ] as const)),
                    ] as const
                  ).map(([icon, label, run]) => (
                    <button
                      key={label}
                      type="button"
                      className="ix-pill"
                      disabled={bulkBusy}
                      onClick={() => void run()}
                    >
                      <IxIcon name={icon} className="ix-i--sm" />
                      {label}
                    </button>
                  ))}
                  {/* a team's conversations can go to any of its people or teams */}
                  {list.inbox ? (
                    <button
                      ref={bulkAssignRef}
                      type="button"
                      className="ix-pill"
                      aria-haspopup="dialog"
                      aria-expanded={bulkAssign}
                      disabled={bulkBusy}
                      onClick={() => setBulkAssign((v) => !v)}
                    >
                      <IxIcon name="user" className="ix-i--sm" />
                      Assign to…
                    </button>
                  ) : null}
                  {bulkAssign && list.inbox ? (
                    <OwnerPicker
                      anchor={bulkAssignRef.current}
                      onClose={() => setBulkAssign(false)}
                      assignee={null}
                      me={me.user}
                      teammates={teammates}
                      teams={inboxTeams}
                      othersWhy={othersWhy}
                      canUnassign
                      onAssign={(id) => {
                        const name =
                          id === me.user.id ? 'you' : teammates.find((t) => t.id === id)?.name;
                        void changeSelected(
                          { assigneeId: id },
                          id ? `Assigned to ${name ?? 'a teammate'}:` : 'Unassigned',
                        );
                      }}
                      onAssignTeam={(id) => {
                        const name = inboxTeams.find((t) => t.id === id)?.name ?? 'a team';
                        void changeSelected({ assigneeTeamId: id }, `Assigned to ${name}:`);
                      }}
                    />
                  ) : null}
                </div>
              </header>
              <div className="ix-empty ix-empty--bulk">
                <p>{selectedWord} selected</p>
              </div>
            </>
          ) : !currentId ? (
            <div className="ix-empty">
              <p>
                {list.searching
                  ? 'Search for anything in Inbox by typing in a term'
                  : 'Choose a thread to continue'}
              </p>
            </div>
          ) : (
            <>
              <header className="ix-th">
                <button
                  type="button"
                  className="ix-icon ix-back"
                  aria-label="Back to conversations"
                  onClick={() => {
                    setSidePeek(false);
                    setReading(false);
                  }}
                >
                  <IxIcon name="left" />
                </button>
                <span className="ix-av">{ixInitials(partyName)}</span>
                <div className="ix-th__t">
                  <h2>{partyName}</h2>
                  <p>
                    {company ? (
                      <>
                        from{' '}
                        <Link href={`/companies/${company.id}`}>
                          {company.name}
                          <IxIcon name="ext" className="ix-i--xs" />
                        </Link>
                        {createdAt ? ' • ' : ''}
                      </>
                    ) : null}
                    {createdAt ? `Created ${timeAgo(createdAt)}` : null}
                  </p>
                </div>
                <div className="ix-th__acts">
                  {thread?.status === 'closed' ? (
                    <button
                      type="button"
                      className="ix-pill"
                      title="Reopen conversation"
                      onClick={() => void changeThread({ status: 'open' }, 'Conversation reopened')}
                    >
                      <IxIcon name="reply" className="ix-i--sm" />
                      Reopen conversation
                    </button>
                  ) : (
                    <button
                      type="button"
                      className="ix-pill"
                      title="Close conversation"
                      disabled={!thread}
                      onClick={() => void changeThread({ status: 'closed' }, 'Conversation closed')}
                    >
                      <IxIcon name="check" className="ix-i--sm" />
                      Close conversation
                    </button>
                  )}
                  <span className="ix-seg">
                    <button
                      ref={moreRef}
                      type="button"
                      className="ix-tip"
                      data-tip="More"
                      aria-label="More actions"
                      aria-haspopup="menu"
                      aria-expanded={menu === 'more'}
                      onClick={() => setMenu((m) => (m === 'more' ? null : 'more'))}
                    >
                      <IxIcon name="more" />
                    </button>
                    <button
                      type="button"
                      className={cn('ix-tip', sideShown && 'is-on')}
                      data-tip="More Information"
                      aria-label="More Information"
                      aria-pressed={sideShown}
                      onClick={toggleSide}
                    >
                      <IxIcon name="info" />
                    </button>
                  </span>
                </div>
              </header>

              {thread ? (
                <ThreadOwner
                  subject={subject}
                  assignee={thread.assignee}
                  assigneeTeam={thread.assigneeTeam}
                  teams={inboxTeams}
                  unassignWhy={thread.assigneeTeam && !canReassign ? ASSIGN_NEEDS_PERMISSION : null}
                  onAssignTeam={(id) => {
                    const name = inboxTeams.find((t) => t.id === id)?.name ?? 'a team';
                    void changeThread({ assigneeTeamId: id }, `Conversation assigned to ${name}`);
                  }}
                  me={me.user}
                  teammates={teammates}
                  othersWhy={othersWhy}
                  locked={assignLocked}
                  busy={false}
                  onAssign={(id) => {
                    const name = teammates.find((t) => t.id === id)?.name;
                    void changeThread(
                      { assigneeId: id },
                      id
                        ? `Conversation assigned to ${id === me.user.id ? 'you' : (name ?? 'a teammate')}`
                        : 'Conversation unassigned',
                    );
                  }}
                >
                  <label className="ix-status">
                    <span className="ix-owner__l">Status</span>
                    <select
                      value={thread.status}
                      onChange={(e) => {
                        const status = e.target.value as InboxThreadStatus;
                        void changeThread({ status }, `Status: ${STATUS_LABELS[status]}`);
                      }}
                    >
                      {Object.entries(STATUS_LABELS).map(([value, label]) => (
                        <option key={value} value={value}>
                          {label}
                        </option>
                      ))}
                    </select>
                  </label>
                </ThreadOwner>
              ) : null}

              {presenceLine ? (
                <p className="ix-presence" role="status">
                  <IxIcon name="user" className="ix-i--sm" />
                  {presenceLine}
                </p>
              ) : null}

              <div className="ix-msgs" ref={messagesRef} aria-live="polite">
                {threadLoading && !thread ? <p className="ix-none">Loading conversation…</p> : null}
                {thread ? (
                  <InboxMessages
                    key={thread.id}
                    messages={thread.messages}
                    comments={comments}
                    mailboxAddress={arrivedVia}
                    team={!!list.inbox}
                    canReply={!limitedFeatures && !teamOff && !readOnly}
                    onReply={replyToMessage}
                    onForward={forwardMessage}
                    onCancelScheduled={(m) => void cancelScheduled(m)}
                  />
                ) : null}
              </div>

              <form
                ref={composerRef}
                className={cn(
                  'ix-comp',
                  expanded && 'is-expanded',
                  mode === 'comment' && 'is-comment',
                )}
                style={!expanded && composerHeight ? { height: composerHeight } : undefined}
                onSubmit={(e) => e.preventDefault()}
              >
                <div
                  className="ix-comp__grip"
                  title="Drag to resize"
                  aria-hidden="true"
                  onPointerDown={onGrip}
                >
                  <IxIcon name="grip" className="ix-i--xs" />
                </div>
                <div className="ix-comp__tabs" role="tablist" aria-label="Reply or comment">
                  <span className={cn('ix-comp__tab', mode === 'email' && 'is-on')}>
                    <button
                      type="button"
                      role="tab"
                      aria-selected={mode === 'email'}
                      onClick={() => setMode('email')}
                    >
                      <IxIcon name={isChat ? 'chat' : 'mail'} className="ix-i--sm" />
                      {isChat ? 'Chat' : 'Email'}
                    </button>
                    <button
                      ref={channelRef}
                      type="button"
                      className="ix-comp__chv"
                      aria-label="Choose channel"
                      aria-haspopup="menu"
                      aria-expanded={menu === 'channel'}
                      onClick={() => setMenu((m) => (m === 'channel' ? null : 'channel'))}
                    >
                      <Tri />
                    </button>
                  </span>
                  <button
                    type="button"
                    role="tab"
                    className={cn('ix-comp__tab', mode === 'comment' && 'is-on')}
                    aria-selected={mode === 'comment'}
                    onClick={() => setMode('comment')}
                  >
                    Comment
                  </button>
                  <button
                    type="button"
                    className="ix-icon ix-tip ix-comp__exp"
                    data-tip={expanded ? 'Collapse' : 'Expand'}
                    aria-label={expanded ? 'Collapse composer' : 'Expand composer'}
                    onClick={() => setExpanded((v) => !v)}
                  >
                    <IxIcon name={expanded ? 'shrink' : 'expand'} className="ix-i--sm" />
                  </button>
                </div>

                {mode === 'comment' ? (
                  <>
                    <label className="crm-visually-hidden" htmlFor="commentBox">
                      Comment
                    </label>
                    <MentionTextarea
                      id="commentBox"
                      value={commentText}
                      people={mentionable}
                      disabled={!currentId || commenting}
                      placeholder="Write a comment and @mention teammates. It is never emailed; mentioned teammates are notified."
                      onChange={(text) => {
                        setCommentText(text);
                        noteTyping();
                      }}
                      onMention={(person) =>
                        setPicked((rows) =>
                          rows.some((r) => r.id === person.id) ? rows : [...rows, person],
                        )
                      }
                    />
                    <div className="ix-send">
                      <span className="ix-tipw">
                        <button
                          type="button"
                          className="ix-split__main ix-split__solo"
                          disabled={commenting || !commentText.trim() || readOnly}
                          onClick={() => void onComment()}
                        >
                          Add comment
                        </button>
                        {readOnly || !commentText.trim() ? (
                          <span className="ix-tipbox ix-tipbox--up" role="tooltip">
                            {readOnly
                              ? 'Read-only users can’t add comments'
                              : 'Write a comment to add it'}
                          </span>
                        ) : null}
                      </span>
                    </div>
                  </>
                ) : (
                  <>
                    {isChat ? null : (
                      <RecipientRows
                        value={recipients}
                        disabled={cannotSend || sending}
                        onChange={setRecipients}
                        onInvalid={invalidAddress}
                        suggest={suggestContacts}
                        choices={replyChoices}
                        trailing={
                          <button
                            type="button"
                            className="ix-icon ix-tip"
                            data-tip={
                              showFields ? 'Hide From and Subject' : 'Show From and Subject'
                            }
                            aria-label="Show From and Subject"
                            aria-expanded={showFields}
                            onClick={() => setShowFields((v) => !v)}
                          >
                            <IxIcon name="vmore" className="ix-i--sm" />
                          </button>
                        }
                      />
                    )}
                    {showFields && !isChat ? (
                      <>
                        <div className="ix-comp__row">
                          <span>From</span>
                          <span className="ix-select ix-select--plain">
                            <select
                              key={address ?? ''}
                              aria-label="From"
                              title={FROM_TITLE}
                              defaultValue={address ?? ''}
                            >
                              <option value={address ?? ''}>
                                {fromName} ({address})
                              </option>
                            </select>
                            <Tri />
                          </span>
                        </div>
                        <div className="ix-comp__row">
                          <span>Subject</span>
                          <input
                            type="text"
                            aria-label="Subject"
                            readOnly
                            title="A reply keeps the conversation’s subject"
                            value={replySubject(subject, !!forwarding)}
                          />
                        </div>
                      </>
                    ) : null}
                    {availability === 'away' ? (
                      <p className="ix-comp__note ix-away" role="status">
                        You’re set to <strong>away</strong>.{' '}
                        <button
                          type="button"
                          className="ix-link"
                          onClick={() => void changeAvailability('available')}
                        >
                          Set as available
                        </button>
                      </p>
                    ) : null}
                    {(channel === 'form' || channel === 'call') && thread ? (
                      <p className="ix-comp__note">
                        {teamOff
                          ? `Connect a Gmail address to this team inbox to reply by email. You can still add a comment.`
                          : 'Your reply is sent to them by email.'}
                      </p>
                    ) : null}
                    {isChat && team && !team.channels.chat.enabled ? (
                      <p className="ix-comp__note">
                        Live chat is switched off, so the visitor can no longer see replies.
                      </p>
                    ) : null}
                    {isChat && thread ? (
                      <p className="ix-comp__note">
                        {chatReplyNote(
                          thread.messages.find((m) => m.direction === 'inbound')?.from.email,
                          !teamOff,
                        )}
                      </p>
                    ) : null}
                    {forwarding ? (
                      <p className="ix-comp__note">
                        Forwarding.{' '}
                        <button type="button" className="ix-link" onClick={backToReply}>
                          Cancel forward
                        </button>
                      </p>
                    ) : null}
                    {limitedFeatures ? (
                      <p className="ix-comp__note">
                        Sending is off on Limited Features.{' '}
                        <Link
                          className="link"
                          href="/extension/popup/setup-permissions?mode=upgrade"
                        >
                          Update Permissions
                        </Link>{' '}
                        to reply from the CRM.
                      </p>
                    ) : null}
                    {chosen ? (
                      <>
                        <p className="ix-comp__note">
                          Template: <strong>{chosen.template.name}</strong>{' '}
                          <button
                            type="button"
                            className="ix-link"
                            aria-label="Remove template"
                            onClick={() => setChosen(null)}
                          >
                            Remove
                          </button>
                          {missing.length ? (
                            <span className="crm-text-danger">
                              {' '}
                              · Missing for this contact: {missing.join(', ')}
                            </span>
                          ) : null}
                        </p>
                        {/* read only: the server fills the template again when it sends */}
                        <div className="ix-ed" style={{ whiteSpace: 'pre-line' }}>
                          {htmlToText(chosen.preview.bodyHtml)}
                        </div>
                      </>
                    ) : cannotSend ? null : (
                      <InboxEditor
                        ref={editorRef}
                        resetKey={`${currentId}-${editorVersion}`}
                        value={reply}
                        onChange={(html) => {
                          setReply(html);
                          noteTyping();
                        }}
                        label="Reply"
                        placeholder={`Write a message${contact && !isChat ? '. Press ’/’ for templates.' : ''}`}
                        onKeyDown={isChat ? undefined : onReplyKeyDown}
                        onSlash={isChat ? undefined : onSlashTyped}
                        snippetTarget={known ? { contactId: known.id } : {}}
                      />
                    )}
                    {forwarding?.files.length || uploads.length ? (
                      <ul className="ix-atts ix-atts--draft">
                        {forwarding?.files.map((f) => (
                          <li key={f.id}>
                            <IxIcon name="clip" className="ix-i--xs" />
                            {f.filename ?? 'attachment'}
                            <button
                              type="button"
                              aria-label={`Remove ${f.filename ?? 'attachment'}`}
                              onClick={() =>
                                setForwarding({
                                  files: forwarding.files.filter((x) => x.id !== f.id),
                                })
                              }
                            >
                              <IxIcon name="x" className="ix-i--xs" />
                            </button>
                          </li>
                        ))}
                        {uploads.map((u) => (
                          <li key={u.attachmentId}>
                            <IxIcon name="clip" className="ix-i--xs" />
                            {u.filename}
                            <button
                              type="button"
                              aria-label={`Remove ${u.filename}`}
                              onClick={() => void removeUpload(u.attachmentId)}
                            >
                              <IxIcon name="x" className="ix-i--xs" />
                            </button>
                          </li>
                        ))}
                      </ul>
                    ) : null}
                    <InboxTools
                      editor={editorRef}
                      disabled={cannotSend || !!chosen}
                      // a chat carries text only
                      onImage={isChat ? undefined : () => imageRef.current?.click()}
                      onAttach={isChat ? undefined : () => fileRef.current?.click()}
                      insert={insertItems(() => editorRef.current, 'reply').filter(
                        (item) => !isChat || CHAT_INSERTS.has(item.id),
                      )}
                      insertOpenAt={insertOpenAt}
                      onInsertClosed={closeInsert}
                    />
                    <input
                      ref={imageRef}
                      type="file"
                      accept="image/png,image/jpeg,image/gif,image/webp"
                      aria-label="Image to attach"
                      hidden
                      onChange={onFiles}
                    />
                    <input
                      ref={fileRef}
                      type="file"
                      aria-label="Files to attach"
                      multiple
                      hidden
                      onChange={onFiles}
                    />
                    <div className="ix-send ix-send--email">
                      <span className="ix-split ix-tipw">
                        <button
                          type="button"
                          className="ix-split__main"
                          disabled={!sendReady}
                          onClick={() => void sendReply()}
                        >
                          {sending ? 'Sending…' : 'Send'}
                        </button>
                        <button
                          ref={sendMoreRef}
                          type="button"
                          className="ix-split__chv"
                          aria-label="More send options"
                          aria-haspopup="menu"
                          aria-expanded={menu === 'send'}
                          disabled={!sendReady}
                          onClick={() => setMenu((m) => (m === 'send' ? null : 'send'))}
                        >
                          <Tri />
                        </button>
                        {!sendReady && !sending ? (
                          <span className="ix-tipbox ix-tipbox--up" role="tooltip">
                            {sendBlocked}
                          </span>
                        ) : null}
                      </span>
                      {isChat ? null : (
                        <SendOptions
                          value={choices}
                          onChange={setChoices}
                          records={recordChoices}
                        />
                      )}
                      {signature && !chosen && !isChat ? (
                        <span className="ix-muted ix-send__sig crm-fs-8">
                          {useSignature ? 'Signature added when sent' : 'No signature'}
                        </span>
                      ) : null}
                    </div>
                  </>
                )}
              </form>
            </>
          )}
        </section>

        {/* ------------------------------------------------------ contact */}
        <aside className="ix-side" aria-label="Contact details">
          {currentId && !bulk ? (
            <div className="ix-side__bar">
              <span className="ix-side__title">Contact details</span>
              <button
                type="button"
                className="ix-icon ix-tip ix-side__toggle"
                data-tip={sideShown ? 'Hide panel' : 'Show contact details'}
                aria-label={sideShown ? 'Hide contact details' : 'Show contact details'}
                aria-expanded={sideShown}
                onClick={toggleSide}
              >
                <IxIcon name={sideShown ? 'dright' : 'dleft'} />
              </button>
            </div>
          ) : null}
          {otherParty && currentId && !bulk ? (
            <InboxSidebar
              party={otherParty}
              caution={
                isChat && !isStandInAddress(otherParty.email)
                  ? 'The visitor typed this email address in the chat. It isn’t verified, so check who you are talking to before sharing anything.'
                  : undefined
              }
              pastScope={list.inbox ? 'this team inbox' : 'your mailbox'}
              contact={contact}
              contactLoading={contactLoading}
              lifecycleLabel={labelOf(stages, contact?.lifecycleStage)}
              leadStatusLabel={labelOf(leadStatuses, contact?.leadStatus)}
              nextTask={
                nextTask ? [nextTask.title, taskDue(nextTask)].filter(Boolean).join(' · ') : null
              }
              tickets={tickets}
              canCreateTicket={!!thread && !readOnly}
              createTicketTitle={readOnly ? READ_ONLY_TICKET : undefined}
              onCreateTicket={() => setTicketOpen(true)}
              past={past ? otherConversations(past.data, currentId) : null}
              pastHasMore={!!past?.more}
              onOpenConversation={openThread}
            />
          ) : null}
        </aside>

        {composeOpen ? (
          <ComposeWindow
            fromChoices={fromChoices}
            defaultFrom={list.inbox ?? ''}
            suggest={suggestContacts}
            insert={(editor, email) => insertItems(editor, 'compose', email)}
            onInvalid={invalidAddress}
            onProblem={(message) => toast(message, 'danger')}
            onSend={sendNewEmail}
            onClose={() => setComposeOpen(false)}
          />
        ) : null}
      </div>

      {menu === 'more' ? (
        <IxPopover
          anchor={moreRef.current}
          onClose={closeMenu}
          className="ix-pop--icons"
          label="More actions"
          align="right"
        >
          <button
            type="button"
            role="menuitem"
            className="ix-mi"
            onClick={() => {
              closeMenu();
              void setUnread(!current?.isUnread);
            }}
          >
            <IxIcon name="mail" className="ix-i--sm" />
            {current?.isUnread ? 'Mark as read' : 'Mark as unread'}
          </button>
          <button
            type="button"
            role="menuitem"
            className="ix-mi"
            onClick={() => {
              closeMenu();
              openTask();
            }}
          >
            <IxIcon name="check" className="ix-i--sm" />
            Create task
          </button>
          <button
            type="button"
            role="menuitem"
            className="ix-mi"
            disabled={!thread || readOnly}
            title={readOnly ? READ_ONLY_TICKET : undefined}
            onClick={() => {
              closeMenu();
              setTicketOpen(true);
            }}
          >
            <IxIcon name="ticket" className="ix-i--sm" />
            Create ticket
          </button>
          {(
            [
              [
                'trash',
                thread?.box === 'trash' ? 'inbox' : 'trash',
                'Move to Trash',
                'Move to inbox',
              ],
              ['spam', thread?.box === 'spam' ? 'inbox' : 'spam', 'Mark as spam', 'Not spam'],
            ] as const
          ).map(([icon, box, there, back]) => (
            <button
              key={icon}
              type="button"
              role="menuitem"
              className="ix-mi"
              disabled={!thread}
              onClick={() => {
                closeMenu();
                void moveTo(box);
              }}
            >
              <IxIcon name={icon} className="ix-i--sm" />
              {box === 'inbox' ? back : there}
            </button>
          ))}
          {(
            [
              ['block', 'Block Sender'],
              ['block', 'Block IP address'],
              ['move', 'Move conversation'],
            ] as const
          ).map(([icon, label]) => (
            <button
              key={label}
              type="button"
              role="menuitem"
              className="ix-mi"
              disabled
              title={SOON}
            >
              <IxIcon name={icon} className="ix-i--sm" />
              {label}
            </button>
          ))}
        </IxPopover>
      ) : null}

      {menu === 'channel' ? (
        <IxPopover anchor={channelRef.current} onClose={closeMenu} label="Choose channel">
          {/* a conversation is answered the way it came; forms and calls by email */}
          <button
            type="button"
            role="menuitemradio"
            aria-checked="true"
            className="ix-mi"
            onClick={closeMenu}
          >
            {isChat ? 'Chat' : 'Email'}
            <IxIcon name="check" className="ix-i--sm ix-mi__ok" />
          </button>
        </IxPopover>
      ) : null}

      {menu === 'send' ? (
        <IxPopover
          anchor={sendMoreRef.current}
          onClose={closeMenu}
          className="ix-pop--sm"
          label="More send options"
        >
          <button
            type="button"
            role="menuitem"
            className="ix-mi"
            onClick={() => {
              closeMenu();
              void sendReply({ thenClose: true });
            }}
          >
            Send and close
          </button>
          {isChat ? null : (
            <button
              type="button"
              role="menuitem"
              className="ix-mi"
              onClick={() => setMenu('schedule')}
            >
              Schedule send
            </button>
          )}
        </IxPopover>
      ) : null}
      {menu === 'schedule' ? (
        <SchedulePopover
          anchor={sendMoreRef.current}
          onClose={closeMenu}
          onSchedule={(sendAt) => void sendReply({ sendAt })}
        />
      ) : null}

      {/* ------------------------------------------------------ create task from email */}
      <FormDrawer
        id="inboxTaskModal"
        title="Create task"
        submitLabel="Create task"
        open={taskOpen}
        onClose={closeTask}
        onSubmit={onCreateTask}
      >
        <div className="form-grid">
          <Field label="Task title" htmlFor="taskTitle" className="span-2">
            <input className="input" id="taskTitle" name="title" required ref={taskTitleRef} />
          </Field>
          <Field label="Type" htmlFor="taskType">
            <select
              key={taskTypes.length}
              className="input"
              id="taskType"
              name="type"
              defaultValue="email"
            >
              {taskTypes.length ? (
                taskTypes.map((t) => (
                  <option key={t.value} value={t.value}>
                    {t.label}
                  </option>
                ))
              ) : (
                <option value="email">Email</option>
              )}
            </select>
          </Field>
          <Field label="Due date" htmlFor="taskDue">
            <input
              className="input"
              id="taskDue"
              type="date"
              name="date"
              defaultValue={todayIso()}
            />
          </Field>
        </div>
        {!contact ? (
          <p className="crm-fs-8 crm-text-muted crm-mt-3">
            Not linked to a record: this address is not a CRM contact.
          </p>
        ) : null}
      </FormDrawer>

      {callOpen && team ? (
        <InboxCallDrawer
          inboxId={team.id}
          inboxName={team.name}
          contactEmail={contact?.email ?? ''}
          onClose={() => setCallOpen(false)}
          onLogged={(threadId) => {
            void loadThreads(listRef.current);
            setReading(true);
            selectThread(threadId, false);
          }}
        />
      ) : null}

      {/* ------------------------------------------------------ create ticket from the conversation */}
      {ticketOpen && thread ? (
        <InboxTicketDrawer
          thread={thread}
          contact={contact}
          timeZone={me.business.timezone}
          onClose={() => setTicketOpen(false)}
          onCreated={() => void loadTickets(thread.id)}
        />
      ) : null}
    </>
  );
}
