'use client';

import Link from 'next/link';
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { useConfirm } from '@/components/crm/useConfirm';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { LogCallDrawer } from '@/features/contacts/ui/actions/LogCallDrawer';
import { LogNoteDrawer } from '@/features/contacts/ui/actions/LogNoteDrawer';
import { ScheduleMeetingDrawer } from '@/features/contacts/ui/actions/ScheduleMeetingDrawer';
import { SendEmailDrawer } from '@/features/contacts/ui/actions/SendEmailDrawer';
import { listPicklistOptions, type PicklistOption } from '@/features/picklists/api.client';
import { getBusinessSettings } from '@/features/settings/api.client';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { CreateTaskDrawer } from '@/features/tasks/ui/CreateTaskDrawer';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { hideActivityBundle, listActivityFeed, restoreActivityBundle } from '../api.client';
import {
  cardTime,
  emptyText,
  ENROLLMENT_OPTIONS,
  eventTime,
  expandLabel,
  groupCards,
  SOON_TYPES,
  tileInitials,
  TYPE_LOOK,
  TYPE_OPTIONS,
} from '../feed';
import type { ActivityFeedCard, ActivityFeedEnrollment, ActivityFeedType } from '../types';

const PAGE_SIZE = 25;
const TIP_ON =
  'Notifications for this thread are on. Click to disable notifications for this thread.';
const TIP_OFF =
  'Notifications for this thread are off. Click to enable notifications for this thread.';

type Toast = {
  tone: 'success' | 'info' | 'warning';
  title: string;
  msg?: string;
  /** #496: e.g. Undo after a delete. */
  action?: { label: string; run: () => void };
};
type DrawerKind = 'call' | 'email' | 'task' | 'note' | 'meeting';

/* ------------------------------------------------------------ icons (design markup) */

function SearchIcon() {
  return (
    <svg
      className="icon iconSize-18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <circle cx="11" cy="11" r="7" />
      <path d="m20 20-3.5-3.5" />
    </svg>
  );
}

function ChevronRight() {
  return (
    <svg
      className="icon iconSize-14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d="m9 18 6-6-6-6" />
    </svg>
  );
}

function Caret() {
  return (
    <svg className="sw-feed-caret" viewBox="0 0 24 24" aria-hidden="true">
      <path d="m7 10 5 5 5-5z" fill="currentColor" />
    </svg>
  );
}

/* ------------------------------------------------------------ per-user feed state */

/**
 * Bundles the user deleted from the feed and threads they silenced, kept in this browser
 * (the CRM has no per-thread notification setting to store them in yet).
 */
function useFeedPrefs(key: string) {
  const [hidden, setHidden] = useState<Set<string>>(() => new Set());
  const [muted, setMuted] = useState<Set<string>>(() => new Set());
  useEffect(() => {
    try {
      const saved = JSON.parse(window.localStorage.getItem(key) ?? '{}') as {
        hidden?: string[];
        muted?: string[];
      };
      setHidden(new Set(saved.hidden ?? []));
      setMuted(new Set(saved.muted ?? []));
    } catch {
      // storage blocked or unreadable: start empty
    }
  }, [key]);
  const save = useCallback(
    (nextHidden: Set<string>, nextMuted: Set<string>) => {
      try {
        window.localStorage.setItem(
          key,
          JSON.stringify({
            hidden: [...nextHidden].slice(-500),
            muted: [...nextMuted].slice(-500),
          }),
        );
      } catch {
        // storage blocked: the change lasts until the page reloads
      }
    },
    [key],
  );
  /**
   * `remember` false: hidden for this page view only. A deleted bundle is kept by the API (#496),
   * so it is not also stored in the browser, where an Undo from another place could not reach it.
   */
  const hide = (id: string, remember = true) => {
    const next = new Set(hidden).add(id);
    setHidden(next);
    if (remember) save(next, muted);
  };
  const unhide = (id: string) => {
    const next = new Set(hidden);
    next.delete(id);
    setHidden(next);
  };
  const toggleMute = (groupKey: string): boolean => {
    const next = new Set(muted);
    const nowMuted = !next.has(groupKey);
    if (nowMuted) next.add(groupKey);
    else next.delete(groupKey);
    setMuted(next);
    save(hidden, next);
    return !nowMuted;
  };
  return { hidden, muted, hide, unhide, toggleMute };
}

/* ------------------------------------------------------------ filter dropdown */

function FeedFilter<V extends string>({
  id,
  label,
  value,
  options,
  disabled,
  rootRef,
  onChange,
}: {
  id: string;
  label: string;
  value: V;
  options: Array<{ value: V; label: string }>;
  disabled?: ReadonlySet<string>;
  rootRef: React.RefObject<HTMLDivElement | null>;
  onChange: (value: V) => void;
}) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
  const button = useRef<HTMLButtonElement>(null);
  const menu = useRef<HTMLDivElement>(null);
  const current = options.find((o) => o.value === value) ?? options[0]!;

  useLayoutEffect(() => {
    if (!open || !button.current || !rootRef.current || !menu.current) return;
    const rect = button.current.getBoundingClientRect();
    const root = rootRef.current.getBoundingClientRect();
    const width = menu.current.offsetWidth;
    const left = Math.max(
      8 - root.left,
      Math.min(rect.left - root.left, window.innerWidth - width - 8 - root.left),
    );
    setPos({ top: rect.bottom - root.top + 4, left });
    const on = menu.current.querySelector<HTMLButtonElement>('.is-on:not(:disabled)');
    (on ?? menu.current.querySelector<HTMLButtonElement>('button:not(:disabled)'))?.focus();
  }, [open, rootRef]);

  useEffect(() => {
    if (!open) return;
    const close = (event: MouseEvent) => {
      const target = event.target as Node;
      if (!menu.current?.contains(target) && !button.current?.contains(target)) setOpen(false);
    };
    const shut = () => setOpen(false);
    document.addEventListener('click', close);
    window.addEventListener('resize', shut);
    return () => {
      document.removeEventListener('click', close);
      window.removeEventListener('resize', shut);
    };
  }, [open]);

  const onMenuKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
    if (event.key === 'Escape') {
      setOpen(false);
      button.current?.focus();
      return;
    }
    if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
    event.preventDefault();
    const items = Array.from(
      menu.current?.querySelectorAll<HTMLButtonElement>('button:not(:disabled)') ?? [],
    );
    const at = items.indexOf(document.activeElement as HTMLButtonElement);
    const next = at + (event.key === 'ArrowDown' ? 1 : -1);
    items[(next + items.length) % items.length]?.focus();
  };

  return (
    <div className="sw-feed-filter-field">
      <span id={`${id}-l`}>{label}</span>
      <button
        ref={button}
        type="button"
        className="sw-feed-dd"
        data-feed-dd=""
        aria-haspopup="menu"
        aria-expanded={open}
        aria-describedby={`${id}-l`}
        onClick={() => setOpen((v) => !v)}
      >
        <span data-feed-dd-label="">{current.label}</span>
        <Caret />
      </button>
      {open ? (
        <div
          ref={menu}
          className="sw-feed-menu"
          role="menu"
          style={{ top: pos.top, left: pos.left }}
          onKeyDown={onMenuKey}
        >
          {options.map((option) => {
            const soon = disabled?.has(option.value) ?? false;
            return (
              <button
                key={option.value}
                type="button"
                role="menuitemradio"
                aria-checked={option.value === value}
                className={cn('sw-feed-menu__it', option.value === value && 'is-on')}
                disabled={soon}
                title={soon ? 'Coming soon' : undefined}
                onClick={() => {
                  setOpen(false);
                  button.current?.focus();
                  if (option.value !== value) onChange(option.value);
                }}
              >
                {soon ? `${option.label} (coming soon)` : option.label}
              </button>
            );
          })}
        </div>
      ) : null}
    </div>
  );
}

/* ------------------------------------------------------------ card */

function CardSentence({ card }: { card: ActivityFeedCard }) {
  const look = TYPE_LOOK[card.type];
  const person = card.contact;
  const who = person?.id ? (
    <Link className="ep-strong" href={`/contacts/${person.id}`}>
      {person.name}
    </Link>
  ) : (
    <span className="ep-strong">{person?.name ?? 'Someone'}</span>
  );
  let what: React.ReactNode = null;
  if (card.title) {
    if (card.type === 'sent_email' && card.sequence) {
      what = (
        <Link className="ep-strong" href={`/sequences/${card.sequence.id}`}>
          {card.title}
        </Link>
      );
    } else if (card.url) {
      what = (
        <a className="ep-strong" href={card.url} target="_blank" rel="noopener noreferrer">
          {card.title}
        </a>
      );
    } else {
      what = <span className="ep-strong">{card.title}</span>;
    }
  }
  return (
    <p className="ep-card__text">
      {who}
      {/* HUB-709: the contact's job title, after their name. */}
      {person?.title ? <span className="ep-job">, {person.title}</span> : null}
      {card.company ? (
        <>
          {' at '}
          <Link className="ep-strong" href={`/companies/${card.company.id}`}>
            {card.company.name}
          </Link>
        </>
      ) : null}{' '}
      {look.verb}
      {what ? <> {what}</> : null}
    </p>
  );
}

function FeedCard({
  card,
  now,
  timeZone,
  notify,
  menuOpen,
  onBell,
  onDelete,
  onAction,
  onMore,
}: {
  card: ActivityFeedCard;
  now: Date;
  timeZone: string;
  notify: boolean;
  menuOpen: boolean;
  onBell: () => void;
  onDelete: () => void;
  onAction: (kind: DrawerKind) => void;
  onMore: (anchor: HTMLButtonElement) => void;
}) {
  const [expanded, setExpanded] = useState(false);
  const look = TYPE_LOOK[card.type];
  const hasContact = Boolean(card.contact?.id);
  const canEmail = Boolean(card.contact?.email);
  return (
    <li
      className={cn('ep-card', menuOpen && 'is-menu-open')}
      data-feed-item=""
      data-type={card.type}
      data-enrollment={card.inSequence ? 'yes' : 'no'}
      data-notify={notify ? 'on' : 'off'}
    >
      <div className="ep-card__top">
        <span className={`ep-logo-tile ep-tint-${look.tint}`} aria-hidden="true">
          {tileInitials(card)}
        </span>
        <div className="ep-card__body">
          <CardSentence card={card} />
          <time className="ep-card__time" dateTime={card.occurredAt}>
            {cardTime(new Date(card.occurredAt), now, timeZone)}
          </time>
        </div>
        <button
          type="button"
          className="ep-bell"
          data-feed-action="bell"
          aria-pressed={notify}
          aria-label={notify ? 'Thread notifications are on' : 'Thread notifications are off'}
          onClick={onBell}
        >
          <svg
            className="icon ep-bell__on"
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.8"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
            <path d="M13.7 21a2 2 0 0 1-3.4 0" />
          </svg>
          <svg
            className="icon ep-bell__off"
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.8"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5" />
            <path d="M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7" />
            <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
            <path d="m2 2 20 20" />
          </svg>
          <span className="ep-tip" role="tooltip">
            {notify ? TIP_ON : TIP_OFF}
          </span>
        </button>
        <button
          type="button"
          className="ep-bell ep-delete"
          data-feed-action="delete"
          aria-label="Delete activity bundle"
          title="Delete activity bundle"
          onClick={onDelete}
        >
          <svg
            className="icon"
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.8"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="M3 6h18" />
            <path d="M8 6V4h8v2" />
            <path d="M19 6l-1 14H6L5 6" />
            <path d="M10 11v6M14 11v6" />
          </svg>
        </button>
      </div>
      <div className="ep-card__foot">
        <button
          type="button"
          className="ep-expand"
          data-feed-expand=""
          aria-expanded={expanded}
          onClick={() => setExpanded((v) => !v)}
        >
          <ChevronRight />
          <span>{expandLabel(card)}</span>
        </button>
        <div className="ep-card__right">
          <span className={`ep-badge ep-badge--${look.badgeTone}`}>{look.badge}</span>
          <div className="ep-actions">
            {card.type === 'sent_email' ? (
              <>
                <button
                  type="button"
                  className="ep-btn-outline ep-btn-outline--neutral"
                  data-feed-action="thread"
                  onClick={onBell}
                >
                  {notify ? 'Turn off thread notifications' : 'Turn on thread notifications'}
                </button>
                <button
                  type="button"
                  className="ep-btn-outline ep-btn-outline--neutral"
                  data-feed-action="delete"
                  onClick={onDelete}
                >
                  Delete activity bundle
                </button>
              </>
            ) : (
              <>
                <button
                  type="button"
                  className="ep-btn-outline ep-btn-outline--neutral"
                  data-feed-action="call"
                  disabled={!hasContact}
                  onClick={() => onAction('call')}
                >
                  Call
                </button>
                <button
                  type="button"
                  className="ep-btn-outline ep-btn-outline--neutral"
                  data-feed-action="email"
                  disabled={!canEmail}
                  onClick={() => onAction('email')}
                >
                  Email
                </button>
                <button
                  type="button"
                  className="ep-btn-outline ep-btn-outline--neutral"
                  data-feed-action="task"
                  disabled={!hasContact}
                  onClick={() => onAction('task')}
                >
                  Create task
                </button>
                <button
                  type="button"
                  className="ep-btn-outline ep-btn-outline--teal"
                  data-feed-action="more"
                  aria-haspopup="menu"
                  aria-expanded={menuOpen}
                  onClick={(event) => {
                    event.stopPropagation();
                    onMore(event.currentTarget);
                  }}
                >
                  More{' '}
                  <svg
                    className="icon"
                    width="12"
                    height="12"
                    viewBox="0 0 24 24"
                    fill="currentColor"
                    aria-hidden="true"
                  >
                    <path d="M7 10l5 5 5-5z" />
                  </svg>
                </button>
              </>
            )}
          </div>
        </div>
      </div>
      <ol className="ep-timeline" data-feed-timeline="" hidden={!expanded}>
        {card.events.map((event) => (
          <li key={event.id}>
            <p>{event.text}</p>
            <time dateTime={event.occurredAt}>
              {eventTime(new Date(event.occurredAt), now, timeZone)}
            </time>
          </li>
        ))}
      </ol>
    </li>
  );
}

/* ------------------------------------------------------------ page */

/** Sales › Activity Feed (design sales-activity-feed.php, QA #344). */
export function ActivityFeedView() {
  const me = useCurrentUser();
  const prefs = useUserPrefs();
  const timeZone = prefs.timeZone;
  const rootRef = useRef<HTMLDivElement>(null);
  const composer = useRef<ComposerWindowHandle | null>(null);

  const [query, setQuery] = useState('');
  const [q, setQ] = useState('');
  const [type, setType] = useState<'all' | ActivityFeedType>('all');
  // #48: opens and clicks only exist for emails sent while tracking is on, with a tracking domain.
  const [trackingOff, setTrackingOff] = useState(false);
  useEffect(() => {
    getBusinessSettings().then(
      (b) => setTrackingOff(!b.trackingEnabled || !b.trackingDomain),
      () => {},
    );
  }, []);
  const [enrollment, setEnrollment] = useState<ActivityFeedEnrollment>('any');
  const [reload, setReload] = useState(0);

  const [cards, setCards] = useState<ActivityFeedCard[]>([]);
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [now, setNow] = useState(() => new Date());
  const request = useRef(0);

  const { hidden, muted, hide, unhide, toggleMute } = useFeedPrefs(
    `crm-activity-feed:${me.business.id}:${me.user.id}`,
  );

  const [toast, setToast] = useState<Toast | null>(null);
  const toastTimer = useRef<number | undefined>(undefined);
  const showToast = useCallback((next: Toast) => {
    window.clearTimeout(toastTimer.current);
    setToast(next);
    // A toast with an action (Undo) stays long enough to use it.
    toastTimer.current = window.setTimeout(() => setToast(null), next.action ? 8000 : 4000);
  }, []);
  useEffect(() => () => window.clearTimeout(toastTimer.current), []);

  const [menu, setMenu] = useState<{
    card: ActivityFeedCard;
    anchor: HTMLButtonElement;
    top: number;
    left: number;
  } | null>(null);
  const menuRef = useRef<HTMLUListElement>(null);

  const [drawer, setDrawer] = useState<{ kind: DrawerKind; card: ActivityFeedCard } | null>(null);
  const [taskTypes, setTaskTypes] = useState<PicklistOption[] | null>(null);
  const [callOutcomes, setCallOutcomes] = useState<PicklistOption[] | null>(null);

  // Search as the user types (debounced), like the design's live filter.
  useEffect(() => {
    const id = window.setTimeout(() => setQ(query.trim()), 300);
    return () => window.clearTimeout(id);
  }, [query]);

  useEffect(() => {
    const id = ++request.current;
    setLoading(true);
    setError(null);
    listActivityFeed({
      types: type === 'all' ? undefined : [type],
      enrollment,
      q,
      limit: PAGE_SIZE,
    }).then(
      (page) => {
        if (id !== request.current) return;
        setNow(new Date());
        setCards(page.data);
        setNextCursor(page.nextCursor);
        setLoading(false);
      },
      (err: unknown) => {
        if (id !== request.current) return;
        setCards([]);
        setNextCursor(null);
        setError(errorText(err));
        setLoading(false);
      },
    );
  }, [type, enrollment, q, reload]);

  const loadMore = () => {
    if (!nextCursor || loadingMore) return;
    const id = request.current;
    setLoadingMore(true);
    listActivityFeed({
      types: type === 'all' ? undefined : [type],
      enrollment,
      q,
      cursor: nextCursor,
      limit: PAGE_SIZE,
    }).then(
      (page) => {
        setLoadingMore(false);
        if (id !== request.current) return;
        setCards((prev) => {
          const seen = new Set(prev.map((c) => c.id));
          return [...prev, ...page.data.filter((c) => !seen.has(c.id))];
        });
        setNextCursor(page.nextCursor);
      },
      (err: unknown) => {
        setLoadingMore(false);
        showToast({
          tone: 'warning',
          title: 'Could not load older activities',
          msg: errorText(err),
        });
      },
    );
  };

  const visible = useMemo(() => cards.filter((card) => !hidden.has(card.id)), [cards, hidden]);
  const groups = useMemo(() => groupCards(visible, now, timeZone), [visible, now, timeZone]);

  /* ---- more menu */
  useLayoutEffect(() => {
    if (!menu || !menuRef.current) return;
    const rect = menu.anchor.getBoundingClientRect();
    const height = menuRef.current.offsetHeight;
    const width = menuRef.current.offsetWidth;
    let top = rect.bottom + 4;
    if (top + height > window.innerHeight - 8) top = Math.max(8, rect.top - height - 4);
    const left = Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8));
    if (top !== menu.top || left !== menu.left) setMenu({ ...menu, top, left });
  }, [menu]);

  useEffect(() => {
    if (!menu) return;
    const close = (event: MouseEvent) => {
      if (!menuRef.current?.contains(event.target as Node)) setMenu(null);
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key !== 'Escape') return;
      menu.anchor.focus();
      setMenu(null);
    };
    const shut = () => setMenu(null);
    document.addEventListener('click', close);
    document.addEventListener('keydown', onKey);
    window.addEventListener('resize', shut);
    return () => {
      document.removeEventListener('click', close);
      document.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', shut);
    };
  }, [menu]);

  /* ---- card actions */
  const toggleNotify = (card: ActivityFeedCard) => {
    const on = toggleMute(card.groupKey);
    showToast({
      tone: 'success',
      title: on ? 'Turned on thread notifications' : 'Turned off thread notifications',
      msg: on
        ? 'Notifications for this thread have been turned back on'
        : 'Notifications for this thread have been turned off',
    });
  };

  const { confirm, dialog: confirmDialog } = useConfirm();
  /**
   * #496: asks first, then removes the card at once and saves it for this user (the API keeps
   * the activities); Undo in the toast brings it back. A failed save puts the card back.
   */
  const deleteBundle = async (card: ActivityFeedCard) => {
    const ok = await confirm({
      title: 'Delete activity bundle?',
      message:
        'It is removed from your Activity Feed only. The emails, meetings and other activities stay on their records.',
      confirmLabel: 'Delete',
      danger: true,
    });
    if (!ok) return;
    hide(card.id, false);
    try {
      await hideActivityBundle(card.groupKey, card.occurredAt);
    } catch (err) {
      unhide(card.id);
      showToast({ tone: 'warning', title: 'Not deleted', msg: errorText(err) });
      return;
    }
    showToast({
      tone: 'success',
      title: 'Activity bundle deleted',
      msg: 'The activity bundle was removed from your feed',
      action: {
        label: 'Undo',
        run: () => {
          setToast(null);
          restoreActivityBundle(card.groupKey).then(
            () => {
              unhide(card.id);
              showToast({ tone: 'success', title: 'Activity bundle restored' });
            },
            (err: unknown) =>
              showToast({ tone: 'warning', title: 'Not restored', msg: errorText(err) }),
          );
        },
      },
    });
  };

  const openDrawer = (kind: DrawerKind, card: ActivityFeedCard) => {
    if (kind === 'task' && taskTypes === null) {
      void listPicklistOptions({
        objectType: 'activity',
        field: 'taskType',
        includeArchived: false,
      }).then(
        (list) => setTaskTypes(list.filter((o) => o.field === 'taskType' && !o.archived)),
        () => setTaskTypes([]),
      );
    }
    if (kind === 'call' && callOutcomes === null) {
      void listPicklistOptions({
        objectType: 'activity',
        field: 'callOutcome',
        includeArchived: false,
      }).then(
        (list) => setCallOutcomes(list.filter((o) => o.field === 'callOutcome' && !o.archived)),
        () => setCallOutcomes([]),
      );
    }
    setDrawer({ kind, card });
  };

  const closeDrawer = () => setDrawer(null);
  const afterActivity = () => {
    closeDrawer();
    setReload((n) => n + 1);
  };

  const person = drawer?.card.contact ?? null;
  const contactId = person?.id ?? null;
  const contactEmail = person?.email?.trim().toLowerCase() ?? null;
  const recordName = person?.name ?? 'this contact';

  return (
    <div
      ref={rootRef}
      className="sw-page sw-activity-feed"
      data-sales-workspace=""
      data-sales-activity-feed=""
    >
      <header className="sw-header">
        <h1>Activity Feed</h1>
      </header>
      <div className="sw-schedule-body">
        <div className="sw-feed-toolbar">
          <div className="ep-search crm-w-md-75 crm-w-100">
            <input
              type="search"
              className="ep-search__input"
              data-feed-search=""
              placeholder="Search activities"
              autoComplete="off"
              aria-label="Search activities"
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === 'Escape' && query) setQuery('');
              }}
            />
            <SearchIcon />
          </div>
          <div className="sw-feed-filter-fields" aria-label="Filter activities">
            <FeedFilter
              id="sw-feed-activity-type"
              label="Activity type:"
              value={type}
              // Prospect visits and the Prospecting Agent have no data yet: not offered (HUB-709).
              options={TYPE_OPTIONS.filter((o) => !SOON_TYPES.has(o.value))}
              rootRef={rootRef}
              onChange={setType}
            />
            <FeedFilter
              id="sw-feed-enrollment"
              label="Sequence enrollment:"
              value={enrollment}
              options={ENROLLMENT_OPTIONS}
              rootRef={rootRef}
              onChange={setEnrollment}
            />
          </div>
        </div>
        <div id="sw-ep-feed" aria-busy={loading}>
          {!loading
            ? groups.map((group) => (
                <section key={group.section} className="ep-group" data-feed-group="">
                  <h3 className="ep-group__title">{group.section}</h3>
                  <ul className="ep-list">
                    {group.cards.map((card) => (
                      <FeedCard
                        key={card.id}
                        card={card}
                        now={now}
                        timeZone={timeZone}
                        notify={!muted.has(card.groupKey)}
                        menuOpen={menu?.card.id === card.id}
                        onBell={() => toggleNotify(card)}
                        onDelete={() => void deleteBundle(card)}
                        onAction={(kind) => openDrawer(kind, card)}
                        onMore={(anchor) => {
                          if (menu?.anchor === anchor) setMenu(null);
                          else {
                            const rect = anchor.getBoundingClientRect();
                            setMenu({ card, anchor, top: rect.bottom + 4, left: rect.left });
                          }
                        }}
                      />
                    ))}
                  </ul>
                </section>
              ))
            : null}
          <div className="ep-empty" data-feed-empty="" hidden={!loading && visible.length > 0}>
            <p data-feed-empty-text="">
              {loading
                ? 'Loading activities…'
                : (error ??
                  (!q && (type === 'email_open' || type === 'email_click') && trackingOff
                    ? 'Email opens and clicks are not recorded: turn on email tracking and set a tracking domain in Settings › Email.'
                    : emptyText(q)))}
            </p>
          </div>
        </div>
        <button
          type="button"
          className={cn(
            'btn-crm btn-crm--outline btn-crm--block ep-load-more',
            loadingMore && 'is-loading',
          )}
          data-feed-load-more=""
          hidden={loading || !nextCursor}
          onClick={loadMore}
        >
          <span>Load older activities</span>
          <span className="btn-crm__spinner" aria-hidden="true" />
        </button>
        {confirmDialog}
        <div className="ep-toasts" data-feed-toasts="" aria-live="polite">
          {toast ? (
            <div className={`ep-toast ep-toast--${toast.tone}`} role="status">
              <div className="ep-toast__body">
                <span className="ep-toast__title">{toast.title}</span>
                {toast.msg ? <span className="ep-toast__msg">{toast.msg}</span> : null}
              </div>
              {toast.action ? (
                <button type="button" className="link" onClick={toast.action.run}>
                  {toast.action.label}
                </button>
              ) : null}
              <button
                type="button"
                className="ep-close"
                aria-label="Close message"
                onClick={() => setToast(null)}
              >
                &times;
              </button>
            </div>
          ) : null}
        </div>
        <ul
          ref={menuRef}
          className="ep-menu ep-menu--sm"
          data-feed-more-menu=""
          role="menu"
          hidden={!menu}
          style={menu ? { top: menu.top, left: menu.left } : undefined}
        >
          <li>
            <button
              type="button"
              role="menuitem"
              data-feed-more="note"
              disabled={!menu?.card.contact?.id}
              onClick={() => {
                if (menu) openDrawer('note', menu.card);
                setMenu(null);
              }}
            >
              Create Note
            </button>
          </li>
          <li>
            <button
              type="button"
              role="menuitem"
              data-feed-more="schedule"
              disabled={!menu?.card.contact?.id}
              onClick={() => {
                if (menu) openDrawer('meeting', menu.card);
                setMenu(null);
              }}
            >
              Schedule
            </button>
          </li>
          <li>
            <button
              type="button"
              role="menuitem"
              data-feed-more="thread"
              data-feed-more-thread=""
              onClick={() => {
                if (menu) toggleNotify(menu.card);
                setMenu(null);
              }}
            >
              {menu && muted.has(menu.card.groupKey)
                ? 'Turn on thread notifications'
                : 'Turn off thread notifications'}
            </button>
          </li>
          <li>
            <button
              type="button"
              role="menuitem"
              data-feed-more="delete"
              onClick={() => {
                if (menu) void deleteBundle(menu.card);
                setMenu(null);
              }}
            >
              Delete activity bundle
            </button>
          </li>
        </ul>
      </div>

      {drawer?.kind === 'call' && contactId ? (
        // HUB-417: the same form as a record's quick Call, so snippets work in the call notes.
        <LogCallDrawer
          composer={composer}
          open
          onClose={closeDrawer}
          dial={{ name: recordName, phone: person?.phone ?? null }}
          link={{ type: 'contact', id: contactId }}
          recordName={recordName}
          outcomes={callOutcomes ?? []}
          timeZone={timeZone}
          onLogged={afterActivity}
        />
      ) : null}
      {drawer?.kind === 'email' ? (
        <SendEmailDrawer
          composer={composer}
          open
          onClose={closeDrawer}
          contactId={contactId ?? undefined}
          contactEmail={contactEmail}
          recipientOptions={
            contactEmail
              ? [
                  {
                    value: contactEmail,
                    label: `${recordName} (${contactEmail})`,
                    ...(contactId ? { contactId } : {}),
                  },
                ]
              : []
          }
          recordLink={contactId ? { type: 'contact', id: contactId } : undefined}
          recordName={recordName}
          signature={prefs.signature}
          onSent={afterActivity}
        />
      ) : null}
      {drawer?.kind === 'task' && contactId ? (
        <CreateTaskDrawer
          composer={composer}
          open
          onClose={closeDrawer}
          link={{ objectType: 'contact', id: contactId }}
          recordName={recordName}
          taskTypes={taskTypes ?? []}
          timeZone={timeZone}
          onCreated={afterActivity}
        />
      ) : null}
      {drawer?.kind === 'note' && contactId ? (
        <LogNoteDrawer
          composer={composer}
          open
          onClose={closeDrawer}
          link={{ type: 'contact', id: contactId }}
          recordName={recordName}
          recordSecondary={person?.email ?? null}
          onLogged={afterActivity}
        />
      ) : null}
      {drawer?.kind === 'meeting' && contactId ? (
        <ScheduleMeetingDrawer
          composer={composer}
          open
          onClose={closeDrawer}
          link={{ type: 'contact', id: contactId }}
          recordName={recordName}
          defaultAttendeeEmail={contactEmail}
          attendeeOptions={
            contactEmail ? [{ value: contactEmail, label: `${recordName} (${contactEmail})` }] : []
          }
          timeZone={timeZone}
          defaultMinutes={prefs.meetingMinutes}
          onScheduled={afterActivity}
        />
      ) : null}
    </div>
  );
}
