import { pickFloorPlanDetail } from "../shopFloorPlan/shopFloorPlanPure.js";
import { useEffect, useRef } from "react";
//#region src/components/pisellFloorMapLayout/hooks/useShopFloorPlanSubscription.ts
/**
* 按 code 订阅店铺平面图：首包 Promise + WebSocket callback 均归一为 `onDetail`。
* 不包含与业务默认 {@link FloorMapViewConfig} 的合并（由调用方在 `onDetail` 或后续 useMemo 完成）。
*/
function useShopFloorPlanSubscription(params) {
	const { enabled, code, subscriberId, ensureByCode, unsubscribeQuery, onDetail, onLoadError, osServer = true } = params;
	const onDetailRef = useRef(onDetail);
	onDetailRef.current = onDetail;
	const onLoadErrorRef = useRef(onLoadError);
	onLoadErrorRef.current = onLoadError;
	const ensureByCodeRef = useRef(ensureByCode);
	ensureByCodeRef.current = ensureByCode;
	const unsubscribeQueryRef = useRef(unsubscribeQuery);
	unsubscribeQueryRef.current = unsubscribeQuery;
	useEffect(() => {
		if (!enabled) return;
		let cancelled = false;
		const subId = subscriberId;
		ensureByCodeRef.current(code, {
			osServer,
			subscriberId: subId,
			callback: (res) => {
				if (cancelled) return;
				const detail = pickFloorPlanDetail(res);
				if (!detail) return;
				onDetailRef.current(detail);
			}
		}).then((detail) => {
			if (cancelled || !detail) return;
			onDetailRef.current(detail);
		}).catch((err) => {
			if (!cancelled) {
				var _onLoadErrorRef$curre;
				(_onLoadErrorRef$curre = onLoadErrorRef.current) === null || _onLoadErrorRef$curre === void 0 || _onLoadErrorRef$curre.call(onLoadErrorRef, err);
			}
		});
		return () => {
			cancelled = true;
			unsubscribeQueryRef.current(subId);
		};
		/** ensureByCode / unsubscribeQuery 走 ref，避免调用方内联函数导致反复退订再订阅 */
	}, [
		enabled,
		code,
		subscriberId,
		osServer
	]);
}
//#endregion
export { useShopFloorPlanSubscription };
