import { createStoreContainer } from "./index.ts";

let globalContainer: ReturnType<typeof createStoreContainer> | undefined;
const storeGlobal = globalThis as typeof globalThis & {
  __wrnexusStoreContainer?: ReturnType<typeof createStoreContainer>;
};

export function browserStoreContainer(hydration: Record<string, unknown> = {}) {
  if (!globalContainer) {
    globalContainer = createStoreContainer({
      runtime: "client",
      hydration,
      onMutation(mutation) {
        try {
          globalThis.dispatchEvent?.(
            new CustomEvent("wrnexus:store-mutation", { detail: mutation }),
          );
        } catch {
          // Minimal DOM and non-browser runtimes may not expose CustomEvent.
        }
      },
    });
    storeGlobal.__wrnexusStoreContainer = globalContainer;
  }
  return globalContainer;
}

export async function resetBrowserStores() {
  await globalContainer?.dispose();
  globalContainer = undefined;
  delete storeGlobal.__wrnexusStoreContainer;
}
