require("../../../_virtual/_rolldown/runtime.js");
const require_asyncToGenerator = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../hooks/useEngineContext.js");
const require_IsActiveContext = require("../context/IsActiveContext.js");
const require_useRuntime = require("./useRuntime.js");
const require_sync = require("../sync.js");
let react = require("react");
let ahooks = require("ahooks");
//#region src/components/ticketBooking/hooks/useSync.ts
/**
* 双屏数据同步 hook，负责主屏与副屏之间的实时数据同步。
*
* 根据当前运行时角色（runtime.type）自动切换行为：
* - **主屏（main）**：订阅 store 变更，通过 unifiedCommunication SDK
*   将格式化后的数据以 `sync_card` 类型发布到副屏。
*   首次变更立即发送，后续变更防抖 2s（leading + trailing）。
* - **副屏（secondary-screen）**：监听 SDK 消息，将接收到的数据
*   通过 mergeSyncData 合并回 store，实现副屏状态同步。
*
* @param store - miniRedux Store 实例，需在组件顶层创建后传入
*
* @example
* ```tsx
* // 在根组件中使用
* const storeRef = useRef(createStore(initialState));
* useSync(storeRef.current);
* ```
*/
function useSync(store) {
	var _context$appHelper, _context$appHelper$ge;
	const context = require_useEngineContext.default();
	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 isActive = require_IsActiveContext.useIsActive();
	const currentModule = (0, react.useRef)(Math.random());
	const { runtime, isSecondaryScreen } = (require_useRuntime.useRuntime === null || require_useRuntime.useRuntime === void 0 ? void 0 : require_useRuntime.useRuntime()) || {
		runtime: null,
		isSecondaryScreen: false
	};
	console.log("runtimeruntime", runtime);
	console.log(currentModule.current, isActive, "currentModule isActive");
	/**
	* 防抖发送：首次调用立即执行，2s 内的后续调用合并为一次，
	* 窗口结束后执行最后一次（trailing），确保最终状态被同步。
	*/
	const { run: debouncedSend } = (0, ahooks.useDebounceFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (key) {
			try {
				var _app$getPlugin, _window;
				console.log(key, isActive, "key1234");
				if (key === "date") return;
				if (isSecondaryScreen || !isActive) return;
				console.log("[useSync] 主屏 防抖发送数据", store.getState());
				const formattedData = require_sync.formatSyncData(store.getState());
				yield 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 = _app$getPlugin.sdk) === null || _app$getPlugin === void 0 ? void 0 : _app$getPlugin.publishData({
					target: { type: "secondary-screen" },
					data: {
						type: "sync_card",
						data: formattedData
					},
					meta: {}
				});
				console.log("[useSync] 主屏 防抖发送数据成功", formattedData);
				(_window = window) === null || _window === void 0 || (_window = _window.app) === null || _window === void 0 || _window.logger.addLog({
					type: "info",
					title: "发送信息到副屏成功"
				});
			} catch (error) {
				var _window2;
				console.log("[useSync] 主屏 防抖发送数据失败", error);
				(_window2 = window) === null || _window2 === void 0 || (_window2 = _window2.app) === null || _window2 === void 0 || _window2.logger.addLog({
					type: "error",
					title: "发送信息到副屏失败"
				});
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), {
		wait: 1e3,
		leading: true,
		trailing: true
	});
	const { run: debouncedMessage } = (0, ahooks.useDebounceFn)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (event) {
			var _envelope$payload, _envelope$payload2;
			console.log("[useSync] 副屏 接收到的数据", event);
			const envelope = event.data;
			const payload = (_envelope$payload = envelope.payload) === null || _envelope$payload === void 0 || (_envelope$payload = _envelope$payload.data) === null || _envelope$payload === void 0 ? void 0 : _envelope$payload.data;
			if (((_envelope$payload2 = envelope.payload) === null || _envelope$payload2 === void 0 || (_envelope$payload2 = _envelope$payload2.data) === null || _envelope$payload2 === void 0 ? void 0 : _envelope$payload2.type) !== "sync_card") return;
			const mergeData = require_sync.mergeSyncData(store.getState(), payload);
			console.log("[useSync] 副屏 格式化后的数据", mergeData);
			store.setState(mergeData);
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}(), { wait: 500 });
	/** 主屏：订阅 store 变更 → 防抖发送到副屏 */
	(0, react.useEffect)(() => {
		if (isSecondaryScreen || !isActive) return;
		console.log("[useSync] 主屏 开始监听 store 变更");
		const fn = store.subscribe(debouncedSend);
		return () => {
			fn();
		};
	}, [
		store,
		runtime,
		debouncedSend,
		isActive
	]);
	/** 副屏：监听 SDK 消息 → 解析 payload 并合并到 store */
	(0, react.useEffect)(() => {
		var _app$getPlugin2;
		if (!isSecondaryScreen) return;
		/**
		* 处理从主屏接收到的同步消息。
		* 消息结构：event.data.payload.data 为经 formatSyncData 序列化后的数据。
		*/
		const handleMessage = (event) => {
			debouncedMessage(event);
		};
		const listenerHandle = app === null || app === void 0 || (_app$getPlugin2 = app.getPlugin) === null || _app$getPlugin2 === void 0 || (_app$getPlugin2 = _app$getPlugin2.call(app, "unifiedCommunication")) === null || _app$getPlugin2 === void 0 || (_app$getPlugin2 = _app$getPlugin2.sdk) === null || _app$getPlugin2 === void 0 ? void 0 : _app$getPlugin2.onMessage(handleMessage);
		/**
		* 清理监听器。onMessage 可能返回同步句柄或 Promise<句柄>，
		* 需兼容两种情况，并对 Promise 分支补充 catch 防止 unhandled rejection。
		*/
		return () => {
			if (listenerHandle && typeof listenerHandle.then === "function") listenerHandle.then((handle) => {
				var _handle$remove;
				return handle === null || handle === void 0 || (_handle$remove = handle.remove) === null || _handle$remove === void 0 ? void 0 : _handle$remove.call(handle);
			}).catch(() => {});
			else {
				var _remove;
				listenerHandle === null || listenerHandle === void 0 || (_remove = listenerHandle.remove) === null || _remove === void 0 || _remove.call(listenerHandle);
			}
		};
	}, [
		store,
		isSecondaryScreen,
		isActive,
		app
	]);
}
//#endregion
exports.useSync = useSync;
