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, useRef, useCallback } from 'react';

/**
 * 尺寸值接口
 */

/**
 * 使用 Sidebar 高度的 Hook
 *
 * @description 计算并管理 Sidebar 的高度，确保在尺寸稳定后才应用
 */
export var useSidebarHeight = function useSidebarHeight(isSizeStable, sizeValues) {
  var _useState = useState(undefined),
    _useState2 = _slicedToArray(_useState, 2),
    siderHeight = _useState2[0],
    setSiderHeight = _useState2[1];
  var hasInitializedRef = useRef(false);
  var rafIdRef = useRef(null);
  var stableCheckCountRef = useRef(0);
  var previousSiderHeightRef = useRef(undefined);
  var sizeValuesRef = useRef(sizeValues);

  // 更新最新的尺寸值
  useEffect(function () {
    sizeValuesRef.current = sizeValues;
  }, [sizeValues]);

  /**
   * 获取 body 元素的 CSS transform Y 轴缩放比例
   * @returns scaleY 缩放比例
   */
  var getBodyScaleY = useCallback(function () {
    try {
      if (typeof window === 'undefined' || typeof document === 'undefined') {
        return 1;
      }
      var bodyTransform = getComputedStyle(document.body).transform;
      var scaleY = 1;
      if (bodyTransform !== 'none') {
        var matrix = new DOMMatrix(bodyTransform);
        scaleY = matrix.d; // Y 轴缩放
      }
      return scaleY;
    } catch (error) {
      return 1;
    }
  }, []);

  /**
   * 计算高度的函数
   * @description 计算时会考虑 body 上的 CSS transform 缩放，返回缩放校正后的实际逻辑高度
   */
  var calculateHeight = useCallback(function () {
    var _sizeValuesRef$curren = sizeValuesRef.current,
      containerSelector = _sizeValuesRef$curren.containerSelector,
      containerHeight = _sizeValuesRef$curren.containerHeight,
      headerHeight = _sizeValuesRef$curren.headerHeight,
      footerHeight = _sizeValuesRef$curren.footerHeight;

    // 优先使用容器高度，如果没有提供容器选择器或容器高度无效，则使用视口高度
    var baseHeight;
    if (containerSelector && containerSelector.trim() && containerHeight && containerHeight > 0) {
      baseHeight = containerHeight;
    } else {
      baseHeight = typeof window !== 'undefined' ? window.innerHeight : 0;
    }
    var bodyPadding = 16 * 2; // 上下各16px
    var headerHeightValue = headerHeight || 0;
    var calculatedHeight = baseHeight - headerHeightValue - footerHeight - bodyPadding;

    // 获取 body 的 Y 轴缩放比例，并计算校正后的高度
    var scaleY = getBodyScaleY();
    var scaledHeight = calculatedHeight / scaleY;

    // 保留两位小数
    return Math.round(scaledHeight * 100) / 100;
  }, [sizeValuesRef.current, getBodyScaleY]);

  // 使用 requestAnimationFrame 确保在浏览器重绘后计算，更稳定
  useEffect(function () {
    if (typeof window === 'undefined' || typeof document === 'undefined') {
      return;
    }

    // 如果尺寸还未稳定，清除之前的动画帧，重置检查计数
    if (!isSizeStable) {
      hasInitializedRef.current = false;
      stableCheckCountRef.current = 0;
      if (rafIdRef.current !== null) {
        cancelAnimationFrame(rafIdRef.current);
        rafIdRef.current = null;
      }
      return;
    }

    // 清除之前的动画帧
    if (rafIdRef.current !== null) {
      cancelAnimationFrame(rafIdRef.current);
    }

    /**
     * 稳定性检查函数：连续3次检查尺寸都稳定才认为真正稳定
     */
    var checkStability = function checkStability() {
      // 再次检查尺寸是否稳定（防止在等待期间尺寸又变化了）
      if (!isSizeStable) {
        stableCheckCountRef.current = 0;
        return;
      }
      var calculatedHeight = calculateHeight();

      // 如果高度无效，重置计数
      if (calculatedHeight <= 0) {
        stableCheckCountRef.current = 0;
        return;
      }

      // 获取上一次的高度用于比较
      var previousHeight = previousSiderHeightRef.current;

      // 如果已经初始化过，且高度变化小于阈值（10px），直接使用之前的高度
      if (hasInitializedRef.current && previousHeight !== undefined && Math.abs(calculatedHeight - previousHeight) < 10) {
        return; // 高度变化太小，不更新
      }

      // 连续3次检查高度都相同（或变化很小），才认为稳定
      stableCheckCountRef.current += 1;
      if (stableCheckCountRef.current >= 3) {
        // 稳定了，应用高度
        previousSiderHeightRef.current = calculatedHeight;
        setSiderHeight(calculatedHeight);
        hasInitializedRef.current = true;
        stableCheckCountRef.current = 0; // 重置计数
      } else {
        // 还未稳定，继续等待下一次重绘
        rafIdRef.current = requestAnimationFrame(checkStability);
      }
    };

    // 使用 requestAnimationFrame 确保在浏览器重绘后检查
    rafIdRef.current = requestAnimationFrame(checkStability);

    // 清理函数
    return function () {
      if (rafIdRef.current !== null) {
        cancelAnimationFrame(rafIdRef.current);
        rafIdRef.current = null;
      }
    };
  }, [isSizeStable, calculateHeight]);
  return siderHeight;
};