function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { useState, useEffect, useCallback, useRef } from 'react';
/**
 * 防抖函数
 */
var debounce = function debounce(fn, delay) {
  var timeoutId = null;
  return function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(function () {
      fn.apply(void 0, args);
      timeoutId = null;
    }, delay);
  };
};

/**
 * 容器是否处于可测量状态（KeepAlive 隐藏时 client 尺寸常为 0，不应写入 scrollState）。
 *
 * @example
 * isScrollContainerMeasurable(container); // false when display:none
 */
var isScrollContainerMeasurable = function isScrollContainerMeasurable(container) {
  var clientWidth = container.clientWidth,
    clientHeight = container.clientHeight;
  if (clientWidth > 0 || clientHeight > 0) {
    return true;
  }
  var _container$getBoundin = container.getBoundingClientRect(),
    width = _container$getBoundin.width,
    height = _container$getBoundin.height;
  return width > 0 || height > 0;
};

/** scrollState 各字段键名，用于浅比较避免同值重复 setState。 */
var SCROLL_STATE_KEYS = ['scrollTop', 'scrollLeft', 'percentY', 'percentX', 'scrollHeight', 'scrollWidth', 'clientHeight', 'clientWidth', 'direction', 'isScrollToTop', 'isScrollToBottom', 'isScrollToLeft', 'isScrollToRight', 'isOverflows'];

/**
 * 判断两份滚动状态是否一致（按字段浅比较，非引用相等）。
 *
 * @example
 * isScrollStateEqual(prev, next) ? prev : next;
 */
var isScrollStateEqual = function isScrollStateEqual(prev, next) {
  return SCROLL_STATE_KEYS.every(function (key) {
    return prev[key] === next[key];
  });
};

/**
 * 滚动状态管理 Hook
 * @description 管理滚动容器的状态，包括滚动位置、溢出检测等
 */
export var useScrollState = function useScrollState(_ref) {
  var containerRef = _ref.containerRef,
    overflow = _ref.overflow;
  // 初始化滚动状态
  var _useState = useState(function () {
      return {
        scrollTop: 0,
        scrollLeft: 0,
        percentY: 0,
        percentX: 0,
        scrollHeight: 0,
        scrollWidth: 0,
        clientHeight: 0,
        clientWidth: 0,
        direction: null,
        isScrollToTop: overflow === 'y' || overflow === 'both',
        isScrollToBottom: false,
        isScrollToLeft: overflow === 'x' || overflow === 'both',
        isScrollToRight: false,
        isOverflows: false
      };
    }),
    _useState2 = _slicedToArray(_useState, 2),
    scrollState = _useState2[0],
    setScrollState = _useState2[1];

  // 使用 ref 存储是否已挂载，避免在组件卸载后更新状态
  var isMountedRef = useRef(true);
  // 存储 ResizeObserver 实例
  var resizeObserverRef = useRef(null);

  /**
   * 计算并更新滚动状态
   */
  var calculateScrollState = useCallback(function () {
    var prevState = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    var container = containerRef.current;
    if (!container) return null;
    try {
      if (!isScrollContainerMeasurable(container)) {
        return null;
      }
      var scrollTop = container.scrollTop,
        scrollLeft = container.scrollLeft,
        scrollHeight = container.scrollHeight,
        scrollWidth = container.scrollWidth,
        clientHeight = container.clientHeight,
        clientWidth = container.clientWidth;

      // 计算是否溢出
      var isOverflows = scrollHeight > clientHeight || scrollWidth > clientWidth;

      // 计算边界状态
      var isScrollToTop = scrollTop <= 0;
      var isScrollToBottom = scrollTop + clientHeight >= scrollHeight - 1; // -1 处理浮点误差
      var isScrollToLeft = scrollLeft <= 0;
      var isScrollToRight = scrollLeft + clientWidth >= scrollWidth - 1;

      // 计算滚动方向
      var direction = null;
      if (prevState) {
        var deltaY = Math.abs(scrollTop - prevState.scrollTop);
        var deltaX = Math.abs(scrollLeft - prevState.scrollLeft);
        if (deltaY > deltaX && deltaY > 0) {
          direction = scrollTop > prevState.scrollTop ? 'down' : 'up';
        } else if (deltaX > 0) {
          direction = scrollLeft > prevState.scrollLeft ? 'right' : 'left';
        } else {
          direction = prevState.direction;
        }
      }

      // 计算滚动百分比
      var maxScrollTop = Math.max(0, scrollHeight - clientHeight);
      var maxScrollLeft = Math.max(0, scrollWidth - clientWidth);
      var percentY = maxScrollTop > 0 ? scrollTop / maxScrollTop * 100 : 0;
      var percentX = maxScrollLeft > 0 ? scrollLeft / maxScrollLeft * 100 : 0;
      return {
        scrollTop: scrollTop,
        scrollLeft: scrollLeft,
        scrollHeight: scrollHeight,
        scrollWidth: scrollWidth,
        clientHeight: clientHeight,
        clientWidth: clientWidth,
        percentY: percentY,
        percentX: percentX,
        direction: direction,
        isScrollToTop: isScrollToTop,
        isScrollToBottom: isScrollToBottom,
        isScrollToLeft: isScrollToLeft,
        isScrollToRight: isScrollToRight,
        isOverflows: isOverflows
      };
    } catch (error) {
      console.warn('[useScrollState] 计算滚动状态时出错:', error);
      return null;
    }
  }, [containerRef]);

  /**
   * 更新滚动状态（用于滚动事件）
   */
  var updateScrollState = useCallback(function () {
    if (!isMountedRef.current) return;
    setScrollState(function (prev) {
      var newState = calculateScrollState(prev);
      if (!newState) {
        return prev;
      }
      return isScrollStateEqual(prev, newState) ? prev : newState;
    });
  }, [calculateScrollState]);

  /**
   * 更新溢出状态（用于尺寸变化）
   */
  var updateOverflowState = useCallback(function () {
    if (!isMountedRef.current) return;
    var newState = calculateScrollState(null);
    if (!newState) {
      return;
    }
    setScrollState(function (prev) {
      var next = _objectSpread(_objectSpread({}, prev), {}, {
        scrollHeight: newState.scrollHeight,
        scrollWidth: newState.scrollWidth,
        clientHeight: newState.clientHeight,
        clientWidth: newState.clientWidth,
        isOverflows: newState.isOverflows,
        isScrollToTop: newState.isScrollToTop,
        isScrollToBottom: newState.isScrollToBottom,
        isScrollToLeft: newState.isScrollToLeft,
        isScrollToRight: newState.isScrollToRight
      });
      return isScrollStateEqual(prev, next) ? prev : next;
    });
  }, [calculateScrollState]);

  // 监听容器尺寸变化
  useEffect(function () {
    isMountedRef.current = true;
    var container = containerRef.current;
    if (!container) return;

    // 防抖处理尺寸变化回调
    var debouncedUpdateOverflow = debounce(updateOverflowState, 50);

    // 初始化状态
    updateOverflowState();

    // 检查 ResizeObserver 是否可用
    if (typeof ResizeObserver === 'undefined') {
      // 降级方案：使用 window resize 事件
      var handleResize = function handleResize() {
        return debouncedUpdateOverflow();
      };
      window.addEventListener('resize', handleResize);
      return function () {
        isMountedRef.current = false;
        window.removeEventListener('resize', handleResize);
      };
    }
    try {
      // 创建 ResizeObserver
      resizeObserverRef.current = new ResizeObserver(function (entries) {
        // 确保只在有效的尺寸变化时更新
        if (entries.length > 0 && isMountedRef.current) {
          debouncedUpdateOverflow();
        }
      });

      // 监听容器本身
      resizeObserverRef.current.observe(container);

      // 监听直接子元素
      var children = container.children;
      for (var i = 0; i < children.length; i++) {
        resizeObserverRef.current.observe(children[i]);
      }

      // 使用 MutationObserver 监听子元素变化
      var mutationObserver = new MutationObserver(function (mutations) {
        if (!isMountedRef.current || !resizeObserverRef.current) return;
        mutations.forEach(function (mutation) {
          // 新增的子元素添加监听
          mutation.addedNodes.forEach(function (node) {
            if (node instanceof Element) {
              var _resizeObserverRef$cu;
              (_resizeObserverRef$cu = resizeObserverRef.current) === null || _resizeObserverRef$cu === void 0 || _resizeObserverRef$cu.observe(node);
            }
          });
        });

        // 子元素变化后更新溢出状态
        debouncedUpdateOverflow();
      });
      mutationObserver.observe(container, {
        childList: true,
        subtree: false
      });

      // 监听 window resize 作为补充
      var handleWindowResize = function handleWindowResize() {
        return debouncedUpdateOverflow();
      };
      window.addEventListener('resize', handleWindowResize);
      return function () {
        var _resizeObserverRef$cu2;
        isMountedRef.current = false;
        (_resizeObserverRef$cu2 = resizeObserverRef.current) === null || _resizeObserverRef$cu2 === void 0 || _resizeObserverRef$cu2.disconnect();
        resizeObserverRef.current = null;
        mutationObserver.disconnect();
        window.removeEventListener('resize', handleWindowResize);
      };
    } catch (error) {
      console.warn('[useScrollState] 初始化 ResizeObserver 失败:', error);
      // 降级方案
      var _handleResize = function _handleResize() {
        return debouncedUpdateOverflow();
      };
      window.addEventListener('resize', _handleResize);
      return function () {
        isMountedRef.current = false;
        window.removeEventListener('resize', _handleResize);
      };
    }
  }, [containerRef, updateOverflowState]);
  return {
    scrollState: scrollState,
    updateScrollState: updateScrollState
  };
};