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 _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; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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; }
import { isValidElement, cloneElement, useMemo, useState, useRef, useEffect, useCallback } from 'react';
import { extractButtonLabel } from "../utils/extractText";

/**
 * useOverflowActions Hook 配置
 */

/**
 * useOverflowActions Hook 返回值
 */

/**
 * 检查元素是否是按钮（根据类名是否包含 "btn"）
 */
var isButtonElement = function isButtonElement(element) {
  var props = element.props || {};
  var className = props.className;

  // 检查 className 是否包含 "btn"
  if (typeof className === 'string' && className.includes('btn')) {
    return true;
  }

  // 如果 className 是数组，检查数组中是否有包含 "btn" 的字符串
  if (Array.isArray(className)) {
    return className.some(function (cls) {
      return typeof cls === 'string' && cls.includes('btn');
    });
  }
  return false;
};

/**
 * 递归提取所有按钮元素
 */
var extractButtons = function extractButtons(node) {
  var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var buttons = [];
  if (!node) {
    return buttons;
  }

  // 如果是数组，递归处理每个元素
  if (Array.isArray(node)) {
    node.forEach(function (item, i) {
      buttons.push.apply(buttons, _toConsumableArray(extractButtons(item, i)));
    });
    return buttons;
  }

  // 如果是有效的 React 元素
  if ( /*#__PURE__*/isValidElement(node)) {
    var element = node;

    // 如果当前元素是按钮，直接添加
    if (isButtonElement(element)) {
      var _element$key;
      buttons.push( /*#__PURE__*/cloneElement(element, {
        key: (_element$key = element.key) !== null && _element$key !== void 0 ? _element$key : "btn-".concat(index)
      }));
      return buttons;
    }

    // 如果不是按钮，递归处理其 children
    if (element.props && element.props.children) {
      var childButtons = extractButtons(element.props.children, index);
      buttons.push.apply(buttons, _toConsumableArray(childButtons));
    }
  }
  return buttons;
};

/**
 * 溢出收纳 Hook
 * @description 处理操作按钮的溢出收纳逻辑，支持左侧自定义内容
 */
export var useOverflowActions = function useOverflowActions(options) {
  var children = options.children,
    _options$gap = options.gap,
    gap = _options$gap === void 0 ? 16 : _options$gap;
  var containerRef = useRef(null);
  var measureRef = useRef(null);
  var moreButtonRef = useRef(null);
  var leftSlotRef = useRef(null);
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    itemWidths = _useState2[0],
    setItemWidths = _useState2[1];
  var _useState3 = useState(80),
    _useState4 = _slicedToArray(_useState3, 2),
    moreButtonWidth = _useState4[0],
    setMoreButtonWidth = _useState4[1];
  var _useState5 = useState(0),
    _useState6 = _slicedToArray(_useState5, 2),
    availableWidth = _useState6[0],
    setAvailableWidth = _useState6[1];

  /**
   * 找到所有按钮元素
   */
  var actionItems = useMemo(function () {
    return extractButtons(children);
  }, [children]);

  /**
   * 测量所有按钮的宽度
   */
  var measureWidths = useCallback(function () {
    if (typeof window === 'undefined' || !measureRef.current || !moreButtonRef.current) return;
    try {
      // 测量所有按钮宽度（向上取整）
      var buttons = measureRef.current.querySelectorAll('[data-measure-item]');
      var widths = [];
      buttons.forEach(function (btn) {
        var rect = btn.getBoundingClientRect();
        if (rect) {
          widths.push(Math.ceil(rect.width));
        }
      });
      setItemWidths(widths);

      // 测量 More 按钮宽度（向上取整）
      var moreBtnRect = moreButtonRef.current.getBoundingClientRect();
      if (moreBtnRect) {
        var moreBtnWidth = Math.ceil(moreBtnRect.width);
        setMoreButtonWidth(moreBtnWidth);
      }
    } catch (error) {
      // 静默处理错误，避免影响渲染
      console.warn('Failed to measure button widths:', error);
    }
  }, []);

  /**
   * 更新可用宽度
   * 计算逻辑：容器宽度 - 左侧插槽宽度 - 间距
   * 
   * 注意：统一使用 getBoundingClientRect() 来获取宽度，
   * 因为 offsetWidth 返回 CSS 像素不受缩放影响，
   * 而 getBoundingClientRect() 返回视觉像素（受缩放影响）。
   * 混用会导致在页面缩放时计算错误。
   */
  var updateAvailableWidth = useCallback(function () {
    if (!containerRef.current || typeof window === 'undefined') return;
    var parent = containerRef.current.parentElement;
    if (!parent) {
      var containerRect = containerRef.current.getBoundingClientRect();
      setAvailableWidth(Math.floor(containerRect.width));
      return;
    }
    var parentStyle = window.getComputedStyle(parent);
    var parentRect = parent.getBoundingClientRect();

    // 计算缩放比例，用于将 CSS 像素值（如 padding）转换为视觉像素
    // offsetWidth 是 CSS 像素，getBoundingClientRect().width 是视觉像素
    var scale = parent.offsetWidth > 0 ? parentRect.width / parent.offsetWidth : 1;

    // padding 从 getComputedStyle 获取的是 CSS 像素，需要乘以缩放比例
    var paddingLeft = (parseFloat(parentStyle.paddingLeft) || 0) * scale;
    var paddingRight = (parseFloat(parentStyle.paddingRight) || 0) * scale;
    var parentGap = (parseFloat(parentStyle.gap) || gap) * scale;

    // 计算左侧插槽占用的宽度（getBoundingClientRect 已经是视觉像素）
    var leftSlotWidth = 0;
    if (leftSlotRef.current) {
      leftSlotWidth = Math.ceil(leftSlotRef.current.getBoundingClientRect().width);
      // 如果左侧有内容，加上间距
      if (leftSlotWidth > 0) {
        leftSlotWidth += parentGap;
      }
    }

    // 计算其他兄弟元素（如 summaryButton）的宽度
    var otherSiblingWidth = 0;
    var siblings = parent.children;
    for (var i = 0; i < siblings.length; i++) {
      var sibling = siblings[i];
      // 排除当前容器和隐藏的测量元素
      if (sibling !== containerRef.current && sibling !== leftSlotRef.current && !sibling.hasAttribute('aria-hidden')) {
        var siblingWidth = Math.ceil(sibling.getBoundingClientRect().width);
        if (siblingWidth > 0) {
          otherSiblingWidth += siblingWidth + parentGap;
        }
      }
    }

    // 可用宽度 = 父容器宽度（视觉像素） - padding - 左侧插槽 - 其他兄弟元素
    var totalWidth = parentRect.width - paddingLeft - paddingRight;
    var width = Math.floor(totalWidth - leftSlotWidth - otherSiblingWidth);
    setAvailableWidth(Math.max(0, width));
  }, [gap]);

  /**
   * 初始化测量
   */
  useEffect(function () {
    var rafId = requestAnimationFrame(function () {
      measureWidths();
      updateAvailableWidth();
    });
    return function () {
      return cancelAnimationFrame(rafId);
    };
  }, [actionItems, measureWidths, updateAvailableWidth]);

  /**
   * 监听尺寸变化
   */
  useEffect(function () {
    var _containerRef$current;
    if (typeof window === 'undefined') return;
    var handleResize = function handleResize() {
      measureWidths();
      updateAvailableWidth();
    };
    window.addEventListener('resize', handleResize);
    var parent = (_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : _containerRef$current.parentElement;
    var resizeObserver = null;
    if (parent && typeof ResizeObserver !== 'undefined') {
      try {
        resizeObserver = new ResizeObserver(function () {
          measureWidths();
          updateAvailableWidth();
        });
        resizeObserver.observe(parent);
      } catch (error) {
        console.warn('Failed to create ResizeObserver:', error);
      }
    }

    // 也监听左侧插槽的尺寸变化
    if (leftSlotRef.current && typeof ResizeObserver !== 'undefined') {
      try {
        var leftObserver = new ResizeObserver(function () {
          return updateAvailableWidth();
        });
        leftObserver.observe(leftSlotRef.current);
        return function () {
          var _resizeObserver;
          window.removeEventListener('resize', handleResize);
          (_resizeObserver = resizeObserver) === null || _resizeObserver === void 0 || _resizeObserver.disconnect();
          leftObserver.disconnect();
        };
      } catch (error) {
        console.warn('Failed to create ResizeObserver for leftSlot:', error);
      }
    }
    return function () {
      var _resizeObserver2;
      window.removeEventListener('resize', handleResize);
      (_resizeObserver2 = resizeObserver) === null || _resizeObserver2 === void 0 || _resizeObserver2.disconnect();
    };
  }, [measureWidths, updateAvailableWidth]);

  /**
   * 计算可见项数量
   * 根据可用宽度计算能显示多少个按钮
   */
  var visibleCount = useMemo(function () {
    if (itemWidths.length === 0 || availableWidth === 0) {
      return actionItems.length;
    }
    var totalItems = itemWidths.length;
    var totalButtonsWidth = itemWidths.reduce(function (sum, w) {
      return sum + w;
    }, 0);
    var totalGapsWidth = (totalItems - 1) * gap;
    var allButtonsWidth = totalButtonsWidth + totalGapsWidth;

    // 所有按钮都能放下
    if (allButtonsWidth <= availableWidth) {
      return totalItems;
    }

    // 需要 More 按钮，预留 More 按钮的空间
    var spaceForButtons = availableWidth - moreButtonWidth - gap;
    if (spaceForButtons <= 0) {
      // 空间不足时，不保留任何按钮，全部收纳到 More 菜单
      return 0;
    }

    // 从右边开始计算能放下多少个按钮（保留主要操作）
    var usedWidth = 0;
    var count = 0;
    for (var i = totalItems - 1; i >= 0; i--) {
      var itemWidth = itemWidths[i];
      var gapWidth = count > 0 ? gap : 0;
      var requiredWidth = itemWidth + gapWidth;
      if (usedWidth + requiredWidth <= spaceForButtons) {
        usedWidth += requiredWidth;
        count++;
      } else {
        break;
      }
    }

    // 不强制保留最后一个按钮，空间不足时全部收纳到 More 菜单
    return count;
  }, [itemWidths, availableWidth, gap, moreButtonWidth, actionItems.length]);

  // 计算溢出项和可见项
  var overflowCount = Math.max(0, actionItems.length - visibleCount);
  var overflowActions = actionItems.slice(0, overflowCount);
  var visibleActions = actionItems.slice(overflowCount);
  var hasOverflow = overflowCount > 0;

  /**
   * 构建 More 菜单项
   */
  var moreMenuItems = useMemo(function () {
    return overflowActions.map(function (action, index) {
      if (! /*#__PURE__*/isValidElement(action)) return null;
      var buttonProps = action.props;
      var label = extractButtonLabel(buttonProps, "\u64CD\u4F5C ".concat(index + 1));
      var originalOnClick = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.onClick;
      return {
        key: "overflow-".concat(index),
        label: label,
        onClick: originalOnClick ? function () {
          return originalOnClick({});
        } : undefined,
        disabled: (buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.disabled) || (buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.loading),
        danger: buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.danger,
        icon: buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.icon,
        title: buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.title
      };
    }).filter(Boolean);
  }, [overflowActions]);
  return {
    containerRef: containerRef,
    measureRef: measureRef,
    moreButtonRef: moreButtonRef,
    leftSlotRef: leftSlotRef,
    actionItems: actionItems,
    visibleActions: visibleActions,
    overflowActions: overflowActions,
    hasOverflow: hasOverflow,
    moreMenuItems: moreMenuItems,
    availableWidth: availableWidth
  };
};