// Window-focus tracking. Under Electron the renderer's `window` matches
// a single BrowserWindow, and Chromium's focus/blur events fire when
// that window gains/loses OS-foreground status, so DOM events are
// authoritative — no IPC bridge needed.
//
// One synchronous getter + one subscriber so callers can mirror the
// value into a ref for fast-path reads inside realtime callbacks.

type Listener = (focused: boolean) => void;

// Optimistic default — if we don't know yet, assume focused so the
// first few events after app start behave like "user is here" rather
// than spamming sounds during the init window.
let cached = true;
let initialized = false;
const listeners = new Set<Listener>();

function emit(next: boolean): void {
  if (next === cached) return;
  cached = next;
  for (const l of listeners) {
    try {
      l(next);
    } catch (err: unknown) {
      console.warn('windowFocus listener threw', err);
    }
  }
}

function ensureInit(): void {
  if (initialized) return;
  initialized = true;
  if (typeof window === 'undefined') return;
  cached = typeof document !== 'undefined' ? document.hasFocus() : true;
  window.addEventListener('focus', () => emit(true));
  window.addEventListener('blur', () => emit(false));
}

ensureInit();

export function getIsWindowFocused(): boolean {
  return cached;
}

export function subscribeWindowFocus(l: Listener): () => void {
  listeners.add(l);
  return () => {
    listeners.delete(l);
  };
}
