import { useSyncExternalStore } from "react"

// Globaler „Einfach/Experte"-Schalter. Einfach (Default) blendet technische
// Details (Kontext, Spec, Slots, Ko-Residenz, Lane-Routing …) aus, damit die UI
// nicht überfordert. In localStorage gemerkt; alle Consumer aktualisieren via Event.

const KEY = "mc_expert_mode"
const EVT = "mc-expert-mode-change"

const read = (): boolean => {
  try {
    return localStorage.getItem(KEY) === "true"
  } catch {
    return false
  }
}

function subscribe(cb: () => void) {
  window.addEventListener(EVT, cb)
  window.addEventListener("storage", cb)
  return () => {
    window.removeEventListener(EVT, cb)
    window.removeEventListener("storage", cb)
  }
}

export function setExpertMode(v: boolean) {
  localStorage.setItem(KEY, String(v))
  window.dispatchEvent(new Event(EVT))
}

export function useExpertMode(): boolean {
  return useSyncExternalStore(subscribe, read, () => false)
}
