export const CHANNEL = 'mai-call-sync'; export type SyncMessage = | { type: 'queue-update'; pendingCount: number } | { type: 'synced'; clientRequestId: string } | { type: 'dead-letter'; clientRequestId: string }; let _ch: BroadcastChannel | null = null; function ch(): BroadcastChannel | null { if (typeof window === 'undefined') return null; if (!_ch) _ch = new BroadcastChannel(CHANNEL); return _ch; } export function broadcast(msg: SyncMessage): void { ch()?.postMessage(msg); } export function subscribeBroadcast(handler: (msg: SyncMessage) => void): () => void { const c = ch(); if (!c) return () => {}; const listener = (e: MessageEvent) => handler(e.data); c.addEventListener('message', listener); return () => c.removeEventListener('message', listener); }