import type { DocsGraphicSnapGuideState } from "./docs-graphic-snap.ts"

export const DOCS_GRAPHIC_SNAP_GUIDES_EVENT = "ultidocs:graphic-snap-guides"

let snapGuideState: DocsGraphicSnapGuideState | null = null

export function getDocsGraphicSnapGuideState(): DocsGraphicSnapGuideState | null {
  return snapGuideState
}

export function setDocsGraphicSnapGuides(state: DocsGraphicSnapGuideState | null) {
  snapGuideState = state
  if (typeof window !== "undefined") {
    window.dispatchEvent(
      new CustomEvent(DOCS_GRAPHIC_SNAP_GUIDES_EVENT, { detail: { state } })
    )
  }
}

export function clearDocsGraphicSnapGuides() {
  setDocsGraphicSnapGuides(null)
}

export function subscribeDocsGraphicSnapGuides(listener: () => void): () => void {
  if (typeof window === "undefined") return () => {}
  const handler = () => listener()
  window.addEventListener(DOCS_GRAPHIC_SNAP_GUIDES_EVENT, handler)
  return () => window.removeEventListener(DOCS_GRAPHIC_SNAP_GUIDES_EVENT, handler)
}
