'use client';

import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  DEFAULT_BROWSER_NOTIFY_TYPES,
  getExtensionSettings,
  updateExtensionSettings,
  type BrowserNotifyTypes,
} from '@/features/extension/api.client';
import { syncExtensionNotifications } from '@/features/extension/bridge';
import {
  getMostReceived,
  getNotificationPreferences,
  updateNotificationPreferences,
  type MostReceived,
  type NotificationChannel,
  type NotificationPreferences,
  type NotificationTopicDef,
  type WebsiteVisitScope,
} from '@/features/settings/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { NOTIFICATION_SOUNDS, playNotificationSound } from './notification-sounds';
import { SettingsForm, SettingsFormsProvider, useHashTab } from './settings-ui';

/**
 * Settings › Notifications — design: settings-notifications.php
 * Persists via GET/PUT /notifications/preferences (HUB-513).
 * Browser channel for tracked-email alerts also syncs extension Chrome prefs.
 */

const VIEW_TABS = [
  { id: 'most_received', label: 'Most received' },
  { id: 'all_notifications', label: 'All notifications' },
] as const;

const CHANNELS: NotificationChannel[] = ['popup', 'browser', 'bell', 'email', 'mobile', 'slack'];

const CHANNEL_LABELS: Record<NotificationChannel, string> = {
  popup: 'Pop-up',
  browser: 'Browser',
  bell: 'Bell',
  email: 'Email',
  mobile: 'Mobile',
  slack: 'Slack',
};

const DETAIL_CHANNELS = [
  'email',
  'bell',
  'popup',
  'browser',
  'google_chat',
  'microsoft_teams',
  'slack',
] as const;

type StatusFilter = 'all' | 'on' | 'off';

function SoundOptionIcon({ name }: { name: string }) {
  if (name === 'Off (no sound)') {
    return (
      <svg className="sn-sound-option-icon" viewBox="0 0 24 24" aria-hidden="true">
        <path d="M4 10v4h4l5 4V6l-5 4H4m12-1 5 5m0-5-5 5" />
      </svg>
    );
  }
  if (name === 'Default (Whizz)') {
    return (
      <svg className="sn-sound-option-icon" viewBox="0 0 24 24" aria-hidden="true">
        <rect x="3" y="5" width="18" height="14" rx="1.5" />
        <path d="M6 9h5M6 12h9" />
      </svg>
    );
  }
  return (
    <svg className="sn-sound-option-icon" viewBox="0 0 24 24" aria-hidden="true">
      <circle cx="12" cy="12" r="10" />
      <path d="m10 8 5 4-5 4z" fill="currentColor" stroke="none" />
    </svg>
  );
}

const WEBSITE_VISITS_GROUP = 'Website visits';

const WEBSITE_VISIT_SECTIONS = [
  { scopeField: 'contactsScope', topicKey: 'website_visit_contacts', noun: 'Contacts' },
  { scopeField: 'companiesScope', topicKey: 'website_visit_companies', noun: 'Companies' },
] as const;

function websiteVisitsOn(topics: NotificationPreferences['topics']): boolean {
  return WEBSITE_VISIT_SECTIONS.some(
    ({ topicKey }) => !!topics[topicKey]?.email || !!topics[topicKey]?.bell,
  );
}

function WebsiteVisitsPanel({
  draft,
  onScope,
  onChannel,
}: {
  draft: NotificationPreferences;
  onScope: (field: 'contactsScope' | 'companiesScope', scope: WebsiteVisitScope) => void;
  onChannel: (topicKey: string, channel: 'email' | 'bell', on: boolean) => void;
}) {
  return (
    <div className="sn-topic-rows sn-website-visits-panel">
      <p className="sn-wv-intro">
        Get notified when a contact or prospect visits your site, so you know when to follow up.
        Contacts are already in the CRM. Prospects aren&apos;t in your contacts, but can often be
        identified by company.
      </p>
      {WEBSITE_VISIT_SECTIONS.map(({ scopeField, topicKey, noun }) => (
        <div key={topicKey} className="sn-wv-section">
          <h3 className="sn-wv-title">{noun}</h3>
          <div className="sn-wv-group">
            <p className="sn-wv-subhead">Choose who you receive notifications about:</p>
            <div className="sn-wv-radios" role="radiogroup" aria-label={`${noun} scope`}>
              {(
                [
                  ['view', `${noun} you can view`],
                  ['own', `${noun} you own`],
                ] as const
              ).map(([value, label]) => (
                <label key={value} className="sn-wv-radio">
                  <input
                    type="radio"
                    name={`wv_${topicKey}_scope`}
                    value={value}
                    checked={draft.websiteVisits[scopeField] === value}
                    onChange={() => onScope(scopeField, value)}
                  />
                  <span className="sn-wv-radio-control" aria-hidden="true" />
                  <span className="sn-wv-label-text">{label}</span>
                </label>
              ))}
            </div>
          </div>
          <div className="sn-wv-group">
            <p className="sn-wv-subhead">Choose how you receive these notifications:</p>
            <div className="sn-wv-checkboxes">
              {(
                [
                  ['email', 'Email'],
                  ['bell', 'Real-time alert in your activity feed'],
                ] as const
              ).map(([channel, label]) => (
                <label key={channel} className="sn-wv-checkbox">
                  <input
                    type="checkbox"
                    checked={!!draft.topics[topicKey]?.[channel]}
                    onChange={(event) => onChannel(topicKey, channel, event.target.checked)}
                  />
                  <span className="sn-wv-check-control" aria-hidden="true">
                    <svg viewBox="0 0 16 16" focusable="false">
                      <path d="m3.5 8.2 2.8 2.8 6.2-6.2" />
                    </svg>
                  </span>
                  <span className="sn-wv-label-text">{label}</span>
                </label>
              ))}
            </div>
          </div>
        </div>
      ))}
      <div className="sn-wv-section sn-wv-section--prospects">
        <h3 className="sn-wv-title">Prospects</h3>
        <p className="sn-wv-desc">
          Save your search as a view and get notified when prospects that match your criteria visit
          your site.
        </p>
        <div className="sn-wv-prospects-table">
          <div className="sn-wv-table-head">
            <span className="sn-wv-th sn-wv-th--view">View</span>
            <span className="sn-wv-th sn-wv-th--email">Daily email</span>
            <span className="sn-wv-th sn-wv-th--notify">Notifications</span>
          </div>
          <div className="sn-wv-table-body">
            <div className="sn-wv-empty-state">
              You haven&apos;t created and subscribed to any views in the prospects tool yet.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function RowSound({
  item,
  popupOn,
  sound,
  playing,
  onPlay,
  onOpenMenu,
}: {
  item: NotificationTopicDef;
  popupOn: boolean;
  sound: string | undefined;
  playing: boolean;
  onPlay: () => void;
  onOpenMenu: (anchor: HTMLElement) => void;
}) {
  if (!topicHasChannel(item, 'popup')) {
    return (
      <div className="sn-notification-sound">
        <span className="sn-not-available">--</span>
      </div>
    );
  }
  return (
    <div className="sn-notification-sound" data-popup-off={popupOn ? undefined : 'true'}>
      <button
        type="button"
        className={playing ? 'sn-row-play is-playing' : 'sn-row-play'}
        aria-label={playing ? 'Stop sound preview' : 'Play sound preview'}
        aria-pressed={playing}
        disabled={!popupOn}
        onClick={onPlay}
      >
        {playing ? (
          <svg viewBox="0 0 24 24" aria-hidden="true">
            <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.5" fill="none" />
            <path d="M9 8h2v8H9zM13 8h2v8h-2z" fill="currentColor" />
          </svg>
        ) : (
          <svg viewBox="0 0 24 24" aria-hidden="true">
            <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.5" fill="none" />
            <path d="m10 8 5 4-5 4z" fill="currentColor" />
          </svg>
        )}
      </button>
      <div className="sn-sound-select-wrap">
        <button
          type="button"
          className="sn-sound-select"
          disabled={!popupOn}
          aria-disabled={!popupOn}
          onClick={(event) => onOpenMenu(event.currentTarget)}
        >
          <span>{sound || 'Default'}</span>
          <svg viewBox="0 0 12 12" aria-hidden="true">
            <path d="m2 4 4 4 4-4" />
          </svg>
        </button>
        {!popupOn ? (
          <div className="sn-sound-tooltip" role="tooltip">
            Turn on pop-ups for this notification to choose a sound.
          </div>
        ) : null}
      </div>
    </div>
  );
}

function PlaySoundButton({
  playing,
  disabled,
  onClick,
}: {
  playing: boolean;
  disabled?: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      className={playing ? 'sn-play-button is-playing' : 'sn-play-button'}
      disabled={disabled}
      aria-pressed={playing}
      onClick={onClick}
    >
      {playing ? (
        <>
          <svg viewBox="0 0 12 12" aria-hidden="true">
            <path d="M3 2h2v8H3zM7 2h2v8H7z" />
          </svg>
          Stop
        </>
      ) : (
        <>
          <svg viewBox="0 0 12 12" aria-hidden="true">
            <path d="m3 2 7 4-7 4z" />
          </svg>
          Play
        </>
      )}
    </button>
  );
}

function ChannelIcon({ channel }: { channel: NotificationChannel }) {
  if (channel === 'popup') {
    return (
      <svg viewBox="0 0 24 24">
        <rect x="3" y="5" width="18" height="14" rx="2" />
        <path d="M7 9h4M7 13h10" />
      </svg>
    );
  }
  if (channel === 'browser') {
    return (
      <svg viewBox="0 0 24 24">
        <rect x="3" y="4" width="18" height="15" rx="2" />
        <path d="M8 22h8M12 19v3M8 8h8" />
      </svg>
    );
  }
  if (channel === 'bell') {
    return (
      <svg viewBox="0 0 24 24">
        <path d="M18 9a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4" />
      </svg>
    );
  }
  if (channel === 'email') {
    return (
      <svg viewBox="0 0 24 24">
        <rect x="2.5" y="5" width="19" height="14" rx="2" />
        <path d="m3 7 9 7 9-7" />
      </svg>
    );
  }
  if (channel === 'mobile') {
    return (
      <svg viewBox="0 0 24 24">
        <rect x="6" y="2" width="12" height="20" rx="2" />
        <path d="M10 18h4" />
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 24 24">
      <path d="M8 4a2 2 0 1 0 0 4h8a2 2 0 1 0 0-4M8 16a2 2 0 1 0 0 4h8a2 2 0 1 0 0-4M4 8v8M20 8v8M8 8v8M16 8v8" />
    </svg>
  );
}

function CheckBox({
  checked,
  indeterminate,
  disabled,
  ariaLabel,
  onChange,
}: {
  checked: boolean;
  indeterminate?: boolean;
  disabled?: boolean;
  ariaLabel: string;
  onChange: (next: boolean) => void;
}) {
  const mixed = !!indeterminate && !checked;
  return (
    <label className="check sn-check">
      <input
        type="checkbox"
        checked={checked}
        disabled={disabled}
        aria-label={ariaLabel}
        aria-checked={mixed ? 'mixed' : checked}
        ref={(el) => {
          if (el) el.indeterminate = mixed;
        }}
        onChange={(e) => {
          // Indeterminate → always turn ON (browser default). Otherwise use the native value.
          onChange(mixed ? true : e.target.checked);
        }}
        onClick={(e) => e.stopPropagation()}
      />
      <span className="check__box" aria-hidden="true">
        <svg viewBox="0 0 16 16" focusable="false">
          <path d={mixed ? 'M3.5 8h9' : 'm3.5 8.2 2.8 2.8 6.2-6.2'} />
        </svg>
      </span>
    </label>
  );
}

function MethodToggle({
  checked,
  disabled,
  onChange,
  children,
}: {
  checked: boolean;
  disabled?: boolean;
  onChange: (next: boolean) => void;
  children: ReactNode;
}) {
  return (
    <label className="sn-detail-channel" style={disabled ? { cursor: 'not-allowed' } : undefined}>
      <span className="sn-method-check">
        <input
          type="checkbox"
          checked={checked}
          disabled={disabled}
          onChange={(e) => onChange(e.target.checked)}
        />
        <span className="sn-method-box" aria-hidden="true">
          <svg className="sn-toggle-check" viewBox="0 0 16 16" focusable="false">
            <path d="m3.5 8.2 2.8 2.8 6.2-6.2" />
          </svg>
        </span>
      </span>
      <span>{children}</span>
    </label>
  );
}

function topicHasChannel(topic: NotificationTopicDef, channel: NotificationChannel) {
  return topic.channels[channel] !== null;
}

function channelDeliverable(
  channelStatus: NotificationPreferences['channelStatus'] | undefined,
  channel: NotificationChannel,
) {
  if (channel === 'mobile') return false;
  return (channelStatus?.[channel] ?? 'live') === 'live';
}

function onChannelLabels(
  topic: NotificationTopicDef,
  topics: NotificationPreferences['topics'],
): string {
  return CHANNELS.filter(
    (channel) => topicHasChannel(topic, channel) && topics[topic.key]?.[channel] === true,
  )
    .map((channel) => CHANNEL_LABELS[channel])
    .join(', ')
    .replace(/, ([^,]*)$/, ' and $1'); // design: "Pop-up, Bell, Email, Mobile and Slack"
}

function rowIsOn(topic: NotificationTopicDef, topics: NotificationPreferences['topics']): boolean {
  return CHANNELS.some((channel) => {
    if (!topicHasChannel(topic, channel)) return false;
    return topics[topic.key]?.[channel] === true;
  });
}

function aggregate(values: boolean[]): { checked: boolean; indeterminate: boolean } {
  const on = values.filter(Boolean).length;
  return {
    checked: values.length > 0 && on === values.length,
    indeterminate: on > 0 && on < values.length,
  };
}

function browserTypesFromPrefs(
  prefs: NotificationPreferences,
  current: BrowserNotifyTypes,
): BrowserNotifyTypes {
  const emailOpen =
    prefs.topics.email_open?.bell ?? prefs.topics.email_open?.email ?? current.email_open;
  const doc = prefs.topics.document_open?.browser ?? current.document_view;
  const visit = prefs.topics.website_visit_contacts?.bell ?? current.lead_visit;
  const click = prefs.topics.email_click?.browser ?? current.email_click;
  return {
    ...current,
    email_open: !!emailOpen,
    email_click: !!click,
    document_view: !!doc,
    lead_visit: !!visit,
  };
}

export function NotificationsSettingsView() {
  const toast = useToast();
  const [view, setView] = useHashTab([...VIEW_TABS], 'most_received');
  const [prefs, setPrefs] = useState<NotificationPreferences | null>(null);
  const [draft, setDraft] = useState<NotificationPreferences | null>(null);
  const [most, setMost] = useState<MostReceived | null>(null);
  const [query, setQuery] = useState('');
  const [status, setStatus] = useState<StatusFilter>('all');
  const [statusOpen, setStatusOpen] = useState(false);
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  const [detailKey, setDetailKey] = useState<string | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [appsView, setAppsView] = useState(false);
  const [allOffMode, setAllOffMode] = useState(false);
  const [soundMenu, setSoundMenu] = useState<{
    key: string;
    kind: 'topic' | 'default' | 'detail';
    top: number;
    left: number;
  } | null>(null);
  const [playingId, setPlayingId] = useState<string | null>(null);
  const playbackRef = useRef<{ id: string; stop: () => void; timer: number } | null>(null);

  const stopPlayback = useCallback(() => {
    const current = playbackRef.current;
    if (!current) return;
    window.clearTimeout(current.timer);
    current.stop();
    playbackRef.current = null;
    setPlayingId(null);
  }, []);

  const togglePlayback = useCallback(
    (id: string, soundName: string) => {
      if (playbackRef.current?.id === id) {
        stopPlayback();
        return;
      }
      stopPlayback();
      const started = playNotificationSound(soundName);
      const timer = window.setTimeout(() => {
        if (playbackRef.current?.id === id) stopPlayback();
      }, started.durationMs || 250);
      playbackRef.current = { id, stop: started.stop, timer };
      setPlayingId(id);
    },
    [stopPlayback],
  );

  useEffect(() => stopPlayback, [stopPlayback]);

  const openSoundMenu = (
    kind: 'topic' | 'default' | 'detail',
    key: string,
    anchor: HTMLElement,
  ) => {
    if (soundMenu && soundMenu.kind === kind && soundMenu.key === key) {
      setSoundMenu(null);
      return;
    }
    const rect = anchor.getBoundingClientRect();
    setSoundMenu({
      kind,
      key,
      top: Math.min(rect.bottom + 6, window.innerHeight - 16),
      left: Math.max(8, Math.min(rect.left, window.innerWidth - 248)),
    });
  };
  const closeDefaults = useCallback(() => {
    setDrawerOpen(false);
    setAppsView(false);
    setSoundMenu(null);
  }, []);
  useEffect(() => {
    if (!drawerOpen && !soundMenu) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key !== 'Escape') return;
      if (soundMenu) setSoundMenu(null);
      else closeDefaults();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [drawerOpen, soundMenu, closeDefaults]);

  const soundMenuOpen = soundMenu !== null;
  useEffect(() => {
    if (!soundMenuOpen) return;
    const inMenuOrTrigger = (target: EventTarget | null) =>
      target instanceof Element && !!target.closest('.sn-sound-menu-portal, .sn-sound-select');
    const onPointerDown = (event: PointerEvent) => {
      if (!inMenuOrTrigger(event.target)) setSoundMenu(null);
    };
    // The menu is fixed to where its trigger was, so it would detach on scroll.
    const onScroll = (event: Event) => {
      if (event.target instanceof Element && event.target.closest('.sn-sound-menu-portal')) return;
      setSoundMenu(null);
    };
    const onResize = () => setSoundMenu(null);
    document.addEventListener('pointerdown', onPointerDown, true);
    window.addEventListener('scroll', onScroll, true);
    window.addEventListener('resize', onResize);
    return () => {
      document.removeEventListener('pointerdown', onPointerDown, true);
      window.removeEventListener('scroll', onScroll, true);
      window.removeEventListener('resize', onResize);
    };
  }, [soundMenuOpen]);

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      try {
        const data = await getNotificationPreferences();
        if (!cancelled) {
          setPrefs(data);
          setDraft(data);
        }
      } catch (err) {
        if (!cancelled) toast(errorText(err), 'danger');
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [toast]);

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      try {
        const data = await getMostReceived();
        if (!cancelled) setMost(data);
      } catch (err) {
        if (!cancelled) {
          setMost({ days: 7, items: [] });
          toast(errorText(err), 'danger');
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [toast]);

  const bumpFormDirty = useCallback(() => {
    document
      .querySelector<HTMLFormElement>('[data-settings-form]')
      ?.dispatchEvent(new Event('change', { bubbles: true }));
  }, []);

  /** Always derive from previous draft so rapid clicks don't overwrite each other. */
  const patchDraft = useCallback(
    (updater: (prev: NotificationPreferences) => NotificationPreferences) => {
      setDraft((prev) => {
        if (!prev) return prev;
        const next = updater(prev);
        queueMicrotask(() => bumpFormDirty());
        return next;
      });
    },
    [bumpFormDirty],
  );

  const setTopicChannel = useCallback(
    (key: string, channel: NotificationChannel, value: boolean) => {
      patchDraft((prev) => ({
        ...prev,
        topics: {
          ...prev.topics,
          [key]: { ...prev.topics[key], [channel]: value },
        },
      }));
    },
    [patchDraft],
  );

  const setChannelEverywhere = useCallback(
    (channel: NotificationChannel, value: boolean, groupName?: string) => {
      patchDraft((prev) => {
        const topics = { ...prev.topics };
        for (const group of prev.catalog) {
          if (groupName && group.name !== groupName) continue;
          for (const item of group.items) {
            if (!topicHasChannel(item, channel)) continue;
            topics[item.key] = { ...topics[item.key], [channel]: value };
          }
        }
        return { ...prev, topics };
      });
    },
    [patchDraft],
  );

  const turnAllTopics = useCallback(
    (on: boolean) => {
      patchDraft((prev) => {
        const topics = { ...prev.topics };
        for (const group of prev.catalog) {
          for (const item of group.items) {
            const row = { ...topics[item.key] };
            for (const channel of CHANNELS) {
              if (topicHasChannel(item, channel)) row[channel] = on;
            }
            topics[item.key] = row;
          }
        }
        for (const { topicKey } of WEBSITE_VISIT_SECTIONS) {
          topics[topicKey] = { ...topics[topicKey], email: on, bell: on };
        }
        return { ...prev, topics };
      });
      setAllOffMode(!on);
    },
    [patchDraft],
  );

  const findTopic = useCallback(
    (key: string): { group: string; topic: NotificationTopicDef } | null => {
      if (!draft) return null;
      for (const group of draft.catalog) {
        const topic = group.items.find((item) => item.key === key);
        if (topic) return { group: group.name, topic };
      }
      return null;
    },
    [draft],
  );

  const filtered = useMemo(() => {
    if (!draft) return [];
    const q = query.trim().toLowerCase();
    return draft.catalog
      .filter((group) => {
        if (group.name !== WEBSITE_VISITS_GROUP) return true;
        const on = websiteVisitsOn(draft.topics);
        const statusMatch = status === 'all' || (status === 'on' ? on : !on);
        const text = 'website visits contacts companies prospects';
        return statusMatch && (!q || text.includes(q));
      })
      .map((group) => {
        if (group.name === WEBSITE_VISITS_GROUP) return group;
        const items = group.items.filter((item) => {
          const text = `${item.title} ${item.description} ${group.name}`.toLowerCase();
          const textMatch = !q || text.includes(q);
          const on = rowIsOn(item, draft.topics);
          const statusMatch = status === 'all' || (status === 'on' ? on : !on);
          return textMatch && statusMatch;
        });
        return { ...group, items };
      })
      .filter((group) => group.name === WEBSITE_VISITS_GROUP || group.items.length > 0);
  }, [draft, query, status]);

  const visibleCount = filtered.reduce(
    (n, g) => n + (g.name === WEBSITE_VISITS_GROUP ? 1 : g.items.length),
    0,
  );

  const topicsByKey = useMemo(() => {
    const map = new Map<string, NotificationTopicDef>();
    if (!draft) return map;
    for (const group of draft.catalog) {
      for (const item of group.items) map.set(item.key, item);
    }
    return map;
  }, [draft]);

  const mostCards = useMemo(() => {
    if (!most) return [];
    const q = query.trim().toLowerCase();
    return most.items.flatMap((item) => {
      const topic = topicsByKey.get(item.key);
      if (!topic) return [];
      const text = `${topic.title} ${topic.description}`.toLowerCase();
      if (q && !text.includes(q)) return [];
      return [{ ...item, topic }];
    });
  }, [most, topicsByKey, query]);

  const setTopicOn = useCallback(
    (topic: NotificationTopicDef, on: boolean) => {
      patchDraft((prev) => {
        const row = { ...prev.topics[topic.key] };
        for (const channel of CHANNELS) {
          if (topicHasChannel(topic, channel)) row[channel] = on;
        }
        return { ...prev, topics: { ...prev.topics, [topic.key]: row } };
      });
    },
    [patchDraft],
  );

  const save = useCallback(async () => {
    if (!draft) return false;
    try {
      const saved = await updateNotificationPreferences({
        topics: draft.topics,
        sounds: draft.sounds,
        channelDefaults: draft.channelDefaults,
        defaultSound: draft.defaultSound,
        websiteVisits: draft.websiteVisits,
      });
      setPrefs(saved);
      setDraft(saved);

      // Keep Gmail extension Chrome alerts aligned with Browser/Bell toggles.
      try {
        const ext = await getExtensionSettings();
        const types = browserTypesFromPrefs(saved, {
          ...DEFAULT_BROWSER_NOTIFY_TYPES,
          ...ext.effective.browserNotifyTypes,
        });
        const enabled =
          saved.channelDefaults.browser &&
          (types.email_open || types.email_click || types.document_view || types.lead_visit);
        await updateExtensionSettings({
          notificationsEnabled: enabled,
          browserNotifyTypes: types,
        });
        await syncExtensionNotifications(enabled);
      } catch {
        /* prefs saved; extension sync is best-effort */
      }
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  }, [draft, toast]);

  if (!draft) {
    return (
      <section className="sn-notifications">
        <header className="sn-page-heading">
          <div>
            <h1>Notifications</h1>
            <p>Loading your preferences…</p>
          </div>
        </header>
      </section>
    );
  }

  const detail = detailKey ? findTopic(detailKey) : null;

  return (
    <SettingsFormsProvider>
      <SettingsForm
        onSave={save}
        onReset={() => {
          if (prefs) setDraft(prefs);
          setDetailKey(null);
          setDrawerOpen(false);
          setAppsView(false);
          setSoundMenu(null);
        }}
      >
        <section className="sn-notifications" data-notifications-root>
          {!detail ? (
            <>
              <header className="sn-page-heading" data-notification-page-heading>
                <div>
                  <h1>Notifications</h1>
                  <p>
                    Control how and when you receive notifications. These preferences apply only to
                    you.
                  </p>
                </div>
                <button
                  type="button"
                  className="sn-set-defaults"
                  onClick={() => {
                    setAppsView(false);
                    setDrawerOpen(true);
                  }}
                >
                  <svg viewBox="0 0 20 20" aria-hidden="true">
                    <path d="M8.2 2.5h3.6l.5 2a6 6 0 0 1 1.4.8l2-.6 1.8 3.1-1.5 1.4v1.6l1.5 1.4-1.8 3.1-2-.6a6 6 0 0 1-1.4.8l-.5 2H8.2l-.5-2a6 6 0 0 1-1.4-.8l-2 .6-1.8-3.1L4 10.8V9.2L2.5 7.8l1.8-3.1 2 .6a6 6 0 0 1 1.4-.8z" />
                    <circle cx="10" cy="10" r="2.3" />
                  </svg>
                  Set channel defaults
                </button>
              </header>

              <div className="sn-search-band">
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <circle cx="10.8" cy="10.8" r="6.7" />
                  <path d="m16 16 4.3 4.3" />
                </svg>
                <input
                  type="search"
                  className="input"
                  placeholder='Search for a topic, for example "tickets"'
                  aria-label="Search notifications"
                  value={query}
                  onChange={(e) => {
                    // QA #528: a search is not a setting, so it must not mark the form unsaved.
                    e.stopPropagation();
                    setQuery(e.target.value);
                  }}
                  onInput={(e) => e.stopPropagation()}
                />
                {query ? (
                  <button type="button" aria-label="Clear search" onClick={() => setQuery('')}>
                    ×
                  </button>
                ) : null}
              </div>

              <div className="os-tabbar sn-view-tabs">
                <nav className="os-tabs" aria-label="Notification view tabs">
                  {VIEW_TABS.map((tab) => (
                    <a
                      key={tab.id}
                      className={view === tab.id ? 'os-tab is-active' : 'os-tab'}
                      href={`#${tab.id}`}
                      role="tab"
                      aria-selected={view === tab.id}
                      aria-current={view === tab.id ? 'page' : undefined}
                      onClick={(event) => {
                        event.preventDefault();
                        setView(tab.id);
                      }}
                    >
                      {tab.label}
                    </a>
                  ))}
                </nav>
              </div>

              {view === 'most_received' ? (
                <section className="sn-most-received-view">
                  <p className="sn-tab-subhead">
                    This list updates automatically based on the notifications you receive in the
                    last 7 days.
                  </p>
                  {!most ? (
                    <p className="sn-most-empty">Loading…</p>
                  ) : mostCards.length === 0 ? (
                    <p className="sn-most-empty">
                      {query.trim()
                        ? `No results for "${query.trim()}"`
                        : 'No notifications in the last 7 days.'}
                    </p>
                  ) : (
                    <div className="sn-most-received-list">
                      {mostCards.map(({ key, count, topic }) => {
                        const on = rowIsOn(topic, draft.topics);
                        const channels = onChannelLabels(topic, draft.topics);
                        return (
                          <div key={key} className="sn-most-card">
                            <div className="sn-most-card-copy">
                              <div className="sn-most-card-title-row">
                                <strong className="sn-most-card-title">{topic.title}</strong>
                                <span
                                  className="sn-most-info"
                                  tabIndex={0}
                                  title={topic.description}
                                  aria-label={topic.description}
                                >
                                  <svg
                                    className="icon iconSize-14"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    strokeWidth="1.8"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    aria-hidden="true"
                                    focusable="false"
                                  >
                                    <circle cx="12" cy="12" r="9" />
                                    <path d="M12 11v5M12 8h.01" />
                                  </svg>
                                </span>
                                <span className="sn-most-badge">
                                  {count === 1 ? '1 received' : `${count} received`}
                                </span>
                              </div>
                              {channels ? (
                                <div className="sn-most-card-channels">{channels}</div>
                              ) : null}
                            </div>
                            <div className="sn-most-card-actions">
                              <button
                                type="button"
                                className="sn-manage-button sn-manage-button--pill"
                                onClick={() => setDetailKey(topic.key)}
                              >
                                Manage
                              </button>
                              <label className="sn-switch">
                                <input
                                  type="checkbox"
                                  checked={on}
                                  onChange={(event) => setTopicOn(topic, event.target.checked)}
                                />
                                <span aria-hidden="true">
                                  <svg
                                    className="sn-switch-check"
                                    viewBox="0 0 16 16"
                                    focusable="false"
                                  >
                                    <path d="m3.5 8.2 2.8 2.8 6.2-6.2" />
                                  </svg>
                                </span>
                                <b>{on ? 'ON' : 'OFF'}</b>
                              </label>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </section>
              ) : null}

              {view === 'all_notifications' ? (
                <>
                  <div className="sn-notification-heading">
                    <div>
                      <h2>All notifications</h2>
                      <div className="sn-status-filter">
                        <span>Notification status</span>
                        <div className="sn-status-dropdown">
                          <button
                            type="button"
                            className="sn-status-trigger"
                            aria-haspopup="listbox"
                            aria-expanded={statusOpen}
                            onClick={() => setStatusOpen((v) => !v)}
                          >
                            <span>
                              {status === 'all'
                                ? 'All'
                                : status === 'on'
                                  ? 'Turned on'
                                  : 'Turned off'}
                            </span>
                            <svg viewBox="0 0 12 12" aria-hidden="true">
                              <path d="m2 4 4 4 4-4" />
                            </svg>
                          </button>
                          {statusOpen ? (
                            <div className="sn-status-menu" role="listbox">
                              {(
                                [
                                  ['all', 'All'],
                                  ['on', 'Turned on'],
                                  ['off', 'Turned off'],
                                ] as const
                              ).map(([value, label]) => (
                                <button
                                  key={value}
                                  type="button"
                                  role="option"
                                  aria-selected={status === value}
                                  onClick={() => {
                                    setStatus(value);
                                    setStatusOpen(false);
                                  }}
                                >
                                  {label}
                                </button>
                              ))}
                            </div>
                          ) : null}
                        </div>
                      </div>
                      {query ? (
                        <p className="sn-search-results">
                          {visibleCount} results for &quot;{query.trim()}&quot;
                        </p>
                      ) : null}
                    </div>
                    <div className="sn-heading-actions">
                      <button
                        type="button"
                        className="sn-text-action"
                        onClick={() => {
                          const topics = filtered;
                          const allExpanded =
                            topics.length > 0 && topics.every((g) => expanded[g.name]);
                          const next: Record<string, boolean> = { ...expanded };
                          topics.forEach((g) => {
                            next[g.name] = !allExpanded;
                          });
                          setExpanded(next);
                        }}
                      >
                        {filtered.length > 0 && filtered.every((g) => expanded[g.name])
                          ? 'Collapse all topics'
                          : 'Expand all topics'}
                      </button>
                      <span aria-hidden="true">|</span>
                      <button
                        type="button"
                        className="sn-text-action"
                        onClick={() => turnAllTopics(allOffMode)}
                      >
                        {allOffMode ? 'Turn on all topics' : 'Turn off all topics'}
                      </button>
                      <span
                        className="sn-info sn-info-tip"
                        tabIndex={0}
                        role="img"
                        data-tip="Turn off or turn on notifications for all topics."
                        aria-label="Turn off or turn on notifications for all topics."
                      >
                        ⓘ
                      </span>
                    </div>
                  </div>

                  <div className="sn-notification-matrix">
                    <div className="sn-matrix-head" role="row">
                      <div className="sn-matrix-topic" role="columnheader" />
                      <div className="sn-matrix-sound-head" role="columnheader" />
                      {CHANNELS.map((channel) => {
                        const values: boolean[] = [];
                        for (const group of draft.catalog) {
                          for (const item of group.items) {
                            if (!topicHasChannel(item, channel)) continue;
                            values.push(!!draft.topics[item.key]?.[channel]);
                          }
                        }
                        const agg = aggregate(values);
                        return (
                          <div key={channel} className="sn-channel-head" role="columnheader">
                            <span className="sn-channel-icon" aria-hidden="true">
                              <ChannelIcon channel={channel} />
                            </span>
                            <span>{CHANNEL_LABELS[channel]}</span>
                            <CheckBox
                              checked={agg.checked}
                              indeterminate={agg.indeterminate}
                              ariaLabel={`Toggle all ${CHANNEL_LABELS[channel]} notifications`}
                              onChange={(next) => setChannelEverywhere(channel, next)}
                            />
                          </div>
                        );
                      })}
                    </div>

                    <div className="sn-topic-list">
                      {filtered.map((group) => {
                        const isOpen = !!expanded[group.name] || !!query;
                        if (group.name === WEBSITE_VISITS_GROUP) {
                          return (
                            <section
                              key={group.name}
                              className="sn-topic"
                              data-topic
                              data-topic-name={group.name}
                              data-topic-custom="true"
                            >
                              <div
                                className={cn(
                                  'sn-topic-summary sn-topic-summary--custom',
                                  isOpen && 'is-expanded',
                                )}
                              >
                                <button
                                  type="button"
                                  className="sn-topic-toggle"
                                  aria-expanded={isOpen}
                                  onClick={() =>
                                    setExpanded((prev) => ({ ...prev, [group.name]: !isOpen }))
                                  }
                                >
                                  <svg
                                    className="sn-chevron"
                                    viewBox="0 0 16 16"
                                    aria-hidden="true"
                                  >
                                    <path d="m5 3 5 5-5 5" />
                                  </svg>
                                  <strong>{group.name}</strong>
                                </button>
                              </div>
                              {isOpen ? (
                                <WebsiteVisitsPanel
                                  draft={draft}
                                  onScope={(field, scope) =>
                                    patchDraft((prev) => ({
                                      ...prev,
                                      websiteVisits: { ...prev.websiteVisits, [field]: scope },
                                    }))
                                  }
                                  onChannel={(topicKey, channel, on) =>
                                    setTopicChannel(topicKey, channel, on)
                                  }
                                />
                              ) : null}
                            </section>
                          );
                        }
                        return (
                          <section
                            key={group.name}
                            className="sn-topic"
                            data-topic
                            data-topic-name={group.name}
                          >
                            <div className={cn('sn-topic-summary', isOpen && 'is-expanded')}>
                              <button
                                type="button"
                                className="sn-topic-toggle"
                                aria-expanded={isOpen}
                                onClick={() =>
                                  setExpanded((prev) => ({
                                    ...prev,
                                    [group.name]: !isOpen,
                                  }))
                                }
                              >
                                <svg className="sn-chevron" viewBox="0 0 16 16" aria-hidden="true">
                                  <path d="m5 3 5 5-5 5" />
                                </svg>
                                <strong>{group.name}</strong>
                              </button>
                              <span className="sn-topic-sound-label">POP-UP SOUND</span>
                              {CHANNELS.map((channel) => {
                                const values = group.items
                                  .filter((item) => topicHasChannel(item, channel))
                                  .map((item) => !!draft.topics[item.key]?.[channel]);
                                if (values.length === 0) {
                                  return (
                                    <span
                                      key={channel}
                                      className={`sn-topic-master-cell sn-topic-master-cell--${channel}`}
                                    >
                                      <span className="sn-not-available">--</span>
                                    </span>
                                  );
                                }
                                const agg = aggregate(values);
                                return (
                                  <span
                                    key={channel}
                                    className={`sn-topic-master-cell sn-topic-master-cell--${channel}`}
                                  >
                                    <CheckBox
                                      checked={agg.checked}
                                      indeterminate={agg.indeterminate}
                                      ariaLabel={`${group.name} - ${channel}`}
                                      onChange={(next) =>
                                        setChannelEverywhere(channel, next, group.name)
                                      }
                                    />
                                  </span>
                                );
                              })}
                            </div>

                            {isOpen ? (
                              <div className="sn-topic-rows">
                                {group.items.map((item) => (
                                  <div
                                    key={item.key}
                                    className="sn-notification-row"
                                    data-notification-row
                                  >
                                    <div className="sn-notification-copy">
                                      <div className="sn-notification-copy-text">
                                        <button
                                          type="button"
                                          className="sn-notification-open sn-notification-name"
                                          onClick={() => setDetailKey(item.key)}
                                        >
                                          {item.title}
                                        </button>
                                        <p>{item.description}</p>
                                      </div>
                                      <button
                                        type="button"
                                        className="sn-manage-button"
                                        onClick={() => setDetailKey(item.key)}
                                      >
                                        Manage
                                      </button>
                                    </div>
                                    <RowSound
                                      item={item}
                                      popupOn={!!draft.topics[item.key]?.popup}
                                      sound={draft.sounds[item.key]}
                                      playing={playingId === `row:${item.key}`}
                                      onPlay={() =>
                                        togglePlayback(
                                          `row:${item.key}`,
                                          draft.sounds[item.key] ||
                                            draft.defaultSound ||
                                            'Default (Whizz)',
                                        )
                                      }
                                      onOpenMenu={(anchor) =>
                                        openSoundMenu('topic', item.key, anchor)
                                      }
                                    />
                                    {CHANNELS.map((channel) => (
                                      <div key={channel} className="sn-notification-channel">
                                        {topicHasChannel(item, channel) ? (
                                          <CheckBox
                                            checked={!!draft.topics[item.key]?.[channel]}
                                            ariaLabel={`${item.title} - ${channel}${
                                              channel === 'mobile'
                                                ? ' (delivered by mobile app later)'
                                                : !channelDeliverable(draft.channelStatus, channel)
                                                  ? ' (coming soon)'
                                                  : ''
                                            }`}
                                            onChange={(next) =>
                                              setTopicChannel(item.key, channel, next)
                                            }
                                          />
                                        ) : (
                                          <span className="sn-not-available">--</span>
                                        )}
                                      </div>
                                    ))}
                                  </div>
                                ))}
                              </div>
                            ) : null}
                          </section>
                        );
                      })}
                    </div>

                    {visibleCount === 0 ? (
                      <div className="sn-notification-empty">
                        <div className="sn-empty-art" aria-hidden="true">
                          <svg viewBox="0 0 100 90">
                            <circle cx="42" cy="32" r="20" />
                            <path d="m57 47 20 20M25 32h34M42 15v34M66 14l10-8M71 26h15" />
                          </svg>
                        </div>
                        <strong>No notifications found.</strong>
                        <button
                          type="button"
                          className="sn-text-action"
                          onClick={() => {
                            setQuery('');
                            setStatus('all');
                          }}
                        >
                          Clear filters
                        </button>
                      </div>
                    ) : null}
                  </div>
                </>
              ) : null}
            </>
          ) : detail ? (
            <section className="sn-detail-view">
              <button type="button" className="sn-back-link" onClick={() => setDetailKey(null)}>
                <svg viewBox="0 0 16 16" aria-hidden="true">
                  <path d="m10 3-5 5 5 5" />
                </svg>
                {view === 'most_received' ? 'Back to most received' : 'Back to all notifications'}
              </button>
              <h2>{detail.topic.title}</h2>
              <div className="sn-detail-allow">
                <div>
                  <strong>Allow notifications</strong>
                  <p>{detail.topic.description}</p>
                </div>
                <label className="sn-switch">
                  <input
                    type="checkbox"
                    checked={rowIsOn(detail.topic, draft.topics)}
                    onChange={(e) => {
                      const on = e.target.checked;
                      const topicKey = detail.topic.key;
                      const topicDef = detail.topic;
                      patchDraft((prev) => {
                        const row = { ...prev.topics[topicKey] };
                        for (const channel of CHANNELS) {
                          if (topicHasChannel(topicDef, channel)) row[channel] = on;
                        }
                        return {
                          ...prev,
                          topics: { ...prev.topics, [topicKey]: row },
                        };
                      });
                    }}
                  />
                  <span aria-hidden="true" />
                  <b>{rowIsOn(detail.topic, draft.topics) ? 'ON' : 'OFF'}</b>
                </label>
              </div>
              <div className="sn-detail-columns">
                <section className="sn-detail-channels">
                  <h3>Channels</h3>
                  <p>
                    Choose where you want to see your {detail.topic.title.replace(/[.!?]$/, '')}{' '}
                    notifications.
                  </p>
                  {DETAIL_CHANNELS.map((channel) => {
                    const isExtra = channel === 'google_chat' || channel === 'microsoft_teams';
                    const matrixChannel = channel as NotificationChannel;
                    const available = !isExtra && topicHasChannel(detail.topic, matrixChannel);
                    const label =
                      channel === 'google_chat'
                        ? 'Google Chat'
                        : channel === 'microsoft_teams'
                          ? 'Microsoft Teams'
                          : CHANNEL_LABELS[matrixChannel];
                    return (
                      <MethodToggle
                        key={channel}
                        checked={
                          available ? !!draft.topics[detail.topic.key]?.[matrixChannel] : false
                        }
                        disabled={!available}
                        onChange={(next) => {
                          if (!available) return;
                          setTopicChannel(detail.topic.key, matrixChannel, next);
                        }}
                      >
                        {label}
                      </MethodToggle>
                    );
                  })}
                </section>
                <section className="sn-detail-additional">
                  <h3>Additional preferences</h3>
                  <label>
                    Sound <small>Only applicable to pop-ups</small>
                  </label>
                  <div className="sn-sound-controls">
                    <div className="sn-sound-wrap">
                      <button
                        type="button"
                        className="sn-sound-select sn-sound-select--detail"
                        disabled={!draft.topics[detail.topic.key]?.popup}
                        onClick={(event) =>
                          openSoundMenu('detail', detail.topic.key, event.currentTarget)
                        }
                      >
                        <span>
                          {draft.sounds[detail.topic.key] || draft.defaultSound || 'Default'}
                        </span>
                        <svg viewBox="0 0 12 12" aria-hidden="true">
                          <path d="m2 4 4 4 4-4" />
                        </svg>
                      </button>
                    </div>
                    <PlaySoundButton
                      playing={playingId === `detail:${detail.topic.key}`}
                      disabled={!draft.topics[detail.topic.key]?.popup}
                      onClick={() =>
                        togglePlayback(
                          `detail:${detail.topic.key}`,
                          draft.sounds[detail.topic.key] || draft.defaultSound || 'Default (Whizz)',
                        )
                      }
                    />
                  </div>
                </section>
              </div>
              {(() => {
                // Design "Do you want fewer notifications?": the other topics of this group that
                // are on, each with its switch and a link to manage it.
                const similar = (
                  draft.catalog.find((g) => g.name === detail.group)?.items ?? []
                ).filter((t) => t.key !== detail.topic.key && rowIsOn(t, draft.topics));
                return (
                  <section className="sn-detail-fewer">
                    <h3>Do you want fewer notifications?</h3>
                    <p>
                      There {similar.length === 1 ? 'is' : 'are'} {similar.length} similar
                      notification{similar.length === 1 ? '' : 's'} you could turn off or adjust
                      {similar.length ? ':' : '.'}
                    </p>
                    {similar.length ? (
                      <ul>
                        {similar.map((t) => (
                          <li key={t.key}>
                            <div>
                              <strong>{t.title}</strong>
                              <span>{onChannelLabels(t, draft.topics)}</span>
                            </div>
                            <button
                              type="button"
                              className="sn-text-action"
                              onClick={() => setDetailKey(t.key)}
                            >
                              Manage
                            </button>
                            <label className="sn-switch">
                              <input
                                type="checkbox"
                                checked
                                aria-label={`Turn off ${t.title}`}
                                onChange={() => setTopicOn(t, false)}
                              />
                              <span aria-hidden="true" />
                              <b>ON</b>
                            </label>
                          </li>
                        ))}
                      </ul>
                    ) : null}
                  </section>
                );
              })()}
            </section>
          ) : null}

          <aside
            className={cn(
              'sn-defaults-drawer',
              drawerOpen && 'is-open',
              appsView && 'sn-apps-view-open',
            )}
            aria-hidden={!drawerOpen}
          >
            <div className="sn-drawer-head">
              {appsView ? (
                <button
                  type="button"
                  className="sn-apps-back"
                  aria-label="Back to channel defaults"
                  onClick={() => setAppsView(false)}
                >
                  <svg viewBox="0 0 16 16" aria-hidden="true">
                    <path d="m10 3-5 5 5 5" />
                  </svg>
                </button>
              ) : null}
              <h2>{appsView ? 'Select an app' : 'Set channel defaults'}</h2>
              <button type="button" className="sn-close" aria-label="Close" onClick={closeDefaults}>
                <svg viewBox="0 0 16 16" aria-hidden="true">
                  <path d="m3 3 10 10M13 3 3 13" />
                </svg>
              </button>
            </div>
            {!appsView ? (
              <div className="sn-drawer-body">
                <h3>Select your notification method</h3>
                {(
                  [
                    ['email', 'Email', 'Sent to your email address.'],
                    ['slack', 'Slack', ''],
                    ['bell', 'Bell', 'Found in the CRM navigation bar.'],
                    ['browser', 'Browser', 'Appear when the CRM tab is inactive.'],
                    ['popup', 'Pop-up', 'Show briefly and play a sound.'],
                  ] as const
                ).map(([key, label, help]) => (
                  <label key={key} className="sn-default-channel">
                    <span className="sn-method-check">
                      <input
                        type="checkbox"
                        checked={draft.channelDefaults[key]}
                        onChange={(e) => {
                          const checked = e.target.checked;
                          patchDraft((prev) => {
                            const topics = { ...prev.topics };
                            for (const group of prev.catalog) {
                              for (const item of group.items) {
                                if (!topicHasChannel(item, key)) continue;
                                topics[item.key] = {
                                  ...topics[item.key],
                                  [key]: checked,
                                };
                              }
                            }
                            return {
                              ...prev,
                              channelDefaults: {
                                ...prev.channelDefaults,
                                [key]: checked,
                              },
                              topics,
                            };
                          });
                        }}
                      />
                      <span className="sn-method-box" aria-hidden="true">
                        <svg className="sn-toggle-check" viewBox="0 0 16 16" focusable="false">
                          <path d="m3.5 8.2 2.8 2.8 6.2-6.2" />
                        </svg>
                      </span>
                    </span>
                    <span>
                      <strong>{label}</strong>
                      {help ? <small>{help}</small> : null}
                    </span>
                  </label>
                ))}
                <div className="sn-mobile-note">
                  <strong>Mobile</strong>
                  <p>
                    Turn on mobile notifications on your device settings. Requires the CRM mobile
                    app.
                  </p>
                </div>
                <div className="sn-drawer-divider" />
                <h3>Sound</h3>
                <p className="sn-drawer-muted">Only applicable to pop-ups</p>
                <div className="sn-sound-controls">
                  <div className="sn-sound-wrap">
                    <button
                      type="button"
                      className="sn-sound-select"
                      disabled={!draft.channelDefaults.popup}
                      onClick={(event) => openSoundMenu('default', '_default', event.currentTarget)}
                    >
                      <span>{draft.defaultSound || 'Default'}</span>
                      <svg viewBox="0 0 12 12" aria-hidden="true">
                        <path d="m2 4 4 4 4-4" />
                      </svg>
                    </button>
                  </div>
                  <PlaySoundButton
                    playing={playingId === 'default'}
                    disabled={!draft.channelDefaults.popup}
                    onClick={() =>
                      togglePlayback('default', draft.defaultSound || 'Default (Whizz)')
                    }
                  />
                </div>
                <div className="sn-third-party">
                  <strong>Third party apps</strong>
                  <p>Manage notifications directly from your connected apps.</p>
                  <div className="sn-third-party-bottom">
                    <button
                      type="button"
                      className="sn-view-apps"
                      onClick={() => setAppsView(true)}
                    >
                      View apps
                    </button>
                    <div className="sn-app-icons" aria-label="Connected apps">
                      <span className="sn-app-icon sn-app-icon--chat" aria-label="Google Chat" />
                      <span
                        className="sn-app-icon sn-app-icon--teams"
                        aria-label="Microsoft Teams"
                      />
                      <span className="sn-app-icon sn-app-icon--slack" aria-label="Slack" />
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="sn-apps-view">
                <div className="sn-apps-section-title">Third party apps</div>
                <article className="sn-app-card sn-app-card--slack">
                  <div className="sn-app-card-icon sn-app-card-icon--slack" aria-hidden="true">
                    ⌁
                  </div>
                  <div className="sn-app-card-copy">
                    <strong>Slack</strong>
                    <p>
                      By CRM · Uses workspace Slack connection, or SLACK_NOTIFICATION_WEBHOOK_URL
                      when set
                    </p>
                  </div>
                  <span className="sn-app-status sn-app-status--muted">Ready</span>
                </article>
                <article className="sn-app-card">
                  <div className="sn-app-card-icon sn-app-card-icon--chat" aria-hidden="true">
                    ◎
                  </div>
                  <div className="sn-app-card-copy">
                    <strong>Google Chat</strong>
                    <p>By CRM · Coming soon</p>
                  </div>
                </article>
              </div>
            )}
            {!appsView ? (
              <div className="sn-drawer-foot">Changes are saved with the page save bar.</div>
            ) : null}
          </aside>
          {drawerOpen ? <div className="sn-drawer-backdrop" onClick={closeDefaults} /> : null}

          {soundMenu ? (
            <div
              className="sn-sound-menu sn-sound-menu-portal"
              role="listbox"
              aria-label="Choose notification sound"
              style={{
                position: 'fixed',
                top: soundMenu.top,
                left: soundMenu.left,
                zIndex: 99999,
                minWidth: 220,
              }}
            >
              {NOTIFICATION_SOUNDS.map((option) => (
                <button
                  key={option}
                  type="button"
                  role="option"
                  aria-selected={
                    option ===
                    (soundMenu.kind === 'default'
                      ? draft.defaultSound
                      : draft.sounds[soundMenu.key] || draft.defaultSound)
                  }
                  onClick={() => {
                    if (soundMenu.kind === 'default') {
                      patchDraft((prev) => ({ ...prev, defaultSound: option }));
                    } else {
                      const topicKey = soundMenu.key;
                      patchDraft((prev) => ({
                        ...prev,
                        sounds: { ...prev.sounds, [topicKey]: option },
                      }));
                    }
                    setSoundMenu(null);
                  }}
                >
                  <SoundOptionIcon name={option} />
                  {option}
                </button>
              ))}
            </div>
          ) : null}
        </section>
      </SettingsForm>
    </SettingsFormsProvider>
  );
}
