import type { Editor } from '@tiptap/react'

/**
 * Singleton registry for the most-recently focused TipTap editor in the
 * admin shell. Lets out-of-tree surfaces (Cmd+K palette, slash commands,
 * future global shortcuts) target the editor a user was last working in
 * without prop-drilling refs through the layout.
 *
 * The `TipTapEditor` component calls `setActiveEditor(editor)` from its
 * `onFocus` callback and clears it on unmount. Subscribers receive a no-op
 * payload — they should re-read via `getActiveEditor()` after the
 * notification.
 */

let activeEditor: Editor | null = null
const listeners = new Set<() => void>()

export function setActiveEditor(editor: Editor | null): void {
  if (activeEditor === editor) return
  activeEditor = editor
  for (const listener of listeners) listener()
}

export function getActiveEditor(): Editor | null {
  return activeEditor
}

export function clearActiveEditorIf(editor: Editor): void {
  if (activeEditor === editor) {
    setActiveEditor(null)
  }
}

export function subscribeActiveEditor(listener: () => void): () => void {
  listeners.add(listener)
  return () => {
    listeners.delete(listener)
  }
}
