import { useEffect, useRef } from 'react';
import useEngineContext from "../../../hooks/useEngineContext";
/**
 * 原生扫码枪事件名，对齐宿主端约定（与 `@pisell/materials` 的 PisellFind 保持一致）。
 */
export var SCAN_RESULT_EVENT = 'nativeScanResult';
/**
 * 监听宿主扫码枪事件。
 *
 * 复用 PisellFind 的实现要点：
 * 1. 用 ref 稳定 `getApp` 引用 —— 低代码环境下 engineContext 每次渲染可能返回新引用，
 *    若放进 effect 依赖会导致频繁 unsubscribe/subscribe（甚至漏事件），故 effect 依赖只保留 `enabled`。
 * 2. 用 ref 持有最新 `onScan`，避免回调闭包 stale。
 * 3. 非法 payload（无 data 或 data 为空串）直接忽略，避免误清空输入框 / 搜索条件。
 *
 * @example
 * ```ts
 * useScannerGun({
 *   enabled: true,
 *   onScan: (payload) => setKeyword(payload.data),
 * });
 * ```
 */
var useScannerGun = function useScannerGun(_ref) {
  var _context$appHelper;
  var _ref$enabled = _ref.enabled,
    enabled = _ref$enabled === void 0 ? false : _ref$enabled,
    onScan = _ref.onScan;
  /** 最新回调引用，避免回调闭包 stale */
  var onScanRef = useRef(onScan);
  onScanRef.current = onScan;
  var context = useEngineContext();
  /** 稳定 getApp 引用：仅在确为函数时缓存 */
  var getAppRef = useRef(undefined);
  getAppRef.current = typeof (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.getApp) === 'function' ? context.appHelper.utils.getApp : undefined;
  useEffect(function () {
    if (!enabled) return undefined;
    var getApp = getAppRef.current;
    if (typeof getApp !== 'function') return undefined;
    var app = getApp();
    var pubsub = app === null || app === void 0 ? void 0 : app.pubsub;
    if (!pubsub || typeof pubsub.subscribe !== 'function') {
      return undefined;
    }
    var handler = function handler(payload) {
      var _onScanRef$current;
      var data = payload === null || payload === void 0 ? void 0 : payload.data;
      if (typeof data !== 'string' || data.length === 0) {
        return;
      }
      (_onScanRef$current = onScanRef.current) === null || _onScanRef$current === void 0 || _onScanRef$current.call(onScanRef, payload);
    };
    try {
      pubsub.subscribe(SCAN_RESULT_EVENT, handler);
    } catch (e) {
      console.warn('[ComprehensiveSearch] subscribe scanner failed:', e);
      return undefined;
    }
    return function () {
      try {
        var _pubsub$unsubscribe;
        (_pubsub$unsubscribe = pubsub.unsubscribe) === null || _pubsub$unsubscribe === void 0 || _pubsub$unsubscribe.call(pubsub, SCAN_RESULT_EVENT, handler);
      } catch (e) {
        console.warn('[ComprehensiveSearch] unsubscribe scanner failed:', e);
      }
    };
  }, [enabled]);
};
export default useScannerGun;