/**
 * Forms event bus — a minimal pub/sub so views that mutate submission state
 * (mark read/unread, star, archive) or form state (create, notify toggle,
 * archive) can tell the sidebar to refresh its unread badges immediately,
 * without threading a refresh callback through the whole component tree.
 *
 * Deliberately tiny and dependency-free: one event, synchronous fan-out,
 * SSR-safe. Subscribers must unsubscribe on unmount via the returned
 * disposer to avoid leaks.
 */
type Listener = () => void

const listeners = new Set<Listener>()

/** Subscribe to "forms data changed" notifications. Returns an unsubscribe fn. */
export function onFormsChanged(listener: Listener): () => void {
  listeners.add(listener)
  return () => {
    listeners.delete(listener)
  }
}

/** Notify all subscribers that forms/submission counts may have changed. */
export function emitFormsChanged(): void {
  for (const listener of listeners) {
    try {
      listener()
    } catch {
      // A misbehaving subscriber must not break sibling subscribers.
    }
  }
}
