import { useSyncExternalStore } from "react"; export const SETTINGS_CONFLICT_EVENT = "b3-swatches:settings-conflict"; const SETTINGS_CONFLICT_STATE_KEY = "__b3WvsSettingsConflict"; type ConflictWindow = Window & Record; function getConflictWindow(): ConflictWindow | null { return typeof window === "undefined" ? null : (window as unknown as ConflictWindow); } export function getSettingsConflict(): boolean { return getConflictWindow()?.[SETTINGS_CONFLICT_STATE_KEY] === true; } function publishSettingsConflict(conflicted: boolean): void { const target = getConflictWindow(); if (!target || getSettingsConflict() === conflicted) return; target[SETTINGS_CONFLICT_STATE_KEY] = conflicted; target.dispatchEvent( new CustomEvent(SETTINGS_CONFLICT_EVENT, { detail: conflicted, }), ); } export function notifySettingsConflict(): void { publishSettingsConflict(true); } /** Clear the shared fence only after an explicit successful Reload latest. */ export function clearSettingsConflictAfterReload(): void { publishSettingsConflict(false); } export function subscribeSettingsConflict(listener: () => void): () => void { const target = getConflictWindow(); if (!target) return () => undefined; target.addEventListener(SETTINGS_CONFLICT_EVENT, listener); return () => target.removeEventListener(SETTINGS_CONFLICT_EVENT, listener); } export function useSettingsConflict(): boolean { return useSyncExternalStore( subscribeSettingsConflict, getSettingsConflict, () => false, ); }