import { _defineProperty } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/defineProperty.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import { useSync } from "./hooks/useSync.js";
import { createContext, useContext, useEffect, useRef, useState } from "react";
//#region src/components/ticketBooking/miniRedux.tsx
var Store = class {
	constructor(initialState) {
		_defineProperty(this, "state", void 0);
		_defineProperty(this, "listeners", void 0);
		this.state = initialState;
		this.listeners = /* @__PURE__ */ new Set();
	}
	getState() {
		return this.state;
	}
	setState(partialState, callback, key) {
		console.log("partialState", partialState);
		if (typeof partialState === "function") Object.assign(this.state, partialState(this.state));
		else Object.assign(this.state, partialState);
		this.notify(key);
		if (callback) callback(this.state);
	}
	subscribe(listener) {
		this.listeners.add(listener);
		return () => {
			this.listeners.delete(listener);
		};
	}
	notify(key) {
		for (const listener of this.listeners) listener(key);
	}
	getLatestState() {
		return this.state;
	}
};
const StoreContext = createContext(null);
function Provider({ store, children }) {
	return /* @__PURE__ */ React.createElement(StoreContext.Provider, { value: store }, children);
}
function createStore(initialState) {
	return new Store(initialState);
}
function useStore() {
	var _context$appHelper, _context$appHelper$ge, _app$getPlugin, _app$getPlugin$useRun;
	const context = useEngineContext();
	const app = context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getApp) === null || _context$appHelper$ge === void 0 ? void 0 : _context$appHelper$ge.call(_context$appHelper);
	const { runtime } = (app === null || app === void 0 || (_app$getPlugin = app.getPlugin) === null || _app$getPlugin === void 0 || (_app$getPlugin = _app$getPlugin.call(app, "unifiedCommunication")) === null || _app$getPlugin === void 0 || (_app$getPlugin$useRun = _app$getPlugin.useRuntime) === null || _app$getPlugin$useRun === void 0 ? void 0 : _app$getPlugin$useRun.call(_app$getPlugin)) || {};
	const store = useContext(StoreContext);
	if (!store) throw new Error("useStore must be used within a Provider");
	const stateRef = useRef(store.getState());
	const [, forceUpdate] = useState({});
	useEffect(() => {
		return store.subscribe(() => {
			stateRef.current = store.getState();
			forceUpdate({});
		});
	}, [store, runtime]);
	useSync(store);
	useEffect(() => {
		window._bookingStore = store;
	}, []);
	return [stateRef.current, store.setState.bind(store)];
}
//#endregion
export { Provider, createStore, useStore };
