import { useEffect } from 'react';
export var useIntersection = function useIntersection(_ref) {
  var containerRef = _ref.containerRef,
    config = _ref.config;
  useEffect(function () {
    if (!(config !== null && config !== void 0 && config.enabled) || !containerRef.current) return;
    var _config$threshold = config.threshold,
      threshold = _config$threshold === void 0 ? 0 : _config$threshold,
      _config$rootMargin = config.rootMargin,
      rootMargin = _config$rootMargin === void 0 ? '0px' : _config$rootMargin,
      targetSelector = config.targetSelector,
      onEnterViewport = config.onEnterViewport,
      onLeaveViewport = config.onLeaveViewport,
      onVisibilityChange = config.onVisibilityChange;
    var container = containerRef.current;

    // 如果没有 targetSelector，监听 children
    // 但通常 IntersectionObserver 最好是用户指定 selector
    // 或者我们遍历所有直接子元素
    var targets = targetSelector ? container.querySelectorAll(targetSelector) : container.children;
    if (!targets || targets.length === 0) return;
    var observer = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        var element = entry.target;
        onVisibilityChange === null || onVisibilityChange === void 0 || onVisibilityChange(entry, element);
        if (entry.isIntersecting) {
          onEnterViewport === null || onEnterViewport === void 0 || onEnterViewport(entry, element);
        } else {
          onLeaveViewport === null || onLeaveViewport === void 0 || onLeaveViewport(entry, element);
        }
      });
    }, {
      root: container,
      rootMargin: rootMargin,
      threshold: threshold
    });
    Array.from(targets).forEach(function (target) {
      return observer.observe(target);
    });
    return function () {
      observer.disconnect();
    };
  }, [config, containerRef]);
};