var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/pisellGlobalSearch/hooks/useProviderSearch.ts
var useProviderSearch_exports = {};
__export(useProviderSearch_exports, {
  useProviderSearch: () => useProviderSearch
});
module.exports = __toCommonJS(useProviderSearch_exports);
var import_react = require("react");
var import_types = require("../types");
var emptyState = {
  loading: false,
  list: [],
  total: 0
};
function useProviderSearch(options) {
  const {
    keyword,
    activeTab,
    providers,
    allModePageSize,
    singleModePageSize,
    mode,
    onRealtimePatchItems
  } = options;
  const [stateMap, setStateMap] = (0, import_react.useState)(
    () => initStateMap(providers)
  );
  const controllersRef = (0, import_react.useRef)(
    /* @__PURE__ */ new Map()
  );
  const realtimeCleanupRef = (0, import_react.useRef)(
    /* @__PURE__ */ new Map()
  );
  const latestRef = (0, import_react.useRef)({
    keyword,
    activeTab,
    providers,
    allModePageSize,
    singleModePageSize,
    mode,
    onRealtimePatchItems
  });
  latestRef.current = {
    keyword,
    activeTab,
    providers,
    allModePageSize,
    singleModePageSize,
    mode,
    onRealtimePatchItems
  };
  const updateProviderState = (0, import_react.useCallback)(
    (key, patch) => {
      setStateMap((prev) => ({
        ...prev,
        [key]: {
          ...prev[key] ?? emptyState,
          ...patch
        }
      }));
    },
    []
  );
  const reportProviderTotal = (0, import_react.useCallback)(
    (key, total) => {
      setStateMap((prev) => {
        const cur = prev[key] ?? emptyState;
        if (cur.total === total) return prev;
        return {
          ...prev,
          [key]: { ...cur, total }
        };
      });
    },
    []
  );
  const patchProviderRealtimeItems = (0, import_react.useCallback)(
    (key, deltaItems) => {
      if (!Array.isArray(deltaItems) || deltaItems.length === 0) return;
      setStateMap((prev) => {
        const state = prev[key] ?? emptyState;
        const deltaMap = /* @__PURE__ */ new Map();
        deltaItems.forEach((item) => {
          const itemKey = getRealtimeItemKey(item);
          if (itemKey) deltaMap.set(itemKey, item);
        });
        if (deltaMap.size === 0) return prev;
        let changed = false;
        const nextList = (state.list ?? []).map((item) => {
          const itemKey = getRealtimeItemKey(item);
          if (!itemKey) return item;
          const nextItem = deltaMap.get(itemKey);
          if (!nextItem) return item;
          changed = true;
          return { ...item, ...nextItem };
        });
        if (!changed) return prev;
        return {
          ...prev,
          [key]: {
            ...state,
            list: nextList
          }
        };
      });
    },
    []
  );
  const runOne = (0, import_react.useCallback)(
    (provider, pageSize, keywordSnapshot, modeSnapshot, scopeSnapshot) => {
      var _a, _b;
      (_a = controllersRef.current.get(provider.key)) == null ? void 0 : _a.abort();
      (_b = realtimeCleanupRef.current.get(provider.key)) == null ? void 0 : _b();
      realtimeCleanupRef.current.delete(provider.key);
      const controller = new AbortController();
      controllersRef.current.set(provider.key, controller);
      const realtimeSubscriberId = `global-search-${String(
        provider.key
      )}-${scopeSnapshot}`;
      updateProviderState(provider.key, {
        loading: true,
        error: void 0
      });
      provider.search({
        keyword: keywordSnapshot,
        pageSize,
        signal: controller.signal,
        mode: modeSnapshot,
        scope: scopeSnapshot,
        onRealtimePatch: (items) => {
          var _a2, _b2;
          patchProviderRealtimeItems(provider.key, items);
          (_b2 = (_a2 = latestRef.current).onRealtimePatchItems) == null ? void 0 : _b2.call(_a2, provider.key, items);
        },
        realtimeSubscriberId,
        onRealtimeCleanup: (cleanup) => {
          realtimeCleanupRef.current.set(provider.key, cleanup);
        }
      }).then((result) => {
        if (controller.signal.aborted) return;
        updateProviderState(provider.key, {
          loading: false,
          list: result.list ?? [],
          total: result.total ?? 0,
          resolvedKeyword: keywordSnapshot,
          error: void 0
        });
      }).catch((err) => {
        if (controller.signal.aborted) return;
        if (err instanceof Error && err.name === "AbortError") return;
        updateProviderState(provider.key, {
          loading: false,
          error: err instanceof Error ? err : new Error(String(err))
        });
      });
    },
    [patchProviderRealtimeItems, updateProviderState]
  );
  const schedule = (0, import_react.useCallback)(() => {
    const {
      keyword: k,
      activeTab: tab,
      providers: ps,
      allModePageSize: allSize,
      singleModePageSize: singleSize,
      mode: m
    } = latestRef.current;
    if (tab === import_types.ALL_TAB_KEY) {
      ps.forEach((p) => runOne(p, allSize, k, m, "all"));
    } else {
      const provider = ps.find((p) => p.key === tab);
      if (provider) {
        runOne(provider, singleSize, k, m, "single");
      }
    }
  }, [runOne]);
  (0, import_react.useEffect)(() => {
    schedule();
  }, [keyword, activeTab, providers, mode, schedule]);
  (0, import_react.useEffect)(() => {
    setStateMap((prev) => {
      const next = { ...prev };
      providers.forEach((p) => {
        if (!next[p.key]) next[p.key] = { ...emptyState };
      });
      return next;
    });
  }, [providers]);
  (0, import_react.useEffect)(() => {
    const controllers = controllersRef.current;
    const realtimeCleanups = realtimeCleanupRef.current;
    return () => {
      controllers.forEach((c) => c.abort());
      controllers.clear();
      realtimeCleanups.forEach((cleanup) => cleanup());
      realtimeCleanups.clear();
    };
  }, []);
  return {
    stateMap,
    refresh: schedule,
    reportProviderTotal
  };
}
function initStateMap(providers) {
  const map = {};
  providers.forEach((p) => {
    map[p.key] = { ...emptyState };
  });
  return map;
}
function getRealtimeItemKey(item) {
  if (!item || typeof item !== "object") return null;
  const obj = item;
  const raw = obj.order_id ?? obj.id ?? obj.key;
  if (raw === void 0 || raw === null || raw === "") return null;
  return String(raw);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useProviderSearch
});
