import type {Crumb, Trail} from '@crumbs/core/schemas'

// cross-store entity sync: a mutation publishes the fresh entity (or its
// removal) once and every store holding a copy subscribes — one mechanism
// instead of pairwise imports between stores, so an edited crumb can never
// linger stale in a place list, profile tab, search result or trail detail

type Handler<T> = (value: T) => void

const channel = <T>() => {
  const handlers = new Set<Handler<T>>()
  return {
    subscribe: (handler: Handler<T>): void => {
      handlers.add(handler)
    },
    publish: (value: T): void => {
      for (const handler of handlers) handler(value)
    },
  }
}

export const crumbSynced = channel<Crumb>()
export const crumbDropped = channel<string>()
// trail edits carry a patch rather than a full summary: mutation sites only
// know the changed fields, and each holder applies them to its own copy
export const trailPatched = channel<{
  id: string
  patch: (trail: Trail) => Trail
}>()
export const trailDropped = channel<string>()
