const LS_KEY = 'mh-event';
const CHANNEL = 'mh-sync';

export type MhEvent =
  | { kind: 'login'; at?: number }
  | { kind: 'logout'; at?: number }
  | { kind: 'mutation'; at?: number };

export function broadcastMhEvent(event: MhEvent): void {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(LS_KEY, JSON.stringify(event));
  } catch (err) {
    void err; // localStorage may be unavailable (private mode, quota exceeded)
  }
  try {
    new BroadcastChannel(CHANNEL).postMessage(event);
  } catch (err) {
    void err; // BroadcastChannel unavailable in some environments
  }
  window.dispatchEvent(new CustomEvent('mh:changed'));
}

export function listenMhEvents(handler: (e: MhEvent) => void): () => void {
  if (typeof window === 'undefined') return () => {};

  const onStorage = (e: StorageEvent) => {
    if (e.key !== LS_KEY || !e.newValue) return;
    try {
      handler(JSON.parse(e.newValue) as MhEvent);
    } catch (err) {
      void err; // Malformed event — ignore
    }
  };
  window.addEventListener('storage', onStorage);

  let bc: BroadcastChannel | null = null;
  try {
    bc = new BroadcastChannel(CHANNEL);
    bc.onmessage = (msg) => handler(msg.data as MhEvent);
  } catch (err) {
    void err; // BroadcastChannel unavailable
  }

  return () => {
    window.removeEventListener('storage', onStorage);
    bc?.close();
  };
}
