'use client';

import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
} from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import {
  createAuditLogView,
  deleteAuditLogView,
  getAuditLogOptions,
  exportAuditLog,
  listAuditLog,
  listAuditLogViews,
  updateAuditLogView,
  type AuditLogEntry,
  type AuditLogOptions,
  type AuditLogSavedView,
  type AuditLogViewFilters,
  type AuditViewTab,
} from '@/features/audit-log/api.client';
import { getCustomProperty } from '@/features/custom-properties/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { scopeFromParams, withoutScope } from '../audit-scope';
import { DialogHead, SetDialog } from './settings-ui';

/** Rows per page choices, as design settings-audit-log.php ("10 per page"). The export takes
 * every matching row, not just this page. */
const PAGE_SIZES = [10, 25, 50, 100] as const;

const ENTITY_VALUES = [
  'member',
  'pipeline',
  'picklist',
  'custom_property',
  'contact',
  'company',
  'deal',
] as const;

const TABS: Array<{ id: AuditViewTab; label: string }> = [
  { id: 'all', label: 'All Logs' },
  { id: 'login', label: 'Login History' },
  { id: 'security', label: 'Security Activity' },
];

const DATE_NAMES: Record<string, string> = {
  today: 'Today',
  yesterday: 'Yesterday',
  'this-week': 'This week',
  'last-week': 'Last week',
  'this-month': 'This month',
  'last-month': 'Last month',
  'last-30': 'Last 30 days',
  'last-3': 'Last 3 months',
  'this-quarter': 'This quarter',
  'last-quarter': 'Last quarter',
  'this-year': 'This year',
  'last-year': 'Last year',
  'all-time': 'All time',
  custom: 'Custom date range',
};

const DATE_MENU = [
  'last-month',
  'last-30',
  'last-3',
  'this-quarter',
  'this-year',
  'custom',
  'today',
] as const;

const CALENDAR_PRESETS = [
  'today',
  'yesterday',
  'this-week',
  'last-week',
  'this-month',
  'last-month',
  'last-30',
  'last-3',
  'this-quarter',
  'last-quarter',
  'this-year',
  'last-year',
  'all-time',
] as const;

const EMPTY_FILTERS: AuditLogViewFilters = {
  tab: 'all',
  category: [],
  subcategory: [],
  action: [],
  actors: [],
  assisted: '',
  date: 'last-30',
  from: '',
  to: '',
};

function Chevron() {
  return (
    <svg viewBox="0 0 12 12" aria-hidden="true">
      <path d="m2 4 4 4 4-4" />
    </svg>
  );
}

function SearchGlyph() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true">
      <circle cx="8.5" cy="8.5" r="5.5" />
      <path d="m13 13 4 4" />
    </svg>
  );
}

function CalendarGlyph() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true">
      <rect x="3" y="5" width="14" height="12" rx="2" />
      <path d="M6 3v4m8-4v4M3 9h14" />
    </svg>
  );
}

function pad(n: number) {
  return String(n).padStart(2, '0');
}

function toISO(date: Date) {
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}

function toMDY(value: string) {
  return value ? `${value.slice(5, 7)}/${value.slice(8, 10)}/${value.slice(0, 4)}` : '';
}

function parseMDY(value: string) {
  const match = String(value || '')
    .trim()
    .match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
  if (!match) return '';
  const date = new Date(Number(match[3]), Number(match[1]) - 1, Number(match[2]));
  return date.getFullYear() === Number(match[3]) &&
    date.getMonth() === Number(match[1]) - 1 &&
    date.getDate() === Number(match[2])
    ? toISO(date)
    : '';
}

function formatRange(from: string, to: string) {
  if (!from && !to) return '';
  if (from === to) return toMDY(from);
  return `${toMDY(from)} - ${toMDY(to)}`;
}

function resolvePreset(key: string): { from: string; to: string } {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const y = today.getFullYear();
  const m = today.getMonth();
  const q = Math.floor(m / 3);
  const d = (year: number, month: number, day: number) => new Date(year, month, day);
  const week = new Date(today);
  week.setDate(today.getDate() - today.getDay());
  let from = new Date(today);
  let to = new Date(today);
  switch (key) {
    case 'yesterday':
      from.setDate(from.getDate() - 1);
      to = new Date(from);
      break;
    case 'this-week':
      from = week;
      to = new Date(week);
      to.setDate(to.getDate() + 6);
      break;
    case 'last-week':
      from = new Date(week);
      from.setDate(from.getDate() - 7);
      to = new Date(week);
      to.setDate(to.getDate() - 1);
      break;
    case 'this-month':
      from = d(y, m, 1);
      to = d(y, m + 1, 0);
      break;
    case 'last-month':
      from = d(y, m - 1, 1);
      to = d(y, m, 0);
      break;
    case 'last-30':
      from = new Date(today);
      from.setDate(from.getDate() - 29);
      break;
    case 'last-3':
      from = d(y, m - 2, 1);
      break;
    case 'this-quarter':
      from = d(y, q * 3, 1);
      break;
    case 'last-quarter':
      from = d(y, q * 3 - 3, 1);
      to = d(y, q * 3, 0);
      break;
    case 'this-year':
      from = d(y, 0, 1);
      break;
    case 'last-year':
      from = d(y - 1, 0, 1);
      to = d(y - 1, 11, 31);
      break;
    case 'all-time':
      return { from: '', to: '' };
    default:
      break;
  }
  return { from: toISO(from), to: toISO(to) };
}

function dateBounds(filters: AuditLogViewFilters) {
  if (filters.date === 'custom') return { from: filters.from, to: filters.to };
  return resolvePreset(filters.date);
}

function asIsoStart(dateOnly: string) {
  if (!dateOnly) return undefined;
  return new Date(`${dateOnly}T00:00:00.000`).toISOString();
}

function asIsoEnd(dateOnly: string) {
  if (!dateOnly) return undefined;
  return new Date(`${dateOnly}T23:59:59.999`).toISOString();
}

function formatDateTime(iso: string) {
  try {
    const date = new Date(iso);
    const day = new Intl.DateTimeFormat('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
    }).format(date);
    const time = new Intl.DateTimeFormat('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true,
      timeZoneName: 'short',
    }).format(date);
    return `${day} ${time}`;
  } catch {
    return iso;
  }
}

const FIELD_LABELS: Record<string, string> = {
  name: 'Company name',
  domain: 'Company domain',
  addressLine1: 'Address line 1',
  addressLine2: 'Address line 2',
  city: 'City',
  state: 'State',
  postalCode: 'Postal code',
  country: 'Country',
  industry: 'Industry',
  currency: 'Company currency',
  extraCurrencies: 'Additional currencies',
  notificationProfiles: 'Notification profiles',
  timezone: 'Time zone',
  fiscalYearStartMonth: 'Fiscal year start',
  emailHourlyLimit: 'Hourly email limit',
  emailDailyLimit: 'Daily email limit',
  trackingDomain: 'Tracking domain',
  trackingEnabled: 'Email tracking',
  automationTestMode: 'Automation test mode',
  automationTestEmails: 'Automation test emails',
  defaultLanguage: 'Account language',
  defaultRegionFormat: 'Account date format',
  defaultEmailFont: 'Default email font',
  defaultEmailFontSize: 'Default email font size',
  defaultEmailFontColor: 'Default email font color',
  lateReleases: 'Gradual feature releases',
  firstName: 'First name',
  lastName: 'Last name',
  jobTitle: 'Job title',
  phone: 'Phone',
  mobilePhone: 'Mobile phone',
  language: 'Language',
  regionFormat: 'Date and number format',
  emailSignature: 'Email signature',
  avatar: 'Profile photo',
  'preferences.defaultHomePage': 'Default home page',
  'preferences.taskDefaultDue': 'Task due date',
  'preferences.taskDefaultReminder': 'Task reminder',
  'preferences.taskDefaultTime': 'Task due time',
  'preferences.meetingDefaultMinutes': 'Default meeting length',
  'preferences.meetingBufferMinutes': 'Meeting buffer',
  'preferences.calendarTimeZone': 'Calendar time zone',
  'preferences.followUpTaskListView': 'Follow-up task in list view',
  'preferences.followUpTaskDisqualifyLead': 'Follow-up task when disqualifying a lead',
  'preferences.workflowMinimap': 'Workflow minimap',
  'preferences.workflowDefaultZoom': 'Workflow zoom',
  'preferences.releaseEmails': 'Feature release emails',
};

function settingLabel(field: string): string {
  if (FIELD_LABELS[field]) return FIELD_LABELS[field];
  if (field.includes(' ') || field.includes('·')) return field;
  const name = field.replace(/^preferences\./, '').replace(/([A-Z])/g, ' $1');
  return name.charAt(0).toUpperCase() + name.slice(1);
}

function formatChangeValue(value: unknown): string {
  if (value == null || value === '') return 'Empty';
  if (typeof value === 'boolean') return value ? 'On' : 'Off';
  if (typeof value === 'string') return value.length > 180 ? `${value.slice(0, 180)}…` : value;
  if (typeof value === 'number') return String(value);
  const text = JSON.stringify(value);
  return text.length > 180 ? `${text.slice(0, 180)}…` : text;
}

function changeEntries(
  row: AuditLogEntry,
): Array<{ field: string; label: string; from: string; to: string }> {
  return Object.entries(row.changes ?? {}).map(([field, change]) => ({
    field,
    label: settingLabel(field),
    from: formatChangeValue(change.from),
    to: formatChangeValue(change.to),
  }));
}

function changeSummary(entries: Array<{ label: string }>): string {
  if (entries.length === 0) return '';
  if (entries.length === 1) return entries[0]!.label;
  if (entries.length === 2) return `${entries[0]!.label}, ${entries[1]!.label}`;
  return `${entries[0]!.label}, ${entries[1]!.label} and ${entries.length - 2} more`;
}

function initials(name: string) {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  if (!parts.length) return '•';
  if (parts.length === 1) return parts[0]!.slice(0, 1).toUpperCase();
  return `${parts[0]!.slice(0, 1)}${parts[parts.length - 1]!.slice(0, 1)}`.toUpperCase();
}

function csvEscape(value: string) {
  return `"${value.replace(/"/g, '""')}"`;
}

function unique(values: string[]) {
  return [...new Set(values.filter(Boolean))];
}

function positionPanel(trigger: HTMLElement): CSSProperties {
  const rect = trigger.getBoundingClientRect();
  const margin = 12;
  const mobile = window.matchMedia('(max-width: 760px)').matches;
  const width = mobile ? Math.min(350, window.innerWidth - margin * 2) : 350;
  const left = Math.max(margin, Math.min(rect.left, window.innerWidth - width - margin));
  let top = rect.bottom + 8;
  if (top + 360 > window.innerHeight - margin && rect.top - 360 - 8 > margin) {
    top = rect.top - 360 - 8;
  }
  return {
    position: 'fixed',
    left,
    top: Math.max(margin, top),
    width,
    maxWidth: `calc(100vw - ${margin * 2}px)`,
    maxHeight: window.innerHeight - margin * 2,
    zIndex: 9999,
  };
}

export function AuditLogSettingsView() {
  const toast = useToast();
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  const urlScope = useMemo(() => scopeFromParams(params, ENTITY_VALUES), [params]);
  const [filters, setFilters] = useState<AuditLogViewFilters>(EMPTY_FILTERS);
  const [options, setOptions] = useState<AuditLogOptions | null>(null);
  const [rows, setRows] = useState<AuditLogEntry[]>([]);
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const [detail, setDetail] = useState<AuditLogEntry | null>(null);
  const [loading, setLoading] = useState(true);
  /** Prev/Next pages like HubSpot (no endless scroll): the cursor that opened each page so far. */
  const [pageCursors, setPageCursors] = useState<(string | null)[]>([null]);
  const [pageSize, setPageSize] = useState<number>(PAGE_SIZES[0]);
  const [sizeOpen, setSizeOpen] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [openPanel, setOpenPanel] = useState<string | null>(null);
  const [panelStyle, setPanelStyle] = useState<CSSProperties>({});
  const [search, setSearch] = useState<Record<string, string>>({});
  const [saved, setSaved] = useState<{ mine: AuditLogSavedView[]; shared: AuditLogSavedView[] }>({
    mine: [],
    shared: [],
  });
  const [activeViewId, setActiveViewId] = useState<string | null>(null);
  const [pickerOpen, setPickerOpen] = useState(false);
  const [pickerQuery, setPickerQuery] = useState('');
  const [modal, setModal] = useState<{
    mode: 'create' | 'rename' | 'share';
    name: string;
    sharing: '' | 'Private' | 'Everyone';
  } | null>(null);
  const [customOpen, setCustomOpen] = useState(false);
  const [calendarOpen, setCalendarOpen] = useState(false);
  const [calendarMonth, setCalendarMonth] = useState(() => new Date());
  const [calendarField, setCalendarField] = useState<'from' | 'to'>('from');
  const [scopeLabel, setScopeLabel] = useState<string | null>(null);
  const rootRef = useRef<HTMLDivElement>(null);
  const dateTriggerRef = useRef<HTMLButtonElement>(null);
  const loadRequest = useRef(0);

  const range = useMemo(() => dateBounds(filters), [filters]);

  useEffect(() => {
    setScopeLabel(null);
    if (!urlScope.entityId || urlScope.entity !== 'custom_property') return;
    let alive = true;
    getCustomProperty(urlScope.entityId).then(
      (property) => alive && setScopeLabel(property.label),
      () => undefined,
    );
    return () => {
      alive = false;
    };
  }, [urlScope.entity, urlScope.entityId]);

  const shownScopeLabel = scopeLabel ?? urlScope.label ?? urlScope.entityId?.slice(0, 8) ?? '';
  const linkSearch = !urlScope.entityId && urlScope.q ? urlScope.q : null;

  const loadViews = useCallback(async () => {
    try {
      setSaved(await listAuditLogViews());
    } catch {
      setSaved({ mine: [], shared: [] });
    }
  }, []);

  useEffect(() => {
    getAuditLogOptions()
      .then(setOptions)
      .catch(() => setOptions(null));
    void loadViews();
  }, [loadViews]);

  const load = useCallback(
    async (cursor: string | null) => {
      setLoading(true);
      setError(null);
      const mine = ++loadRequest.current;
      try {
        const page = await listAuditLog({
          limit: pageSize,
          cursor: cursor ?? undefined,
          view: filters.tab === 'all' ? undefined : filters.tab,
          actors: filters.actors.join(',') || undefined,
          category: filters.category.join(',') || undefined,
          subcategory: filters.subcategory.join(',') || undefined,
          actionKind: filters.action.join(',') || undefined,
          assisted: filters.assisted || undefined,
          entity: urlScope.entity || undefined,
          entityId: urlScope.entityId ?? undefined,
          from: asIsoStart(range.from),
          to: asIsoEnd(range.to),
        });
        if (mine !== loadRequest.current) return;
        setRows(page.data);
        setNextCursor(page.nextCursor);
      } catch (err) {
        if (mine !== loadRequest.current) return;
        setError(errorText(err));
        setRows([]);
      } finally {
        if (mine === loadRequest.current) setLoading(false);
      }
    },
    [filters, range.from, range.to, urlScope.entity, urlScope.entityId, pageSize],
  );

  // New filters start again at page 1.
  useEffect(() => {
    setPageCursors([null]);
    void load(null);
  }, [load]);

  const pageIndex = pageCursors.length - 1;
  const goNext = () => {
    if (!nextCursor || loading) return;
    setPageCursors((current) => [...current, nextCursor]);
    void load(nextCursor);
    rootRef.current?.scrollIntoView({ block: 'start' });
  };
  const goPrev = () => goTo(pageIndex - 1);
  /** A page already opened (its cursor is known): 1 … the current one. */
  const goTo = (index: number) => {
    if (index < 0 || index > pageIndex || index === pageIndex || loading) return;
    setPageCursors((current) => current.slice(0, index + 1));
    void load(pageCursors[index] ?? null);
    rootRef.current?.scrollIntoView({ block: 'start' });
  };

  const visibleRows = useMemo(() => {
    const term = (urlScope.q || '').trim().toLowerCase();
    if (!term) return rows;
    return rows.filter((row) => {
      const haystack =
        `${row.action} ${row.entityType} ${row.subcategory} ${JSON.stringify(row.details ?? {})} ${JSON.stringify(row.changes ?? {})}`.toLowerCase();
      return haystack.includes(term);
    });
  }, [rows, urlScope.q]);

  const categories = unique([...(options?.categories ?? []), ...rows.map((row) => row.category)]);
  const subcategories = unique([
    ...(options?.subcategories ?? []),
    ...rows.map((row) => row.subcategory),
  ]);
  const users = options?.users ?? [];

  const closePanels = () => {
    setOpenPanel(null);
    setCustomOpen(false);
    setCalendarOpen(false);
  };

  const openPopover = (name: string, trigger: HTMLElement) => {
    if (openPanel === name) {
      setOpenPanel(null);
      return;
    }
    setCustomOpen(false);
    setCalendarOpen(false);
    setPanelStyle(positionPanel(trigger));
    setOpenPanel(name);
  };

  useEffect(() => {
    const onClick = (event: MouseEvent) => {
      const target = event.target as Node;
      if (!rootRef.current?.contains(target)) return;
      if (
        !(event.target as HTMLElement).closest(
          '.audit-filter-item, .audit-popover-wrap, .audit-custom-dates',
        )
      ) {
        closePanels();
      }
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        closePanels();
        setPickerOpen(false);
        setModal(null);
      }
    };
    document.addEventListener('click', onClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('click', onClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [openPanel]);

  const toggleList = (key: 'category' | 'subcategory' | 'action' | 'actors', value: string) => {
    setFilters((current) => {
      const list = current[key] as string[];
      const next = list.includes(value) ? list.filter((item) => item !== value) : [...list, value];
      return { ...current, [key]: next };
    });
    setActiveViewId(null);
  };

  const clearList = (key: 'category' | 'subcategory' | 'action' | 'actors' | 'assisted') => {
    setFilters((current) => ({
      ...current,
      [key]: key === 'assisted' ? '' : [],
    }));
    setActiveViewId(null);
  };

  const applyPreset = (key: string) => {
    if (key === 'custom') {
      setOpenPanel(null);
      setFilters((current) => ({ ...current, date: 'custom' }));
      setCustomOpen(true);
      setCalendarOpen(true);
      setCalendarField('from');
      setActiveViewId(null);
      return;
    }
    const next = resolvePreset(key);
    setFilters((current) => ({ ...current, date: key, from: next.from, to: next.to }));
    setCustomOpen(false);
    setCalendarOpen(false);
    setOpenPanel(null);
    setActiveViewId(null);
  };

  const currentFilters = (): AuditLogViewFilters => ({ ...filters });

  const applySaved = (view: AuditLogSavedView) => {
    setFilters({ ...EMPTY_FILTERS, ...view.filters });
    setActiveViewId(view.id);
    setPickerOpen(false);
  };

  const applyTab = (tab: AuditViewTab) => {
    setFilters((current) => ({ ...current, tab }));
    setActiveViewId(null);
  };

  const undo = () => {
    setFilters(EMPTY_FILTERS);
    setActiveViewId(null);
    const next = withoutScope(new URLSearchParams(params.toString()));
    router.push(next ? `${pathname}?${next}` : pathname, { scroll: false });
  };

  const exportCsv = async () => {
    // #541: the file is every row matching the filters, not just this page. One server call
    // (it pages on the server), so it no longer takes minutes.
    let collected: AuditLogEntry[];
    let truncated = false;
    try {
      const result = await exportAuditLog({
        view: filters.tab === 'all' ? undefined : filters.tab,
        actors: filters.actors.join(',') || undefined,
        category: filters.category.join(',') || undefined,
        subcategory: filters.subcategory.join(',') || undefined,
        actionKind: filters.action.join(',') || undefined,
        assisted: filters.assisted || undefined,
        entity: urlScope.entity || undefined,
        entityId: urlScope.entityId ?? undefined,
        from: asIsoStart(range.from),
        to: asIsoEnd(range.to),
      });
      collected = result.data;
      truncated = result.truncated;
    } catch (err) {
      toast(errorText(err), 'danger');
      return;
    }
    if (!collected.length) {
      toast('Nothing to export for the current filters.', 'info');
      return;
    }
    const header = ['Category', 'Subcategory', 'Action', 'Modified by', 'Date of change', 'Source'];
    const lines = collected.map((row) =>
      [
        row.category,
        row.subcategory,
        row.actionKind,
        row.actorName ?? 'System',
        formatDateTime(row.createdAt),
        row.ip ?? '-',
      ]
        .map(csvEscape)
        .join(','),
    );
    const blob = new Blob([[header.map(csvEscape).join(','), ...lines].join('\r\n')], {
      type: 'text/csv;charset=utf-8;',
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'audit-report.csv';
    a.click();
    URL.revokeObjectURL(url);
    if (truncated) {
      toast(
        'The file holds the newest 10,000 events. Narrow the dates to export the rest.',
        'info',
      );
    }
  };

  const submitModal = async () => {
    if (!modal) return;
    const name = modal.name.trim();
    if (!name || !modal.sharing) return;
    try {
      if (modal.mode === 'create') {
        const view = await createAuditLogView({
          name,
          sharedWith: modal.sharing,
          filters: currentFilters(),
        });
        await loadViews();
        setActiveViewId(view.id);
        toast('View saved.', 'success');
      } else if (activeViewId && (modal.mode === 'rename' || modal.mode === 'share')) {
        await updateAuditLogView(activeViewId, {
          name,
          sharedWith: modal.sharing,
        });
        await loadViews();
        toast(modal.mode === 'rename' ? 'View renamed.' : 'Sharing updated.', 'success');
      }
      setModal(null);
      setPickerOpen(true);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const onMore = async (action: string) => {
    setOpenPanel(null);
    if (action === 'undo') return undo();
    if (action === 'export') return exportCsv();
    if (action === 'manage-views' || action === 'copy' || action === 'save') {
      if (action === 'save' && activeViewId) {
        try {
          await updateAuditLogView(activeViewId, { filters: currentFilters() });
          await loadViews();
          toast('View saved.', 'success');
        } catch (err) {
          toast(errorText(err), 'danger');
        }
        return;
      }
      if (action === 'copy' || (action === 'save' && !activeViewId)) {
        setModal({ mode: 'create', name: '', sharing: '' });
        return;
      }
      setPickerOpen(true);
      return;
    }
    if (!activeViewId) {
      setPickerOpen(true);
      return;
    }
    const current = [...saved.mine, ...saved.shared].find((view) => view.id === activeViewId);
    if (action === 'rename') {
      setModal({
        mode: 'rename',
        name: current?.name ?? '',
        sharing: current?.isShared ? 'Everyone' : 'Private',
      });
      return;
    }
    if (action === 'sharing') {
      setModal({
        mode: 'share',
        name: current?.name ?? '',
        sharing: current?.isShared ? 'Everyone' : 'Private',
      });
      return;
    }
    if (action === 'delete') {
      try {
        await deleteAuditLogView(activeViewId);
        await loadViews();
        setActiveViewId(null);
        setFilters(EMPTY_FILTERS);
        toast('View deleted.', 'success');
      } catch (err) {
        toast(errorText(err), 'danger');
      }
    }
  };

  const filterLabel = (
    key: 'category' | 'subcategory' | 'action' | 'actors' | 'assisted' | 'date',
  ) => {
    if (key === 'date') return DATE_NAMES[filters.date] || 'Last 30 days';
    if (key === 'assisted') return filters.assisted || 'All';
    if (key === 'actors') {
      if (!filters.actors.length) return 'Anyone';
      if (filters.actors.length === 1) {
        return users.find((user) => user.id === filters.actors[0])?.name ?? '1 selected';
      }
      return `${filters.actors.length} selected`;
    }
    const list = filters[key];
    if (!list.length) return 'All';
    if (list.length === 1) return list[0]!;
    return `${list.length} selected`;
  };

  const optionList = (key: 'category' | 'subcategory' | 'action', items: string[]) => {
    const term = (search[key] ?? '').trim().toLowerCase();
    return items.filter((item) => item.toLowerCase().includes(term));
  };

  const renderCheckPanel = (
    name: 'category' | 'subcategory' | 'action',
    items: string[],
    extra?: ReactNode,
  ) =>
    openPanel === name ? (
      <div
        className={cn(
          'audit-filter-panel',
          'audit-check-panel',
          name !== 'category' && 'audit-narrow-panel',
        )}
        data-audit-panel={name}
        style={panelStyle}
        onClick={(event) => event.stopPropagation()}
      >
        <label className="audit-searchbox">
          <input
            type="search"
            placeholder="Search"
            value={search[name] ?? ''}
            onChange={(event) =>
              setSearch((current) => ({ ...current, [name]: event.target.value }))
            }
          />
          <SearchGlyph />
        </label>
        <div className="audit-check-list">
          {optionList(name, items).map((item) => (
            <label key={item} className="audit-check-option" data-option-item>
              <input
                type="checkbox"
                checked={(filters[name] as string[]).includes(item)}
                onChange={() => toggleList(name, item)}
              />
              <span>{item}</span>
            </label>
          ))}
        </div>
        <div className="audit-panel-footer">
          <button type="button" onClick={() => clearList(name)}>
            Deselect all
          </button>
        </div>
        {extra}
      </div>
    ) : null;

  const allUsersChecked =
    users.length > 0 && users.every((user) => filters.actors.includes(user.id));
  const pickerTerm = pickerQuery.trim().toLowerCase();
  const confirmReady = Boolean(modal?.name.trim() && modal.sharing);

  return (
    <div className="audit-log-page" ref={rootRef}>
      <header className="set-head audit-page-head">
        <div>
          <h1 className="set-head__title">Audit Log</h1>
          <p className="set-head__sub">
            View user actions taken in your account over the last 365 days.
          </p>
        </div>
      </header>

      {error ? <Alert tone="danger">{error}</Alert> : null}

      <div className="audit-topbar">
        <nav className="audit-view-tabs" role="tablist" aria-label="Audit log views">
          {TABS.map((tab) => (
            <button
              key={tab.id}
              type="button"
              className={cn(
                'audit-view-tab',
                filters.tab === tab.id && !activeViewId && 'is-active',
              )}
              role="tab"
              aria-selected={filters.tab === tab.id && !activeViewId}
              onClick={() => applyTab(tab.id)}
            >
              {tab.label}
            </button>
          ))}
        </nav>
        <div className="audit-view-actions">
          <button
            className="audit-icon-btn"
            type="button"
            aria-label="Undo"
            title="Undo"
            onClick={undo}
          >
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path d="M9 14 4 9l5-5M4 9h9a7 7 0 0 1 7 7v2" />
            </svg>
          </button>
          <button
            className="audit-icon-btn"
            type="button"
            aria-label="Copy view"
            title="Copy view"
            onClick={() => void onMore('copy')}
          >
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <rect x="8" y="8" width="12" height="12" rx="2" />
              <path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3" />
            </svg>
          </button>
          <button
            className={cn('audit-icon-btn', !activeViewId && 'is-muted')}
            type="button"
            aria-label="Save view"
            title="Save view"
            onClick={() => void onMore('save')}
          >
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path d="M5 3h12l3 3v15H4V3z" />
              <path d="M8 3v6h8V3M8 21v-7h8v7" />
            </svg>
          </button>
          <div className="audit-popover-wrap">
            <button
              className="audit-pill-btn"
              type="button"
              aria-expanded={openPanel === 'more'}
              onClick={(event) => openPopover('more', event.currentTarget)}
            >
              More <Chevron />
            </button>
            {openPanel === 'more' ? (
              <div className="audit-menu audit-more-menu">
                <button type="button" onClick={() => void onMore('rename')}>
                  Rename
                </button>
                <button type="button" onClick={() => void onMore('delete')}>
                  Delete
                </button>
                <button type="button" onClick={() => void onMore('sharing')}>
                  Manage sharing
                </button>
                <div className="audit-menu-divider" />
                <button type="button" onClick={() => void onMore('manage-views')}>
                  Manage all views
                </button>
              </div>
            ) : null}
          </div>
        </div>
      </div>

      <div className="audit-filter-line" aria-label="Audit filters">
        <div className="audit-filter-item">
          <span className="audit-filter-label">Category</span>
          <button
            type="button"
            className="audit-filter-trigger"
            aria-expanded={openPanel === 'category'}
            onClick={(event) => openPopover('category', event.currentTarget)}
          >
            <strong>{filterLabel('category')}</strong>
            <Chevron />
          </button>
          {renderCheckPanel(
            'category',
            categories,
            <p className="audit-upgrade-note">
              <svg viewBox="0 0 16 16" aria-hidden="true">
                <rect x="3" y="7" width="10" height="8" rx="1" />
                <path d="M5 7V5a3 3 0 0 1 6 0v2" />
              </svg>
              Would you like to get access to other types of events in your audit?{' '}
              <Link href="/settings/billing">Upgrade now</Link>
            </p>,
          )}
        </div>

        <div className="audit-filter-item">
          <span className="audit-filter-label">Subcategory</span>
          <button
            type="button"
            className="audit-filter-trigger"
            aria-expanded={openPanel === 'subcategory'}
            onClick={(event) => openPopover('subcategory', event.currentTarget)}
          >
            <strong>{filterLabel('subcategory')}</strong>
            <Chevron />
          </button>
          {renderCheckPanel('subcategory', subcategories)}
        </div>

        <div className="audit-filter-item">
          <span className="audit-filter-label">Action</span>
          <button
            type="button"
            className="audit-filter-trigger"
            aria-expanded={openPanel === 'action'}
            onClick={(event) => openPopover('action', event.currentTarget)}
          >
            <strong>{filterLabel('action')}</strong>
            <Chevron />
          </button>
          {renderCheckPanel('action', options?.actions ?? [])}
        </div>

        <div className="audit-filter-item">
          <span className="audit-filter-label">Modified by</span>
          <button
            type="button"
            className="audit-filter-trigger"
            aria-expanded={openPanel === 'modified'}
            onClick={(event) => openPopover('modified', event.currentTarget)}
          >
            <strong>{filterLabel('actors')}</strong>
            <Chevron />
          </button>
          {openPanel === 'modified' ? (
            <div
              className="audit-filter-panel audit-check-panel audit-user-panel"
              style={{ ...panelStyle, width: 248 }}
              onClick={(event) => event.stopPropagation()}
            >
              <div className="audit-check-list audit-user-list">
                <label className="audit-check-option audit-user-parent">
                  <input
                    type="checkbox"
                    checked={allUsersChecked}
                    onChange={() =>
                      setFilters((current) => ({
                        ...current,
                        actors: allUsersChecked ? [] : users.map((user) => user.id),
                      }))
                    }
                  />
                  <strong>User</strong>
                </label>
                {users.map((user) => (
                  <label key={user.id} className="audit-check-option audit-user-child">
                    <input
                      type="checkbox"
                      checked={filters.actors.includes(user.id)}
                      onChange={() => toggleList('actors', user.id)}
                    />
                    <span>
                      <strong>{user.name}</strong>
                      <small>{user.email}</small>
                    </span>
                  </label>
                ))}
              </div>
              <div className="audit-panel-footer">
                <button type="button" onClick={() => clearList('actors')}>
                  Deselect all
                </button>
              </div>
            </div>
          ) : null}
        </div>

        <div className="audit-filter-item">
          <span className="audit-filter-label">Assisted by</span>
          <button
            type="button"
            className="audit-filter-trigger"
            aria-expanded={openPanel === 'assisted'}
            onClick={(event) => openPopover('assisted', event.currentTarget)}
          >
            <strong>{filterLabel('assisted')}</strong>
            <Chevron />
          </button>
          {openPanel === 'assisted' ? (
            <div
              className="audit-filter-panel audit-assisted-panel"
              style={{ ...panelStyle, width: 258 }}
              onClick={(event) => event.stopPropagation()}
            >
              <label className="audit-searchbox">
                <input
                  type="search"
                  placeholder="Search for AI tools or Apps"
                  value={search.assisted ?? ''}
                  onChange={(event) =>
                    setSearch((current) => ({ ...current, assisted: event.target.value }))
                  }
                />
                <SearchGlyph />
              </label>
              <div className="audit-assisted-list">
                {(options?.assisted.ai ?? ['AI', 'Breeze Assistant'])
                  .filter((item) =>
                    item.toLowerCase().includes((search.assisted ?? '').toLowerCase()),
                  )
                  .map((item, index) =>
                    index === 0 ? (
                      <button
                        key={item}
                        type="button"
                        className="audit-assisted-heading"
                        onClick={() => {
                          setFilters((current) => ({ ...current, assisted: item }));
                          setActiveViewId(null);
                          setOpenPanel(null);
                        }}
                      >
                        {item} <span>New</span>
                      </button>
                    ) : (
                      <button
                        key={item}
                        type="button"
                        className="audit-assisted-option"
                        onClick={() => {
                          setFilters((current) => ({ ...current, assisted: item }));
                          setActiveViewId(null);
                          setOpenPanel(null);
                        }}
                      >
                        {item}
                      </button>
                    ),
                  )}
                <strong className="audit-assisted-section">Apps</strong>
                {(options?.assisted.apps ?? ['Salesforce', 'Zapier'])
                  .filter((item) =>
                    item.toLowerCase().includes((search.assisted ?? '').toLowerCase()),
                  )
                  .map((item) => (
                    <button
                      key={item}
                      type="button"
                      className="audit-assisted-option"
                      onClick={() => {
                        setFilters((current) => ({ ...current, assisted: item }));
                        setActiveViewId(null);
                        setOpenPanel(null);
                      }}
                    >
                      {item}
                    </button>
                  ))}
              </div>
              <div className="audit-panel-footer">
                <button type="button" onClick={() => clearList('assisted')}>
                  Clear
                </button>
              </div>
            </div>
          ) : null}
        </div>

        <div className="audit-filter-item audit-date-filter">
          <span className="audit-filter-label">Date</span>
          <button
            ref={dateTriggerRef}
            type="button"
            className="audit-filter-trigger"
            aria-expanded={openPanel === 'date'}
            onClick={(event) => openPopover('date', event.currentTarget)}
          >
            <strong>{filterLabel('date')}</strong>
            <Chevron />
          </button>
          {openPanel === 'date' ? (
            <div
              className="audit-filter-panel audit-date-panel"
              style={{ ...panelStyle, width: 258 }}
              onClick={(event) => event.stopPropagation()}
            >
              <label className="audit-searchbox">
                <input
                  type="search"
                  placeholder="Search"
                  value={search.date ?? ''}
                  onChange={(event) =>
                    setSearch((current) => ({ ...current, date: event.target.value }))
                  }
                />
                <SearchGlyph />
              </label>
              <div className="audit-date-options">
                {DATE_MENU.filter((key) => {
                  const bounds = key === 'custom' ? { from: '', to: '' } : resolvePreset(key);
                  const label = `${DATE_NAMES[key]} ${key === 'custom' ? 'custom date range' : formatRange(bounds.from, bounds.to)}`;
                  return label.toLowerCase().includes((search.date ?? '').toLowerCase());
                }).map((key) => {
                  const bounds = key === 'custom' ? { from: '', to: '' } : resolvePreset(key);
                  return (
                    <button
                      key={key}
                      type="button"
                      className={cn(filters.date === key && 'is-selected')}
                      onClick={() => applyPreset(key)}
                    >
                      <span>{DATE_NAMES[key]}</span>
                      <small>
                        {key === 'custom'
                          ? 'Select a custom date range'
                          : formatRange(bounds.from, bounds.to)}
                      </small>
                    </button>
                  );
                })}
              </div>
            </div>
          ) : null}
          {customOpen ? (
            <div
              className="audit-custom-dates"
              style={
                customOpen && dateTriggerRef.current
                  ? (() => {
                      const rect = dateTriggerRef.current!.getBoundingClientRect();
                      const width = Math.min(460, window.innerWidth - 24);
                      const left = Math.max(
                        12,
                        Math.min(rect.left, window.innerWidth - width - 12),
                      );
                      return { left, width, top: rect.bottom + 8 };
                    })()
                  : undefined
              }
              onClick={(event) => event.stopPropagation()}
            >
              <div className="audit-custom-date-inputs">
                <label>
                  From{' '}
                  <span className="audit-date-input-wrap">
                    <CalendarGlyph />
                    <input
                      type="text"
                      inputMode="numeric"
                      placeholder="MM/DD/YYYY"
                      aria-label="Start date"
                      value={toMDY(filters.from)}
                      onFocus={() => {
                        setCalendarOpen(true);
                        setCalendarField('from');
                      }}
                      onChange={(event) => {
                        const parsed = parseMDY(event.target.value);
                        if (parsed)
                          setFilters((current) => ({ ...current, from: parsed, date: 'custom' }));
                      }}
                    />
                  </span>
                </label>
                <label>
                  to{' '}
                  <span className="audit-date-input-wrap">
                    <CalendarGlyph />
                    <input
                      type="text"
                      inputMode="numeric"
                      placeholder="MM/DD/YYYY"
                      aria-label="End date"
                      value={toMDY(filters.to)}
                      onFocus={() => {
                        setCalendarOpen(true);
                        setCalendarField('to');
                      }}
                      onChange={(event) => {
                        const parsed = parseMDY(event.target.value);
                        if (parsed)
                          setFilters((current) => ({ ...current, to: parsed, date: 'custom' }));
                      }}
                    />
                  </span>
                </label>
                <button
                  type="button"
                  onClick={() => {
                    if (!filters.from || !filters.to) {
                      window.alert('Please select both a start date and an end date.');
                      return;
                    }
                    if (filters.from > filters.to) {
                      window.alert('The start date must be before the end date.');
                      return;
                    }
                    setFilters((current) => ({ ...current, date: 'custom' }));
                    setCustomOpen(false);
                    setCalendarOpen(false);
                    setActiveViewId(null);
                  }}
                >
                  Apply
                </button>
              </div>
              <div className="audit-calendar" hidden={!calendarOpen}>
                <div className="audit-calendar-presets">
                  {CALENDAR_PRESETS.map((key) => (
                    <button
                      key={key}
                      type="button"
                      className={cn(filters.date === key && 'is-active')}
                      onClick={() => applyPreset(key)}
                    >
                      {DATE_NAMES[key]}
                    </button>
                  ))}
                </div>
                <div className="audit-calendar-main">
                  <AuditCalendar
                    month={calendarMonth}
                    from={filters.from}
                    to={filters.to}
                    onMonth={(delta) =>
                      setCalendarMonth(
                        (current) => new Date(current.getFullYear(), current.getMonth() + delta, 1),
                      )
                    }
                    onDay={(value) => {
                      setFilters((current) => {
                        if (calendarField === 'from') {
                          setCalendarField('to');
                          return {
                            ...current,
                            date: 'custom',
                            from: value,
                            to: current.to && current.to < value ? '' : current.to,
                          };
                        }
                        if (current.from && value < current.from) {
                          setCalendarField('from');
                          return { ...current, date: 'custom', from: value, to: current.from };
                        }
                        setCalendarField('from');
                        return { ...current, date: 'custom', to: value };
                      });
                      setActiveViewId(null);
                    }}
                    onClear={() => {
                      setFilters((current) => ({ ...current, from: '', to: '', date: 'custom' }));
                      setActiveViewId(null);
                    }}
                  />
                </div>
              </div>
            </div>
          ) : null}
        </div>

        <button type="button" className="audit-export-btn" onClick={exportCsv}>
          Export report
        </button>
      </div>

      {urlScope.entityId || linkSearch ? (
        <span className="audit-scope-chip" role="status">
          <span>
            {urlScope.entityId ? `Changes to ${shownScopeLabel}` : `Search: ${linkSearch}`}
          </span>
          <button type="button" aria-label="Show all changes" onClick={undo}>
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
        </span>
      ) : null}

      <div className="crm-table-card audit-table-card" id="audit-table-region">
        <div className="crm-table-wrap audit-table-wrap">
          {loading || visibleRows.length > 0 ? (
            <table className="crm-table audit-table" id="audit-table">
              <thead>
                <tr>
                  <th>Category</th>
                  <th>
                    Subcategory{' '}
                    <span className="audit-info" title="More about subcategory">
                      ⓘ
                    </span>
                  </th>
                  <th>Action</th>
                  <th>Modified by</th>
                  <th>
                    Date of change <span className="audit-sort">↓</span>
                  </th>
                  <th>
                    Source{' '}
                    <span className="audit-info" title="Source IP address">
                      ⓘ
                    </span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={6} className="crm-text-body-secondary">
                      Loading log entries...
                    </td>
                  </tr>
                ) : (
                  visibleRows.map((row) => {
                    const changes = changeEntries(row);
                    const summary = changeSummary(changes);
                    return (
                      <tr key={row.id} className={changes.length ? 'audit-row--detail' : undefined}>
                        <td>{row.category}</td>
                        <td>
                          {row.subcategory}
                          {summary ? (
                            <button
                              type="button"
                              className="audit-change-link"
                              onClick={() => setDetail(row)}
                            >
                              {summary}
                            </button>
                          ) : null}
                        </td>
                        <td>{row.actionKind}</td>
                        <td>
                          <span className="audit-user-cell">
                            <span className="audit-avatar">{initials(row.actorName ?? 'S')}</span>
                            <span>
                              <strong>{row.actorName ?? 'System'}</strong>
                              <small>{row.actorEmail ?? ''}</small>
                            </span>
                          </span>
                        </td>
                        <td>{formatDateTime(row.createdAt)}</td>
                        <td className="audit-source">{row.ip ?? '-'}</td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          ) : (
            <div className="audit-no-events">
              <svg viewBox="0 0 220 190" aria-hidden="true">
                <path d="m22 139 88-48 88 48-88 48Z" fill="#edf2f6" />
                <path
                  d="M84 67a32 24 0 1 0 64 0 32 24 0 1 0-64 0Z"
                  fill="#f8fbfd"
                  stroke="#cbd7e4"
                  strokeWidth="5"
                />
                <path
                  d="m138 84 29 20-8 12-30-19"
                  fill="#dce6ef"
                  stroke="#cbd7e4"
                  strokeWidth="5"
                  strokeLinejoin="round"
                />
                <path
                  d="M95 66a21 15 0 1 0 42 0 21 15 0 1 0-42 0Z"
                  fill="none"
                  stroke="#dce6ef"
                  strokeWidth="4"
                />
                <path
                  d="m93 91-22 49m72-49 22 49"
                  stroke="#d3dee8"
                  strokeWidth="2"
                  strokeDasharray="4 5"
                />
                <ellipse
                  cx="118"
                  cy="143"
                  rx="33"
                  ry="13"
                  fill="#fff"
                  stroke="#d3dee8"
                  strokeWidth="2"
                  strokeDasharray="4 4"
                />
                <path
                  d="m177 33 7-12m9 25 13-5"
                  stroke="#d3dee8"
                  strokeWidth="4"
                  strokeLinecap="round"
                />
              </svg>
              <h2>No events found</h2>
              <p>Not what you expected? You may want to adjust the filters and date range</p>
            </div>
          )}
        </div>
        {rows.length > 0 || pageIndex > 0 ? (
          <nav className="audit-pager" aria-label="Audit log pagination">
            <button
              type="button"
              className="audit-pager__step"
              disabled={pageIndex === 0 || loading}
              onClick={goPrev}
              aria-label="Previous page"
            >
              ‹ Prev
            </button>
            {pageCursors.map((_, index) => (
              <button
                key={index}
                type="button"
                className="audit-pager__num"
                aria-current={index === pageIndex ? 'page' : undefined}
                disabled={loading}
                onClick={() => goTo(index)}
              >
                {index + 1}
              </button>
            ))}
            {nextCursor ? (
              <button
                type="button"
                className="audit-pager__num"
                disabled={loading}
                onClick={goNext}
              >
                {pageIndex + 2}
              </button>
            ) : null}
            <button
              type="button"
              className="audit-pager__step"
              disabled={!nextCursor || loading}
              onClick={goNext}
              aria-label="Next page"
            >
              Next ›
            </button>
            <div className="audit-pager__size">
              <button
                type="button"
                aria-haspopup="listbox"
                aria-expanded={sizeOpen}
                onClick={() => setSizeOpen((open) => !open)}
              >
                {pageSize} per page <Chevron />
              </button>
              {sizeOpen ? (
                <ul role="listbox" aria-label="Rows per page">
                  {PAGE_SIZES.map((size) => (
                    <li key={size}>
                      <button
                        type="button"
                        role="option"
                        aria-selected={size === pageSize}
                        onClick={() => {
                          setSizeOpen(false);
                          setPageSize(size);
                        }}
                      >
                        {size} per page
                      </button>
                    </li>
                  ))}
                </ul>
              ) : null}
            </div>
          </nav>
        ) : null}
      </div>

      {pickerOpen ? (
        <>
          <div className="audit-view-picker-backdrop" onClick={() => setPickerOpen(false)} />
          <section className="audit-view-picker" aria-label="Choose a saved view">
            <label className="audit-searchbox audit-view-picker-search">
              <input
                type="search"
                placeholder="Search"
                value={pickerQuery}
                onChange={(event) => setPickerQuery(event.target.value)}
              />
              <SearchGlyph />
            </label>
            <div className="audit-view-picker-columns">
              <div>
                <strong>HubSpot Provided</strong>
                {TABS.filter((tab) => tab.label.toLowerCase().includes(pickerTerm)).map((tab) => (
                  <button
                    key={tab.id}
                    type="button"
                    onClick={() => {
                      applyTab(tab.id);
                      setPickerOpen(false);
                    }}
                  >
                    {tab.label}
                  </button>
                ))}
              </div>
              <div>
                <strong>Created by me</strong>
                {saved.mine
                  .filter((view) => view.name.toLowerCase().includes(pickerTerm))
                  .map((view) => (
                    <button
                      key={view.id}
                      type="button"
                      className="audit-saved-view-item"
                      onClick={() => applySaved(view)}
                    >
                      <span>{view.name}</span>
                      <small>{view.isShared ? 'Everyone' : 'Private'}</small>
                    </button>
                  ))}
              </div>
              <div>
                <strong>Created by others</strong>
                {saved.shared
                  .filter((view) => view.name.toLowerCase().includes(pickerTerm))
                  .map((view) => (
                    <button key={view.id} type="button" onClick={() => applySaved(view)}>
                      {view.name}
                    </button>
                  ))}
              </div>
            </div>
            <div className="audit-view-picker-footer">
              <button
                type="button"
                onClick={() => setModal({ mode: 'create', name: '', sharing: '' })}
              >
                ＋ Create new view
              </button>
            </div>
          </section>
        </>
      ) : null}

      {modal ? (
        <div
          className="audit-modal-backdrop"
          onClick={(event) => {
            if (event.target === event.currentTarget) setModal(null);
          }}
        >
          <section
            className="audit-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="audit-modal-title"
          >
            <header>
              <h2 id="audit-modal-title">
                {modal?.mode === 'rename'
                  ? 'Rename view'
                  : modal?.mode === 'share'
                    ? 'Manage sharing'
                    : 'Create new view'}
              </h2>
              <button type="button" aria-label="Close" onClick={() => setModal(null)}>
                <svg viewBox="0 0 20 20" aria-hidden="true">
                  <path d="m5 5 10 10M15 5 5 15" />
                </svg>
              </button>
            </header>
            <form
              onSubmit={(event) => {
                event.preventDefault();
                void submitModal();
              }}
            >
              <label className="audit-modal-field crm-mb-2">
                Name *
                <input
                  type="text"
                  name="view_name"
                  placeholder="Enter a name"
                  required
                  maxLength={60}
                  value={modal?.name ?? ''}
                  onChange={(event) =>
                    setModal((current) =>
                      current ? { ...current, name: event.target.value } : current,
                    )
                  }
                />
              </label>
              <fieldset>
                <legend>Shared with *</legend>
                <label>
                  <input
                    type="radio"
                    name="shared_with"
                    checked={modal?.sharing === 'Private'}
                    onChange={() =>
                      setModal((current) =>
                        current ? { ...current, sharing: 'Private' } : current,
                      )
                    }
                  />{' '}
                  Private
                </label>
                <label>
                  <input
                    type="radio"
                    name="shared_with"
                    checked={modal?.sharing === 'Everyone'}
                    onChange={() =>
                      setModal((current) =>
                        current ? { ...current, sharing: 'Everyone' } : current,
                      )
                    }
                  />{' '}
                  Everyone
                </label>
              </fieldset>
              <footer>
                <button type="submit" className="audit-confirm-btn" disabled={!confirmReady}>
                  Confirm
                </button>
                <button type="button" className="audit-cancel-btn" onClick={() => setModal(null)}>
                  Cancel
                </button>
              </footer>
            </form>
          </section>
        </div>
      ) : null}

      <SetDialog
        open={detail != null}
        onClose={() => setDetail(null)}
        drawer
        labelledBy="audit-detail-title"
      >
        <div>
          <DialogHead
            id="audit-detail-title"
            title={detail ? changeSummary(changeEntries(detail)) : 'Change'}
            onClose={() => setDetail(null)}
          />
          <div className="set-modal__body audit-detail">
            <p className="audit-detail__meta">
              {detail?.subcategory}
              {detail?.actorName ? ` · ${detail.actorName}` : ''}
            </p>
            <ul>
              {detail
                ? changeEntries(detail).map((change) => (
                    <li key={change.field}>
                      <strong>{change.label}</strong>
                      <span>
                        {change.from} → {change.to}
                      </span>
                    </li>
                  ))
                : null}
            </ul>
          </div>
        </div>
      </SetDialog>
    </div>
  );
}

function AuditCalendar({
  month,
  from,
  to,
  onMonth,
  onDay,
  onClear,
}: {
  month: Date;
  from: string;
  to: string;
  onMonth: (delta: number) => void;
  onDay: (value: string) => void;
  onClear: () => void;
}) {
  const y = month.getFullYear();
  const m = month.getMonth();
  const first = new Date(y, m, 1);
  const start = new Date(y, m, 1 - first.getDay());
  const today = toISO(new Date());
  const days: Date[] = [];
  for (let i = 0; i < 42; i += 1) {
    const day = new Date(start);
    day.setDate(start.getDate() + i);
    days.push(day);
  }
  const title = month.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
  return (
    <>
      <div className="audit-calendar-head">
        <button type="button" aria-label="Previous month" onClick={() => onMonth(-1)}>
          ‹
        </button>
        <strong>{title}</strong>
        <button type="button" aria-label="Next month" onClick={() => onMonth(1)}>
          ›
        </button>
      </div>
      <div className="audit-calendar-grid">
        {['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((label) => (
          <span key={label}>{label}</span>
        ))}
        {days.map((day) => {
          const key = toISO(day);
          const out = day.getMonth() !== m;
          const selected = key === from || key === to;
          const inRange = Boolean(from && to && key > from && key < to);
          return (
            <button
              key={key}
              type="button"
              className={cn(
                out && 'is-out',
                selected && 'is-selected',
                inRange && 'is-range',
                key === today && 'is-today',
              )}
              aria-label={day.toDateString()}
              onClick={() => onDay(key)}
            >
              {day.getDate()}
            </button>
          );
        })}
      </div>
      <button type="button" className="audit-calendar-clear" onClick={onClear}>
        Clear
      </button>
    </>
  );
}
