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/components/PisellProcedure/hooks/useOverflowActions.ts
var useOverflowActions_exports = {};
__export(useOverflowActions_exports, {
  useOverflowActions: () => useOverflowActions
});
module.exports = __toCommonJS(useOverflowActions_exports);
var import_react = require("react");
var import_extractText = require("../utils/extractText");
var isButtonElement = (element) => {
  const props = element.props || {};
  const className = props.className;
  if (typeof className === "string" && className.includes("btn")) {
    return true;
  }
  if (Array.isArray(className)) {
    return className.some((cls) => typeof cls === "string" && cls.includes("btn"));
  }
  return false;
};
var extractButtons = (node, index = 0) => {
  const buttons = [];
  if (!node) {
    return buttons;
  }
  if (Array.isArray(node)) {
    node.forEach((item, i) => {
      buttons.push(...extractButtons(item, i));
    });
    return buttons;
  }
  if ((0, import_react.isValidElement)(node)) {
    const element = node;
    if (isButtonElement(element)) {
      buttons.push(
        (0, import_react.cloneElement)(element, {
          key: element.key ?? `btn-${index}`
        })
      );
      return buttons;
    }
    if (element.props && element.props.children) {
      const childButtons = extractButtons(element.props.children, index);
      buttons.push(...childButtons);
    }
  }
  return buttons;
};
var useOverflowActions = (options) => {
  const { children, gap = 16 } = options;
  const containerRef = (0, import_react.useRef)(null);
  const measureRef = (0, import_react.useRef)(null);
  const moreButtonRef = (0, import_react.useRef)(null);
  const leftSlotRef = (0, import_react.useRef)(null);
  const [itemWidths, setItemWidths] = (0, import_react.useState)([]);
  const [moreButtonWidth, setMoreButtonWidth] = (0, import_react.useState)(80);
  const [availableWidth, setAvailableWidth] = (0, import_react.useState)(0);
  const actionItems = (0, import_react.useMemo)(() => {
    return extractButtons(children);
  }, [children]);
  const measureWidths = (0, import_react.useCallback)(() => {
    if (typeof window === "undefined" || !measureRef.current || !moreButtonRef.current) return;
    try {
      const buttons = measureRef.current.querySelectorAll("[data-measure-item]");
      const widths = [];
      buttons.forEach((btn) => {
        const rect = btn.getBoundingClientRect();
        if (rect) {
          widths.push(Math.ceil(rect.width));
        }
      });
      setItemWidths(widths);
      const moreBtnRect = moreButtonRef.current.getBoundingClientRect();
      if (moreBtnRect) {
        const moreBtnWidth = Math.ceil(moreBtnRect.width);
        setMoreButtonWidth(moreBtnWidth);
      }
    } catch (error) {
      console.warn("Failed to measure button widths:", error);
    }
  }, []);
  const updateAvailableWidth = (0, import_react.useCallback)(() => {
    if (!containerRef.current || typeof window === "undefined") return;
    const parent = containerRef.current.parentElement;
    if (!parent) {
      const containerRect = containerRef.current.getBoundingClientRect();
      setAvailableWidth(Math.floor(containerRect.width));
      return;
    }
    const parentStyle = window.getComputedStyle(parent);
    const parentRect = parent.getBoundingClientRect();
    const scale = parent.offsetWidth > 0 ? parentRect.width / parent.offsetWidth : 1;
    const paddingLeft = (parseFloat(parentStyle.paddingLeft) || 0) * scale;
    const paddingRight = (parseFloat(parentStyle.paddingRight) || 0) * scale;
    const parentGap = (parseFloat(parentStyle.gap) || gap) * scale;
    let leftSlotWidth = 0;
    if (leftSlotRef.current) {
      leftSlotWidth = Math.ceil(leftSlotRef.current.getBoundingClientRect().width);
      if (leftSlotWidth > 0) {
        leftSlotWidth += parentGap;
      }
    }
    let otherSiblingWidth = 0;
    const siblings = parent.children;
    for (let i = 0; i < siblings.length; i++) {
      const sibling = siblings[i];
      if (sibling !== containerRef.current && sibling !== leftSlotRef.current && !sibling.hasAttribute("aria-hidden")) {
        const siblingWidth = Math.ceil(sibling.getBoundingClientRect().width);
        if (siblingWidth > 0) {
          otherSiblingWidth += siblingWidth + parentGap;
        }
      }
    }
    const totalWidth = parentRect.width - paddingLeft - paddingRight;
    const width = Math.floor(totalWidth - leftSlotWidth - otherSiblingWidth);
    setAvailableWidth(Math.max(0, width));
  }, [gap]);
  (0, import_react.useEffect)(() => {
    const rafId = requestAnimationFrame(() => {
      measureWidths();
      updateAvailableWidth();
    });
    return () => cancelAnimationFrame(rafId);
  }, [actionItems, measureWidths, updateAvailableWidth]);
  (0, import_react.useEffect)(() => {
    var _a;
    if (typeof window === "undefined") return;
    const handleResize = () => {
      measureWidths();
      updateAvailableWidth();
    };
    window.addEventListener("resize", handleResize);
    const parent = (_a = containerRef.current) == null ? void 0 : _a.parentElement;
    let resizeObserver = null;
    if (parent && typeof ResizeObserver !== "undefined") {
      try {
        resizeObserver = new ResizeObserver(() => {
          measureWidths();
          updateAvailableWidth();
        });
        resizeObserver.observe(parent);
      } catch (error) {
        console.warn("Failed to create ResizeObserver:", error);
      }
    }
    if (leftSlotRef.current && typeof ResizeObserver !== "undefined") {
      try {
        const leftObserver = new ResizeObserver(() => updateAvailableWidth());
        leftObserver.observe(leftSlotRef.current);
        return () => {
          window.removeEventListener("resize", handleResize);
          resizeObserver == null ? void 0 : resizeObserver.disconnect();
          leftObserver.disconnect();
        };
      } catch (error) {
        console.warn("Failed to create ResizeObserver for leftSlot:", error);
      }
    }
    return () => {
      window.removeEventListener("resize", handleResize);
      resizeObserver == null ? void 0 : resizeObserver.disconnect();
    };
  }, [measureWidths, updateAvailableWidth]);
  const visibleCount = (0, import_react.useMemo)(() => {
    if (itemWidths.length === 0 || availableWidth === 0) {
      return actionItems.length;
    }
    const totalItems = itemWidths.length;
    const totalButtonsWidth = itemWidths.reduce((sum, w) => sum + w, 0);
    const totalGapsWidth = (totalItems - 1) * gap;
    const allButtonsWidth = totalButtonsWidth + totalGapsWidth;
    if (allButtonsWidth <= availableWidth) {
      return totalItems;
    }
    const spaceForButtons = availableWidth - moreButtonWidth - gap;
    if (spaceForButtons <= 0) {
      return 0;
    }
    let usedWidth = 0;
    let count = 0;
    for (let i = totalItems - 1; i >= 0; i--) {
      const itemWidth = itemWidths[i];
      const gapWidth = count > 0 ? gap : 0;
      const requiredWidth = itemWidth + gapWidth;
      if (usedWidth + requiredWidth <= spaceForButtons) {
        usedWidth += requiredWidth;
        count++;
      } else {
        break;
      }
    }
    return count;
  }, [itemWidths, availableWidth, gap, moreButtonWidth, actionItems.length]);
  const overflowCount = Math.max(0, actionItems.length - visibleCount);
  const overflowActions = actionItems.slice(0, overflowCount);
  const visibleActions = actionItems.slice(overflowCount);
  const hasOverflow = overflowCount > 0;
  const moreMenuItems = (0, import_react.useMemo)(() => {
    return overflowActions.map((action, index) => {
      if (!(0, import_react.isValidElement)(action)) return null;
      const buttonProps = action.props;
      const label = (0, import_extractText.extractButtonLabel)(buttonProps, `操作 ${index + 1}`);
      const originalOnClick = buttonProps == null ? void 0 : buttonProps.onClick;
      return {
        key: `overflow-${index}`,
        label,
        onClick: originalOnClick ? () => originalOnClick({}) : void 0,
        disabled: (buttonProps == null ? void 0 : buttonProps.disabled) || (buttonProps == null ? void 0 : buttonProps.loading),
        danger: buttonProps == null ? void 0 : buttonProps.danger,
        icon: buttonProps == null ? void 0 : buttonProps.icon,
        title: buttonProps == null ? void 0 : buttonProps.title
      };
    }).filter(Boolean);
  }, [overflowActions]);
  return {
    containerRef,
    measureRef,
    moreButtonRef,
    leftSlotRef,
    actionItems,
    visibleActions,
    overflowActions,
    hasOverflow,
    moreMenuItems,
    availableWidth
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useOverflowActions
});
