'use client';

import { Fragment, useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { createPortal } from 'react-dom';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { formatUserDate, readable, type ReadableContext } from '@/features/activities/readable';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { formatMoney } from '@/features/companies/ui/format';
import {
  getContact,
  getContactHistory,
  getContactTimeline,
  updateContact,
} from '@/features/contacts/api.client';
import type { Contact, TimelineItem, UpdateContactBody } from '@/features/contacts/types';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { listRecordLists, type RecordList } from '@/features/lists/api.client';
import { listLinkedRecords } from '@/features/objects/api.client';
import type { LinkedRecord } from '@/features/objects/types';
import { useOwners } from '@/features/owners/useOwners';
import { PropertyHistoryDrawer } from '@/features/property-history/PropertyHistoryDrawer';
import { contactHistoryDescriber } from '@/features/property-history/records';
import { follow, getFollow, unfollow } from '@/features/record-tools/api.client';
import { listPicklistOptions, type PicklistOption } from '@/features/picklists/api.client';
import type { RegionFormat } from '@/features/settings/types';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { NO_VALUE } from '../segment';
import {
  PROPERTY_DOCS_HREF,
  aboutFields,
  activityGroups,
  activityIcon,
  canEditContact,
  copyableValue,
  googleSearchUrl,
  internalValue,
  membershipTypeText,
  recentActivities,
  previewCompany,
  previewInitial,
  previewName,
  previewSub,
  shownCompanies,
  type AboutField,
  type AboutFieldKey,
  type CompanyFilter,
  type CompanySort,
} from '../preview';
import { EditEmailModal, EditPhoneModal } from './EditContactModals';
import { EventPreviewDrawer } from './EventPreviewDrawer';
import { SegDrawer, SegDropdown, useEscapeLayer } from './primitives';
import {
  canEditPropertySettings,
  canOpenPropertySettings,
} from '@/features/permission-sets/property-settings';

/** Recent activities shown (SEG2a C2a): the newest items of the timeline. */
const RECENT_SHOWN = 10;

/** One `.lp-pv__sec` accordion (PHP:2589-3415); `aria-expanded` drives the CSS (JS:3088-3095). */
function Section({
  title,
  defaultOpen,
  tools,
  children,
}: {
  title: string;
  defaultOpen: boolean;
  tools?: React.ReactNode;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <section className="lp-pv__sec">
      <div className="lp-pv__sh-row">
        <h3>
          <button
            type="button"
            className="lp-pv__sh"
            aria-expanded={open}
            onClick={(e) => {
              e.preventDefault();
              setOpen((v) => !v);
            }}
          >
            <CrmIcon name="chevron-down" className="lp-i iconSize-14" />
            <span>{title}</span>
          </button>
        </h3>
        {tools ? <div className="lp-pv__sh-tools">{tools}</div> : null}
      </div>
      <div className="lp-pv__fields">{children}</div>
    </section>
  );
}

function EmptyState({ icon, text }: { icon: string; text: string }) {
  return (
    <div className="vcs-empty-state">
      <div className="vcs-empty-icon">
        <CrmIcon name={icon} className="iconSize-20" />
      </div>
      <p className="crm-text-muted crm-fs-8 crm-mb-0">{text}</p>
    </div>
  );
}

function PaymentsText({ text }: { text: string }) {
  return <p className="crm-text-muted crm-fs-8 crm-mb-2">{text}</p>;
}

/** The activity toolbar of Recent / Upcoming activities (PHP:2845-2893, 2953-2995). */
function ActivityToolbar() {
  const checks: Array<[string, boolean]> = [
    ['Calls', true],
    ['Emails', true],
    ['Notes', true],
    ['Tasks', false],
    ['Meetings', false],
  ];
  return (
    <div className="vcs-act-toolbar">
      <input type="search" className="vcs-act-search" placeholder="Search activities" />
      <SegDropdown
        toggleClassName="lp-btn lp-btn--outline lp-btn--sm"
        menuClassName="dropdown__menu--right crm-p-2 vcs-dd-menu-w200"
        toggle={
          <>
            <span>Activity</span>
            <CrmIcon name="chevron-down" className="iconSize-12" />
          </>
        }
      >
        {checks.map(([l, on], i) => (
          <label key={l} className={i < checks.length - 1 ? 'lp-check crm-mb-1' : 'lp-check'}>
            <input type="checkbox" defaultChecked={on} /> <span>{l}</span>
          </label>
        ))}
      </SegDropdown>
    </div>
  );
}

type Anchor = { top: number; left: number };
type PickerKind = 'owner' | 'lifecycle' | 'leadStatus';

const CHECK = (
  <svg
    className="lp-ce-opt__ck"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2.5"
  >
    <polyline points="20 6 9 17 4 12" />
  </svg>
);

/** The `.vcs-floating-picker` of owner, lifecycle stage and lead status (JS:3826-4121). */
function FloatingPicker({
  kind,
  anchor,
  current,
  options,
  onPick,
  onClose,
}: {
  kind: PickerKind;
  anchor: Anchor;
  current: string | null;
  options: Array<{ value: string | null; label: string }>;
  onPick: (value: string | null, label: string) => void;
  onClose: () => void;
}) {
  const [q, setQ] = useState('');
  useEscapeLayer(true, onClose);
  useEffect(() => {
    const onDown = (e: MouseEvent) => {
      if (!(e.target as HTMLElement).closest?.('.vcs-floating-picker')) onClose();
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [onClose]);
  const meta = {
    owner: { ph: 'Search owners', inputId: 'vcsOwnerSearch', listId: 'vcsOwnerList' },
    lifecycle: { ph: 'Search stages', inputId: 'vcsLifecycleSearch', listId: 'vcsLifecycleList' },
    leadStatus: {
      ph: 'Search statuses',
      inputId: 'vcsLeadStatusSearchCompact',
      listId: 'vcsLeadStatusItemsCompact',
    },
  }[kind];
  const shown = options.filter((o) => o.label.toLowerCase().includes(q.toLowerCase().trim()));
  return (
    <div className="vcs-floating-picker is-open" style={{ top: anchor.top, left: anchor.left }}>
      <div className="lp-ce-pick__q" style={{ padding: '4px 4px 6px' }}>
        <input
          type="search"
          className="lp-input"
          placeholder={meta.ph}
          style={{ width: '100%', height: 32, fontSize: 13 }}
          id={meta.inputId}
          autoComplete="off"
          autoFocus
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
      </div>
      <div
        className="lp-ce-pick__list"
        id={meta.listId}
        role="listbox"
        style={{ maxHeight: 200, overflowY: 'auto' }}
      >
        {shown.map((o) => {
          const on = o.value === current;
          const none = kind === 'owner' && o.value === null;
          return (
            <button
              key={o.value ?? '__none'}
              type="button"
              role="option"
              aria-selected={on}
              className={`lp-ce-opt ${on ? 'is-on' : ''} ${none ? 'is-none' : ''}`}
              onClick={() => onPick(o.value, o.label)}
            >
              {kind === 'owner' ? (
                <span
                  className="vcs-owner-avatar"
                  style={{
                    width: 22,
                    height: 22,
                    fontSize: 11,
                    display: 'inline-grid',
                    placeItems: 'center',
                    borderRadius: '50%',
                    background: 'var(--brand-soft)',
                    color: 'var(--brand)',
                    marginRight: 6,
                    flexShrink: 0,
                  }}
                >
                  {none ? '-' : o.label.charAt(0).toUpperCase()}
                </span>
              ) : null}
              <span
                style={{
                  flex: 1,
                  minWidth: 0,
                  textOverflow: 'ellipsis',
                  overflow: 'hidden',
                  whiteSpace: 'nowrap',
                }}
              >
                {o.label}
              </span>
              {on ? CHECK : null}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/**
 * The field `⋯` menu (`.vcs-field-menu`, JS:3157-3196). SEG2a C3: Copy internal value works;
 * Add property documentation links the properties settings, only for those who may open them
 * (`docsHref` null otherwise, the user's call 17 Nov).
 */
export function FieldMenu({
  anchor,
  onCopy,
  onCopyInternal,
  docsHref,
  onClose,
}: {
  anchor: Anchor;
  onCopy: () => void;
  onCopyInternal: () => void;
  docsHref: string | null;
  onClose: () => void;
}) {
  useEscapeLayer(true, onClose);
  useEffect(() => {
    const onDown = (e: MouseEvent) => {
      const t = e.target as HTMLElement;
      if (!t.closest?.('.vcs-field-menu') && !t.closest?.('[data-field-more-btn]')) onClose();
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [onClose]);
  const svg = (children: React.ReactNode) => (
    <span className="vcs-field-menu__icon">
      <svg
        viewBox="0 0 24 24"
        width="14"
        height="14"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        {children}
      </svg>
    </span>
  );
  return (
    <div className="vcs-field-menu" role="menu" style={{ left: anchor.left, top: anchor.top }}>
      <button
        type="button"
        className="vcs-field-menu__item"
        role="menuitem"
        data-field-act="copy"
        onClick={onCopy}
      >
        {svg(
          <>
            <rect x="8" y="8" width="12" height="12" rx="2" />
            <path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2" />
          </>,
        )}
        <span>Copy value</span>
      </button>
      <button
        type="button"
        className="vcs-field-menu__item"
        role="menuitem"
        data-field-act="copy-internal"
        onClick={onCopyInternal}
      >
        {svg(
          <>
            <rect x="9" y="9" width="11" height="11" rx="2" />
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
            <path d="M12 12h5M12 15h3" />
          </>,
        )}
        <span>Copy internal value</span>
      </button>
      {docsHref ? (
        <a
          href={docsHref}
          target="_blank"
          rel="noopener"
          className="vcs-field-menu__item"
          role="menuitem"
          data-field-act="doc"
          onClick={onClose}
        >
          {svg(
            <path d="M2 5h7a3 3 0 0 1 3 3v12a2 2 0 0 0-2-2H2zM22 5h-7a3 3 0 0 0-3 3v12a2 2 0 0 1 2-2h8z" />,
          )}
          <span>Add property documentation</span>
        </a>
      ) : null}
    </div>
  );
}

/** Where the field menu goes under its button (JS:3201-3215). */
function menuAnchor(el: HTMLElement, width: number, height: number): Anchor {
  const r = el.getBoundingClientRect();
  let left = r.right - width;
  if (left < 8) left = 8;
  if (left + width > window.innerWidth - 8) left = window.innerWidth - width - 8;
  let top = r.bottom + 6;
  if (top + height > window.innerHeight - 8) top = Math.max(8, r.top - height - 6);
  return { top, left };
}

/** Where a picker goes under its value (JS:3871-3879). */
function pickerAnchor(el: HTMLElement, width: number, height: number): Anchor {
  const r = el.getBoundingClientRect();
  const left = Math.max(8, Math.min(r.left, window.innerWidth - width - 12));
  let top = r.bottom + 4;
  if (top + height > window.innerHeight && r.top - height >= 10) top = r.top - height;
  return { top, left };
}

/**
 * SEG2a C2a: Recent activities' cards (PHP:2885-2930): a `vcs-timeline-month` heading per month,
 * then one `vcs-act-card` per item, in the words of the record pages (`readable`). Collapse all
 * hides them (JS:3098-3109).
 */
export function RecentActivityList({
  items,
  ctx,
  collapsed,
}: {
  items: TimelineItem[];
  ctx: ReadableContext;
  collapsed: boolean;
}) {
  const hidden = collapsed ? { display: 'none' } : undefined;
  return (
    <>
      {activityGroups(items, { region: ctx.region, timeZone: ctx.timeZone }).map((g, gi) => (
        <Fragment key={g.month}>
          <div
            className={gi === 0 ? 'vcs-timeline-month' : 'vcs-timeline-month crm-mt-3'}
            style={hidden}
          >
            {g.month}
          </div>
          {g.items.map((item) => {
            const r = readable(item, ctx);
            return (
              <div className="vcs-act-card" key={item.id} style={hidden}>
                <div className="vcs-act-head">
                  <CrmIcon name={activityIcon(item.type)} className="iconSize-14" />
                  <span>{r.title}</span>
                  <span className="crm-text-muted crm-fs-8 crm-ms-auto">
                    {formatUserDate(item.occurredAt, {
                      region: ctx.region,
                      timeZone: ctx.timeZone,
                      time: true,
                    })}
                  </span>
                </div>
                {r.sentence ? <div className="vcs-act-body">{r.sentence}</div> : null}
              </div>
            );
          })}
        </Fragment>
      ))}
    </>
  );
}

const DESIGN_TITLES: Partial<Record<AboutFieldKey, { attr: string; title: string }>> = {
  email: { attr: 'data-drawer-email', title: 'Click to edit email' },
  phone: { attr: 'data-drawer-phone', title: 'Click to edit phone number' },
  owner: { attr: 'data-drawer-owner', title: 'Click to change contact owner' },
  lifecycle: { attr: 'data-drawer-lifecycle', title: 'Click to change lifecycle stage' },
  leadStatus: { attr: 'data-drawer-leadstatus', title: 'Click to change lead status' },
};
const VALUE_ATTR: Partial<Record<AboutFieldKey, string>> = {
  lastActivity: 'data-drawer-lastactivity',
  createDate: 'data-drawer-createdate',
};

/**
 * The loaded drawer (PHP:2472-3417) plus its modals and menus. Exported so tests can render it
 * with data; the page uses `ContactPreviewDrawer`.
 */
export function ContactPreviewView({
  contact,
  lists,
  canEdit,
  picklists,
  timeZone,
  onClose,
  onChanged,
  onContact,
  following = null,
  onFollow,
  activities = [],
  activitiesFailed = false,
  events = [],
  customDefs = [],
  canManageSettings = false,
  canOpenProperties = false,
  region = 'us',
}: {
  contact: Contact;
  /** The lists the contact is in; `null` until loaded (or when the call failed). */
  lists: RecordList[] | null;
  canEdit: boolean;
  picklists: PicklistOption[];
  timeZone?: string;
  onClose: () => void;
  onChanged: () => void;
  onContact: (contact: Contact) => void;
  /** Whether I follow the contact (GET /follows); `null` until known. */
  following?: boolean | null;
  /** Actions › Follow / Unfollow; the item is left out without it. */
  onFollow?: () => void;
  /** SEG2a C2a: the contact's timeline, newest first; `null` until loaded. */
  activities?: TimelineItem[] | null;
  /** The timeline read failed. */
  activitiesFailed?: boolean;
  /** SEG2a C5: the contact's events; `null` until loaded (`[]` after a failed read). */
  events?: LinkedRecord[] | null;
  /** The contact's custom fields, for the history's and activities' labels. */
  customDefs?: CustomPropertyDefinition[];
  /** May change properties (Edit property settings): Add property documentation. */
  canManageSettings?: boolean;
  /** May open `/settings/properties` (P1 `canOpenPropertySettings`): the history's Manage properties. */
  canOpenProperties?: boolean;
  region?: RegionFormat;
}) {
  const toast = useToast();
  const [modal, setModal] = useState<'email' | 'phone' | null>(null);
  const [picker, setPicker] = useState<{ kind: PickerKind; anchor: Anchor } | null>(null);
  const [fieldMenu, setFieldMenu] = useState<{ key: AboutFieldKey; anchor: Anchor } | null>(null);
  const [actsCollapsed, setActsCollapsed] = useState(false);
  const [attrModel, setAttrModel] = useState('Linear');
  const [companyFilter, setCompanyFilter] = useState<CompanyFilter>('all');
  const [companySort, setCompanySort] = useState<CompanySort>('assoc');
  /** SEG2a C2b: master's property history drawer, every field (JS:4174-4185). */
  const [historyOpen, setHistoryOpen] = useState(false);
  /** SEG2a C5: the event shown in the event drawer. */
  const [eventShown, setEventShown] = useState<{ id: string; name: string } | null>(null);
  // CrmModal closes on any Escape: as a layer here, that Escape leaves this drawer open.
  useEscapeLayer(historyOpen, () => setHistoryOpen(false));
  // Up front: Recent activities names owners in owner changes (shared, cached read).
  const { owners } = useOwners(true);
  const describeHistory = useMemo(
    () =>
      contactHistoryDescriber({
        defs: customDefs,
        owners,
        picklists,
        formatDateTime: (iso) =>
          formatUserDate(iso, { region, timeZone: timeZone ?? 'UTC', time: true }),
      }),
    [customDefs, owners, picklists, region, timeZone],
  );
  const openHistory = () => {
    setFieldMenu(null);
    setHistoryOpen(true);
  };

  const id = contact.id;
  const href = `/contacts/${id}`;
  const name = previewName(contact);
  const sub = previewSub(contact);
  const fields = aboutFields(contact, { timeZone, picklists });
  const companies = shownCompanies(contact.companies ?? [], companyFilter, companySort);
  const shownActs = activities ? recentActivities(activities) : null;
  const allCompanies = contact.companies?.length ?? 0;

  const saved = (updated: Contact) => {
    onContact(updated);
    onChanged();
  };

  const pick = async (kind: PickerKind, value: string | null, label: string) => {
    setPicker(null);
    const body: UpdateContactBody =
      kind === 'owner'
        ? { ownerId: value }
        : kind === 'lifecycle'
          ? { lifecycleStage: value }
          : { leadStatus: value };
    try {
      const updated = await updateContact(id, body);
      toast(
        kind === 'owner'
          ? `Contact owner updated to ${label}`
          : kind === 'lifecycle'
            ? `Lifecycle stage changed to ${label}`
            : `Lead status changed to ${label}`,
        'success',
      );
      saved(updated);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const pickerOptions = (kind: PickerKind): Array<{ value: string | null; label: string }> => {
    if (kind === 'owner') {
      return [
        ...owners.filter((o) => o.active).map((o) => ({ value: o.userId, label: o.name })),
        { value: null, label: 'No owner' },
      ];
    }
    const field = kind === 'lifecycle' ? 'lifecycleStage' : 'leadStatus';
    return picklists
      .filter((o) => o.field === field && !o.archived)
      .map((o) => ({ value: o.value, label: o.label }));
  };
  const pickerCurrent = (kind: PickerKind) =>
    kind === 'owner'
      ? (contact.owner?.id ?? null)
      : kind === 'lifecycle'
        ? contact.lifecycleStage
        : contact.leadStatus;

  /** A click on an editable field row opens its modal or picker (JS:4124-4171). */
  const onFieldClick = (key: AboutFieldKey) => (e: React.MouseEvent<HTMLDivElement>) => {
    const t = e.target as HTMLElement;
    if (t.closest('.lp-pv__hover-tools, a')) return;
    if (!canEdit) return;
    if (key === 'email') setModal('email');
    else if (key === 'phone') setModal('phone');
    else if (key === 'owner' || key === 'lifecycle' || key === 'leadStatus') {
      e.preventDefault();
      e.stopPropagation();
      const val = e.currentTarget.querySelector<HTMLElement>('.lp-pv__val') ?? e.currentTarget;
      const kind: PickerKind = key;
      setFieldMenu(null);
      setPicker({ kind, anchor: pickerAnchor(val, key === 'leadStatus' ? 240 : 270, 240) });
    }
  };

  const copyField = () => {
    const field = fields.find((f) => f.key === fieldMenu?.key);
    setFieldMenu(null);
    const text = copyableValue(field?.value ?? '');
    const failed = () => toast("Couldn't copy to the clipboard.", 'danger');
    if (!navigator.clipboard) return failed();
    navigator.clipboard
      .writeText(text)
      .then(() => toast(`Copied to clipboard: ${text}`, 'success'), failed);
  };

  /** SEG2a C3a: JS:3256-3279, with the design's toast. */
  const copyInternal = () => {
    const key = fieldMenu?.key;
    setFieldMenu(null);
    if (!key) return;
    const failed = () => toast("Couldn't copy to the clipboard.", 'danger');
    if (!navigator.clipboard) return failed();
    navigator.clipboard
      .writeText(internalValue(key, contact))
      .then(() => toast('Copied internal value to clipboard', 'success'), failed);
  };

  const readableCtx: ReadableContext = useMemo(
    () => ({
      recordName: name === NO_VALUE ? '' : name,
      describe: describeHistory,
      region,
      timeZone: timeZone ?? 'UTC',
      objectLabel: 'Contact',
    }),
    [name, describeHistory, region, timeZone],
  );

  const fieldRow = (f: AboutField) => {
    const design = DESIGN_TITLES[f.key];
    // SEG1 A5: the hint and pointer only where the click edits (`onFieldClick` needs `canEdit`).
    const valueProps: Record<string, unknown> = design
      ? canEdit
        ? { [design.attr]: '', style: { cursor: 'pointer' }, title: design.title }
        : { [design.attr]: '' }
      : VALUE_ATTR[f.key]
        ? { [VALUE_ATTR[f.key]!]: '' }
        : {};
    const menuOpen = fieldMenu?.key === f.key;
    return (
      <div className="lp-pv__field" data-field={f.key} key={f.key} onClick={onFieldClick(f.key)}>
        <span className="lp-pv__label">{f.label}</span>
        <div className="lp-pv__field-row">
          <div className="lp-pv__val" {...valueProps}>
            {f.pill ? (
              <span className="badge badge--pill badge--subtle" data-drawer-eventsource="">
                {f.value}
              </span>
            ) : (
              f.value
            )}
          </div>
          <div className={menuOpen ? 'lp-pv__hover-tools is-active' : 'lp-pv__hover-tools'}>
            <button
              type="button"
              className="lp-icon-btn lp-icon-btn--sm"
              title="View property history"
              onClick={openHistory}
            >
              <CrmIcon name="clock" className="iconSize-14" />
            </button>
            {f.key === 'email' ? (
              <a
                href={`mailto:${contact.email ?? ''}`}
                className="lp-icon-btn lp-icon-btn--sm"
                title="Send email"
                data-drawer-email-link=""
              >
                <CrmIcon name="mail" className="iconSize-14" />
              </a>
            ) : null}
            <button
              type="button"
              className="lp-icon-btn lp-icon-btn--sm"
              title="More options"
              data-field-more-btn=""
              aria-haspopup="menu"
              aria-expanded={menuOpen}
              onClick={(e) => {
                e.stopPropagation();
                if (menuOpen) setFieldMenu(null);
                else {
                  setPicker(null);
                  setFieldMenu({ key: f.key, anchor: menuAnchor(e.currentTarget, 230, 116) });
                }
              }}
            >
              <CrmIcon name="more-horizontal" className="iconSize-14" />
            </button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <>
      <SegDrawer
        open
        onClose={onClose}
        label="Contact preview"
        id="vcsSideDrawer"
        className="lp-side--preview"
      >
        <header className="lp-side__head vcs-drawer-head">
          <h2 className="lp-side__title crm-fs-5 crm-fw-700 crm-mb-0" data-drawer-name="">
            {name}
          </h2>
          <div className="lp-side__tools">
            <button
              type="button"
              className="lp-icon-btn"
              id="vcsDrawerClose"
              aria-label="Close preview"
              onClick={onClose}
            >
              <CrmIcon name="x" className="iconSize-16" />
            </button>
          </div>
        </header>

        <div className="vcs-drawer-subbar">
          <Link className="vcs-drawer-rec-link" href={href} data-drawer-record-link="">
            View record
          </Link>
          <SegDropdown
            toggleClassName="lp-btn lp-btn--outline lp-btn--sm"
            menuClassName="dropdown__menu--right vcs-actions-menu"
            toggle={
              <>
                <span>Actions</span>
                <CrmIcon name="chevron-down" className="iconSize-12" />
              </>
            }
          >
            {onFollow ? (
              <button
                type="button"
                className="dropdown__item"
                data-drawer-action="follow"
                onClick={onFollow}
              >
                {following ? 'Unfollow' : 'Follow'}
              </button>
            ) : null}
            <button
              type="button"
              className="dropdown__item"
              data-drawer-action="prop-history"
              onClick={openHistory}
            >
              View property history
            </button>
            <a
              href={googleSearchUrl(name === NO_VALUE ? '' : name, previewCompany(contact))}
              target="_blank"
              rel="noopener"
              className="dropdown__item crm-d-flex crm-align-items-center crm-justify-content-between"
              data-drawer-action="search-google"
            >
              <span>Search in Google</span>
              <CrmIcon name="external" className="iconSize-12" />
            </a>
          </SegDropdown>
        </div>

        {canEdit ? null : (
          <div className="vcs-drawer-alert">
            <CrmIcon name="info" className="iconSize-16" />
            <span>Your permissions don&apos;t allow you to edit this record.</span>
          </div>
        )}

        <div className="lp-side__body">
          <div className="lp-pv__id">
            <span className="lp-av lp-av--lg lp-av--neutral" id="vcsDrawerAvatar">
              {previewInitial(name)}
            </span>
            <div className="lp-pv__copy">
              <h2 className="lp-pv__name" data-drawer-name="">
                <Link href={href}>{name}</Link>
              </h2>
              <p className="lp-pv__sub" data-drawer-sub="">
                {sub}
              </p>
              <p className="lp-pv__mail">
                {contact.email ? (
                  <a
                    href={`mailto:${contact.email}`}
                    className="vcs-link-action crm-d-inline-flex crm-align-items-center crm-gap-1"
                    data-drawer-email-link=""
                  >
                    <span data-drawer-email="">{contact.email}</span>
                    <CrmIcon name="external" className="iconSize-12" />
                  </a>
                ) : (
                  <span data-drawer-email="">{NO_VALUE}</span>
                )}
              </p>
            </div>
          </div>

          {/* 1. About this contact */}
          <Section
            title="About this contact"
            defaultOpen
            tools={
              <>
                <SegDropdown
                  toggleClassName="vcs-link-action crm-d-flex crm-align-items-center crm-gap-1"
                  menuClassName="dropdown__menu--right vcs-about-actions-menu"
                  toggle={
                    <>
                      <span>Actions</span>
                      <CrmIcon name="chevron-down" className="iconSize-10" />
                    </>
                  }
                >
                  <button
                    type="button"
                    className="dropdown__item"
                    data-about-action="prop-history"
                    onClick={openHistory}
                  >
                    View property history
                  </button>
                </SegDropdown>
              </>
            }
          >
            {fields.map(fieldRow)}
          </Section>

          {/* 2. Pinned activity */}
          <Section title="Pinned activity" defaultOpen>
            <EmptyState icon="pin" text="There is no pinned activity on this record." />
          </Section>

          {/* 3. Recent activities: the contact's timeline (SEG2a C2a) */}
          <Section
            title="Recent activities"
            defaultOpen
            tools={
              <button
                type="button"
                className="vcs-link-action crm-fs-8"
                data-vcs-toggle-acts=""
                onClick={(e) => {
                  e.stopPropagation();
                  setActsCollapsed((v) => !v);
                }}
              >
                {actsCollapsed ? 'Expand all' : 'Collapse all'}
              </button>
            }
          >
            <ActivityToolbar />
            {activitiesFailed ? (
              <p className="crm-text-muted crm-fs-8 crm-mb-0">Couldn&apos;t load activities.</p>
            ) : shownActs === null ? null : shownActs.length === 0 ? (
              <EmptyState
                icon="search"
                text="No activities match the current filters. Change filters to broaden your search."
              />
            ) : (
              <RecentActivityList items={shownActs} ctx={readableCtx} collapsed={actsCollapsed} />
            )}
          </Section>

          {/* 4. Upcoming activities */}
          <Section
            title="Upcoming activities"
            defaultOpen={false}
            tools={
              <button type="button" className="vcs-link-action crm-fs-8">
                Collapse all
              </button>
            }
          >
            <ActivityToolbar />
            <EmptyState
              icon="search"
              text="No activities match the current filters. Change filters to broaden your search."
            />
          </Section>

          {/* 5. Contacts */}
          <Section title="Contacts" defaultOpen={false}>
            <EmptyState icon="user" text="See the people associated with this record." />
          </Section>

          {/* 6. Companies: the contact's real companies */}
          <Section
            title={`Companies (${allCompanies})`}
            defaultOpen
            tools={
              <>
                <SegDropdown
                  toggleClassName="lp-btn lp-btn--outline lp-btn--sm vcs-btn-mini"
                  toggle={
                    <>
                      <span>Filters</span>
                      <CrmIcon name="chevron-down" className="iconSize-10" />
                    </>
                  }
                >
                  <button
                    type="button"
                    className={
                      companyFilter === 'all' ? 'dropdown__item is-selected' : 'dropdown__item'
                    }
                    onClick={() => setCompanyFilter('all')}
                  >
                    All companies
                  </button>
                  <button
                    type="button"
                    className={
                      companyFilter === 'primary' ? 'dropdown__item is-selected' : 'dropdown__item'
                    }
                    onClick={() => setCompanyFilter('primary')}
                  >
                    Primary company only
                  </button>
                </SegDropdown>
                <SegDropdown
                  toggleClassName="lp-btn lp-btn--outline lp-btn--sm vcs-btn-mini"
                  toggle={
                    <>
                      <span>Sort</span>
                      <CrmIcon name="chevron-down" className="iconSize-10" />
                    </>
                  }
                >
                  <button
                    type="button"
                    className={
                      companySort === 'assoc' ? 'dropdown__item is-selected' : 'dropdown__item'
                    }
                    onClick={() => setCompanySort('assoc')}
                  >
                    Association date
                  </button>
                  <button
                    type="button"
                    className={
                      companySort === 'name' ? 'dropdown__item is-selected' : 'dropdown__item'
                    }
                    onClick={() => setCompanySort('name')}
                  >
                    Company name (A-Z)
                  </button>
                </SegDropdown>
              </>
            }
          >
            {allCompanies === 0 ? (
              <EmptyState
                icon="briefcase"
                text="See the businesses or organizations associated with this record."
              />
            ) : (
              <>
                {companies.map((c, i) => (
                  <div
                    className={i === 0 ? 'vcs-assoc-card' : 'vcs-assoc-card crm-mt-2'}
                    key={c.id}
                  >
                    <div className="crm-d-flex crm-align-items-center crm-gap-2">
                      <span className={`lp-av lp-av--sm lp-av--sq lp-av--c${i % 5}`}>
                        {(c.name || '?').charAt(0).toUpperCase()}
                      </span>
                      <div>
                        <div className="crm-d-flex crm-align-items-center crm-gap-1">
                          <strong data-drawer-company-name="">{c.name}</strong>
                          {c.isPrimary ? (
                            <span className="badge badge--solid-info crm-fs-8">Primary</span>
                          ) : null}
                        </div>
                        <small className="crm-text-muted crm-d-block">
                          Company Domain Name:{' '}
                          <span data-drawer-company-domain="">{c.domain || NO_VALUE}</span>
                        </small>
                        <small className="crm-text-muted crm-d-block">
                          Phone Number: <span data-drawer-company-phone="">{NO_VALUE}</span>
                        </small>
                      </div>
                    </div>
                    <Link
                      className="lp-icon-btn lp-icon-btn--sm"
                      title="Preview company"
                      href={`/companies/${c.id}`}
                    >
                      <CrmIcon name="external" className="iconSize-12" />
                    </Link>
                  </div>
                ))}
                <Link
                  href={href}
                  className="vcs-link-action crm-fs-8 crm-fw-600 crm-mt-2 crm-d-block"
                >
                  View all associated Companies ({allCompanies})
                </Link>
              </>
            )}
          </Section>

          {/* 7. Deals */}
          <Section title={`Deals (${contact.deals?.length ?? 0})`} defaultOpen={false}>
            {contact.deals?.length ? (
              // SEG1 A2 (the user's call, 16 Nov): the deals in the Company card's markup.
              contact.deals.map((d, i) => (
                <div className={i === 0 ? 'vcs-assoc-card' : 'vcs-assoc-card crm-mt-2'} key={d.id}>
                  <div className="crm-d-flex crm-align-items-center crm-gap-2">
                    <span className={`lp-av lp-av--sm lp-av--sq lp-av--c${i % 5}`}>
                      {(d.name || '?').charAt(0).toUpperCase()}
                    </span>
                    <div>
                      <strong data-drawer-deal-name="">{d.name}</strong>
                      <small className="crm-text-muted crm-d-block">
                        Deal stage: <span>{d.stage.name}</span>
                      </small>
                      <small className="crm-text-muted crm-d-block">
                        Amount:{' '}
                        <span>{d.amount ? formatMoney(d.amount, d.currency) : NO_VALUE}</span>
                      </small>
                    </div>
                  </div>
                  <Link
                    className="lp-icon-btn lp-icon-btn--sm"
                    title="Preview deal"
                    href={`/deals/${d.id}`}
                  >
                    <CrmIcon name="external" className="iconSize-12" />
                  </Link>
                </div>
              ))
            ) : (
              <EmptyState
                icon="dollar-sign"
                text="Track the revenue opportunities associated with this record."
              />
            )}
          </Section>

          {/* 8. Tickets */}
          <Section title="Tickets" defaultOpen={false}>
            <EmptyState
              icon="help-circle"
              text="Track customer requests associated with this record."
            />
          </Section>

          {/* 9. Subscriptions */}
          <Section title="Subscriptions" defaultOpen={false}>
            <PaymentsText text="Automatic subscription management and recurring billing from this record." />
          </Section>

          {/* 10. Payments */}
          <Section title="Payments" defaultOpen={false}>
            <PaymentsText text="Track payments associated with this record. A payment is created when a customer pays or a recurring payment is processed through CRM." />
          </Section>

          {/* 11. Payment links */}
          <Section title="Payment links" defaultOpen={false}>
            <PaymentsText text="Add a payment link to accept a payment and associate it with this record." />
          </Section>

          {/* 12. Attachments */}
          <Section title="Attachments" defaultOpen={false}>
            <p className="crm-text-muted crm-fs-8 crm-mb-0">
              See the files attached to your activities or uploaded to this record.
            </p>
          </Section>

          {/* 13. Contact create attribution: an empty chart area, no Chart.js */}
          <Section title="Contact create attribution" defaultOpen>
            <div className="crm-mb-3">
              <label className="lp-pv__label crm-mb-1 crm-d-block" htmlFor="vcsAttrModelBtn">
                Attribution model:
              </label>
              <SegDropdown
                className="crm-w-100"
                toggleClassName="form-select form-select--sm crm-w-100 crm-d-flex crm-align-items-center crm-justify-content-between"
                toggleId="vcsAttrModelBtn"
                menuClassName="crm-w-100"
                toggle={
                  <>
                    <span id="vcsAttrModelVal">{attrModel}</span>
                    <CrmIcon name="chevron-down" className="iconSize-12" />
                  </>
                }
              >
                {['Linear', 'First touch', 'Last touch', 'Full path', 'U-shaped', 'W-shaped'].map(
                  (m) => (
                    <button
                      key={m}
                      type="button"
                      className={m === attrModel ? 'dropdown__item is-selected' : 'dropdown__item'}
                      data-val={m}
                      onClick={() => setAttrModel(m)}
                    >
                      {m}
                    </button>
                  ),
                )}
              </SegDropdown>
            </div>
            <div className="vcs-attr-card">
              <div className="crm-d-flex crm-align-items-center crm-gap-2 crm-mb-3">
                <span className="vcs-attr-pill">All time</span>
                <span className="vcs-attr-pill">Filters</span>
              </div>
              <div className="vcs-attr-chart-box">
                <canvas id="vcsAttributionChart" width="160" height="160" />
              </div>
            </div>
          </Section>

          {/* 14. Segment memberships: GET /lists/memberships */}
          <Section
            title="Segment memberships"
            defaultOpen
            tools={
              <Link href="/lists" className="vcs-link-action crm-fs-8">
                Manage
              </Link>
            }
          >
            <p className="crm-text-muted crm-fs-8 crm-mb-2">
              <span data-drawer-name-inline="">{name}</span> is a member of{' '}
              <strong>{lists ? lists.length : NO_VALUE}</strong> segments.
            </p>
            {(lists ?? []).map((l) => (
              <div className="lp-pv__assoc" key={l.listId}>
                <span className="lp-av lp-av--sm lp-av--c4">
                  <CrmIcon name="list" className="iconSize-16" />
                </span>
                <span>
                  <strong>
                    <Link href={`/lists/${l.listId}`}>{l.name}</Link>
                  </strong>
                  <small>{membershipTypeText(l.listType)}</small>
                </span>
              </div>
            ))}
          </Section>

          {/* 15. Invoices */}
          <Section title="Invoices" defaultOpen={false}>
            <PaymentsText text="Send your customer a request for payment and associate it with this record." />
          </Section>

          {/* 16. Workflow memberships */}
          <Section
            title="Workflow memberships"
            defaultOpen={false}
            tools={
              <Link href="/workflows" className="vcs-link-action crm-fs-8">
                Manage
              </Link>
            }
          >
            <p className="crm-text-muted crm-fs-8 crm-mb-0">
              Use workflows to automate actions for this record.
            </p>
          </Section>

          {/* 17. Events: the contact's events (SEG2a C5) */}
          <Section title={events ? `Events (${events.length})` : 'Events'} defaultOpen>
            {events === null ? null : events.length === 0 ? (
              <EmptyState icon="calendar" text="See the events associated with this record." />
            ) : (
              <>
                {events.map((ev, i) => {
                  const evName = ev.name || NO_VALUE;
                  const preview = (e: React.MouseEvent) => {
                    e.preventDefault();
                    setEventShown({ id: ev.id, name: ev.name ?? '' });
                  };
                  return (
                    <div
                      className={
                        i < events.length - 1 ? 'vcs-assoc-card crm-mb-2' : 'vcs-assoc-card'
                      }
                      data-event-card={evName}
                      key={ev.id}
                    >
                      <div className="crm-d-flex crm-align-items-center crm-gap-2">
                        <span className="lp-av lp-av--sm lp-av--sq lp-av--neutral">
                          <CrmIcon name="calendar" className="iconSize-14" />
                        </span>
                        <div className="crm-flex-grow-1">
                          <a
                            href={`/events/${ev.id}`}
                            className="vcs-link-action crm-fw-600"
                            data-event-preview={evName}
                            onClick={preview}
                          >
                            {evName}
                          </a>
                          <small className="crm-text-muted crm-d-block">Year: {NO_VALUE}</small>
                        </div>
                        <button
                          type="button"
                          className="lp-icon-btn lp-icon-btn--sm"
                          title="Preview event"
                          data-event-preview={evName}
                          onClick={preview}
                        >
                          <CrmIcon name="eye" className="iconSize-14" />
                        </button>
                      </div>
                    </div>
                  );
                })}
                <Link
                  href={href}
                  className="vcs-link-action crm-fs-8 crm-fw-600 crm-mt-2 crm-d-flex crm-align-items-center crm-gap-1"
                >
                  <span>View all associated Events</span>
                  <CrmIcon name="external" className="iconSize-12" />
                </Link>
              </>
            )}
          </Section>
        </div>
      </SegDrawer>

      <PropertyHistoryDrawer
        open={historyOpen}
        onClose={() => setHistoryOpen(false)}
        load={(params) => getContactHistory(id, params)}
        describe={describeHistory}
        reloadKey={contact.updatedAt}
        timeZone={timeZone}
        design={{
          recordName: name,
          objectType: 'contact',
          canManageProperties: canOpenProperties,
        }}
      />
      <EventPreviewDrawer
        open={eventShown !== null}
        onClose={() => setEventShown(null)}
        eventName={eventShown?.name ?? ''}
        eventId={eventShown?.id ?? null}
      />

      <EditEmailModal
        open={modal === 'email'}
        onClose={() => setModal(null)}
        contactId={id}
        email={contact.email}
        onSaved={saved}
      />
      <EditPhoneModal
        open={modal === 'phone'}
        onClose={() => setModal(null)}
        contactId={id}
        phone={contact.phone}
        onSaved={saved}
      />
      {picker && typeof document !== 'undefined'
        ? createPortal(
            <FloatingPicker
              kind={picker.kind}
              anchor={picker.anchor}
              current={pickerCurrent(picker.kind)}
              options={pickerOptions(picker.kind)}
              onPick={(value, label) => void pick(picker.kind, value, label)}
              onClose={() => setPicker(null)}
            />,
            document.body,
          )
        : null}
      {fieldMenu && typeof document !== 'undefined'
        ? createPortal(
            <FieldMenu
              anchor={fieldMenu.anchor}
              onCopy={copyField}
              onCopyInternal={copyInternal}
              docsHref={canManageSettings ? PROPERTY_DOCS_HREF : null}
              onClose={() => setFieldMenu(null)}
            />,
            document.body,
          )
        : null}
    </>
  );
}

/**
 * DI-3: the contact preview drawer of the segment page (`#vcsSideDrawer`). Loads the contact
 * (`GET /contacts/:id`), its lists (`GET /lists/memberships`) and the contact picklists.
 */
export function ContactPreviewDrawer({
  contactId,
  onClose,
  onChanged,
}: {
  contactId: string | null;
  onClose: () => void;
  onChanged: () => void;
}) {
  const toast = useToast();
  const me = useCurrentUser();
  const { timeZone, regionFormat } = useUserPrefs();
  const [contact, setContact] = useState<Contact | null>(null);
  const [lists, setLists] = useState<RecordList[] | null>(null);
  const [picklists, setPicklists] = useState<PicklistOption[]>([]);
  /** SEG2a: the timeline, the events and the custom fields, each for `of` (stale replies dropped). */
  const [activities, setActivities] = useState<{
    of: string;
    items: TimelineItem[] | null;
    failed: boolean;
  } | null>(null);
  const [events, setEvents] = useState<{ of: string; items: LinkedRecord[] } | null>(null);
  const [customDefs, setCustomDefs] = useState<CustomPropertyDefinition[]>([]);
  /** Bumped by an edit in the drawer: the timeline is read again. */
  const [timelineKey, setTimelineKey] = useState(0);
  const [following, setFollowing] = useState<boolean | null>(null);
  const [followBusy, setFollowBusy] = useState(false);
  /** The contact shown now: a Follow answer for another one is dropped. */
  const shownRef = useRef(contactId);
  shownRef.current = contactId;

  // Follow (HUB-382): whether I follow this contact. On failure it stays unknown ("Follow").
  useEffect(() => {
    if (!contactId) return;
    let live = true;
    setFollowing(null);
    getFollow('contact', contactId).then(
      (s) => {
        if (live) setFollowing(s.following);
      },
      () => {},
    );
    return () => {
      live = false;
    };
  }, [contactId]);

  /** Actions › Follow / Unfollow (JS:4213-4216): the design's toasts, after the call worked. */
  const toggleFollow = async () => {
    if (!contactId || !contact || followBusy) return;
    const name = previewName(contact);
    setFollowBusy(true);
    try {
      const next = following
        ? await unfollow('contact', contactId)
        : await follow('contact', contactId);
      if (shownRef.current !== contactId) return;
      setFollowing(next.following);
      toast(
        next.following
          ? `You're now following ${name}. You'll receive activity updates.`
          : `You unfollowed ${name}.`,
        'success',
      );
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setFollowBusy(false);
    }
  };

  useEffect(() => {
    if (!contactId) return;
    let live = true;
    setContact(null);
    setLists(null);
    getContact(contactId).then(
      (c) => {
        if (live) setContact(c);
      },
      (err: unknown) => {
        if (!live) return;
        toast(errorText(err), 'danger');
        onClose();
      },
    );
    listRecordLists('contact', contactId).then(
      (l) => {
        if (live) setLists(l);
      },
      (err: unknown) => {
        if (live) toast(errorText(err), 'danger');
      },
    );
    return () => {
      live = false;
    };
    // Reload only for another contact; toast and onClose may change identity every render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [contactId]);

  useEffect(() => {
    if (!contactId) return;
    let live = true;
    listPicklistOptions({ objectType: 'contact', includeArchived: true }).then(
      (p) => {
        if (live) setPicklists(p);
      },
      () => {},
    );
    // The history's and activities' field labels; without them they show field keys.
    listCustomProperties({ objectType: 'contact', includeArchived: true }).then(
      (d) => {
        if (live) setCustomDefs(d);
      },
      () => {},
    );
    return () => {
      live = false;
    };
  }, [contactId]);

  // SEG2a C2a: the timeline up to now (future meetings are Upcoming), again after an edit here.
  // A re-read keeps what is shown until it answers, and after it fails.
  useEffect(() => {
    if (!contactId) return;
    let live = true;
    setActivities((prev) =>
      prev?.of === contactId ? prev : { of: contactId, items: null, failed: false },
    );
    getContactTimeline(contactId, { limit: RECENT_SHOWN, to: new Date().toISOString() }).then(
      (page) => {
        if (live) setActivities({ of: contactId, items: page.data, failed: false });
      },
      () => {
        if (!live) return;
        setActivities((prev) =>
          prev?.of === contactId && prev.items
            ? prev
            : { of: contactId, items: null, failed: true },
        );
      },
    );
    return () => {
      live = false;
    };
  }, [contactId, timelineKey]);

  // SEG2a C5: the contact's events.
  useEffect(() => {
    if (!contactId) return;
    let live = true;
    setEvents(null);
    listLinkedRecords({ fromType: 'contact', fromId: contactId, toType: 'event', limit: 100 }).then(
      (page) => {
        if (live) setEvents({ of: contactId, items: page.data });
      },
      () => {
        // No Events object, or no access: the empty card (the plan's failure state).
        if (live) setEvents({ of: contactId, items: [] });
      },
    );
    return () => {
      live = false;
    };
  }, [contactId]);

  if (!contactId) return null;
  if (!contact || contact.id !== contactId) {
    return (
      <SegDrawer
        open
        onClose={onClose}
        label="Contact preview"
        id="vcsSideDrawer"
        className="lp-side--preview"
      >
        <header className="lp-side__head vcs-drawer-head">
          <h2 className="lp-side__title crm-fs-5 crm-fw-700 crm-mb-0" data-drawer-name="" />
          <div className="lp-side__tools">
            <button
              type="button"
              className="lp-icon-btn"
              id="vcsDrawerClose"
              aria-label="Close preview"
              onClick={onClose}
            >
              <CrmIcon name="x" className="iconSize-16" />
            </button>
          </div>
        </header>
        <div className="lp-side__body" />
      </SegDrawer>
    );
  }
  return (
    <ContactPreviewView
      contact={contact}
      lists={lists}
      canEdit={canEditContact(me, contact)}
      picklists={picklists}
      timeZone={timeZone}
      onClose={onClose}
      onChanged={onChanged}
      onContact={(c) => {
        setContact(c);
        // An edit here adds to the timeline: read it again (the shown items stay meanwhile).
        setTimelineKey((k) => k + 1);
      }}
      following={following}
      onFollow={() => void toggleFollow()}
      activities={activities?.of === contactId ? activities.items : null}
      activitiesFailed={activities?.of === contactId && activities.failed}
      events={events?.of === contactId ? events.items : null}
      customDefs={customDefs}
      canManageSettings={canEditPropertySettings(me)}
      canOpenProperties={canOpenPropertySettings(me)}
      region={regionFormat}
    />
  );
}
