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, useMemo } from 'react';
import { debounce } from "./utils";
/**
 * Hook for managing selection indicator position with enhanced features
 * @param containerRef - Ref to the tab container
 * @param selectedTabId - ID of the currently selected tab (optional)
 * @param transition - Custom transition string (optional)
 * @returns Selection indicator props and list container props
 */
export function useSelectionIndicator(containerRef, selectedTabId, transition) {
  var _useState = useState({
      width: 0,
      transform: 'translateX(0)',
      transition: 'none'
    }),
    _useState2 = _slicedToArray(_useState, 2),
    indicatorStyle = _useState2[0],
    setIndicatorStyle = _useState2[1];
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    selectedTabRef = _useState4[0],
    setSelectedTabRef = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    isFocusVisible = _useState6[0],
    setIsFocusVisible = _useState6[1];
  var _useState7 = useState(''),
    _useState8 = _slicedToArray(_useState7, 2),
    focusRingClasses = _useState8[0],
    setFocusRingClasses = _useState8[1];

  // Create a ref setter for the selected tab
  var setSelectedTab = useCallback(function (element) {
    setSelectedTabRef(function (prevRef) {
      return (prevRef === null || prevRef === void 0 ? void 0 : prevRef.current) === element ? prevRef : {
        current: element
      };
    });
  }, []);

  // Find selected tab by aria-selected attribute
  var findSelectedTabByAttribute = useCallback(function () {
    if (!containerRef.current) return null;
    var selectedTab = containerRef.current.querySelector('[role="tab"][aria-selected="true"]');
    if (selectedTab) {
      setSelectedTab(selectedTab);
    }
    return selectedTab;
  }, [containerRef, setSelectedTab]);

  // Find selected tab by ID
  var findSelectedTabById = useCallback(function () {
    if (!selectedTabId || !containerRef.current) return null;
    var selectedTab = containerRef.current.querySelector("[id=\"".concat(selectedTabId, "\"]"));
    return selectedTab;
  }, [containerRef, selectedTabId]);

  // Get transition string with defaults
  var getTransition = useCallback(function (customTransition) {
    return customTransition || 'transform 300ms, width 100ms';
  }, []);

  // Detect text direction (RTL/LTR)
  var getDirection = useCallback(function () {
    if (!containerRef.current) return 'ltr';
    return window.getComputedStyle(containerRef.current).direction || 'ltr';
  }, [containerRef]);

  // Update indicator position with RTL support and improved error handling
  var updateIndicatorPosition = useCallback(function () {
    try {
      var selectedTab = findSelectedTabByAttribute() || findSelectedTabById();
      if (!selectedTab || !containerRef.current) {
        setIndicatorStyle(function (prev) {
          return _objectSpread(_objectSpread({}, prev), {}, {
            width: 0,
            transform: 'translateX(0)'
          });
        });
        return;
      }
      var container = containerRef.current;
      var offsetParent = selectedTab.offsetParent;
      if (!offsetParent) {
        setIndicatorStyle(function (prev) {
          return _objectSpread(_objectSpread({}, prev), {}, {
            width: 0,
            transform: 'translateX(0)'
          });
        });
        return;
      }

      // 检查元素是否仍然有效
      if (!selectedTab.isConnected) {
        console.warn('useSelectionIndicator: Selected tab is no longer connected to DOM');
        return;
      }
      var direction = getDirection();
      var width = selectedTab.offsetWidth;
      if (width <= 0) {
        setIndicatorStyle(function (prev) {
          return _objectSpread(_objectSpread({}, prev), {}, {
            width: 0,
            transform: 'translateX(0)'
          });
        });
        return;
      }
      var left;
      if (direction === 'rtl') {
        // RTL calculation
        left = -1 * (offsetParent.clientWidth - selectedTab.offsetLeft - selectedTab.offsetWidth);
      } else {
        // LTR calculation
        left = selectedTab.offsetLeft;
      }
      var transitionValue = getTransition(transition);
      setIndicatorStyle({
        width: "".concat(width, "px"),
        transform: "translateX(".concat(left, "px)"),
        transition: transitionValue
      });
    } catch (error) {
      console.warn('useSelectionIndicator: Error updating indicator position:', error);
      // 重置为安全状态
      setIndicatorStyle(function (prev) {
        return _objectSpread(_objectSpread({}, prev), {}, {
          width: 0,
          transform: 'translateX(0)'
        });
      });
    }
  }, [containerRef, selectedTabId, transition, findSelectedTabByAttribute, findSelectedTabById, getDirection, getTransition]);

  // Debounced update function
  var debouncedUpdate = useMemo(function () {
    return debounce(updateIndicatorPosition, 50);
  }, [updateIndicatorPosition]);

  // Focus management
  var handleFocusIn = useCallback(function (event) {
    setIsFocusVisible(event.target instanceof HTMLElement && event.target.matches(':focus-visible'));
    setFocusRingClasses(event.target instanceof HTMLElement && event.target.matches(':focus-visible') ? 'focus-visible' : '');
  }, []);
  var handleFocusOut = useCallback(function () {
    setIsFocusVisible(false);
    setFocusRingClasses('');
  }, []);
  var handleMouseDown = useCallback(function () {
    setIsFocusVisible(false);
    setFocusRingClasses('');
  }, []);

  // Initial update and event listeners
  useEffect(function () {
    debouncedUpdate();
  }, [debouncedUpdate, selectedTabId]);

  // Resize observers for container and selected tab with improved error handling
  useEffect(function () {
    var container = containerRef.current;
    if (!container) return;
    var resizeObserver = null;
    try {
      resizeObserver = new ResizeObserver(function (entries) {
        try {
          // 检查观察的元素是否仍然有效
          var validEntries = entries.filter(function (entry) {
            return entry.target && entry.target.isConnected;
          });
          if (validEntries.length > 0) {
            debouncedUpdate();
          }
        } catch (error) {
          console.warn('useSelectionIndicator: Error in ResizeObserver callback:', error);
        }
      });
      resizeObserver.observe(container);
      if (selectedTabRef !== null && selectedTabRef !== void 0 && selectedTabRef.current) {
        resizeObserver.observe(selectedTabRef.current);
      }
    } catch (error) {
      console.warn('useSelectionIndicator: Failed to create ResizeObserver:', error);
    }
    return function () {
      if (resizeObserver) {
        try {
          resizeObserver.disconnect();
        } catch (error) {
          console.warn('useSelectionIndicator: Error disconnecting ResizeObserver:', error);
        }
      }
    };
  }, [containerRef, selectedTabRef, debouncedUpdate]);

  // Focus event listeners
  useEffect(function () {
    var container = containerRef.current;
    if (!container) return;
    var nativeFocusIn = function nativeFocusIn(event) {
      var syntheticEvent = _objectSpread(_objectSpread({}, event), {}, {
        currentTarget: event.currentTarget,
        target: event.target
      });
      handleFocusIn(syntheticEvent);
    };
    container.addEventListener('focusin', nativeFocusIn);
    container.addEventListener('focusout', handleFocusOut);
    container.addEventListener('mousedown', handleMouseDown);
    return function () {
      container.removeEventListener('focusin', nativeFocusIn);
      container.removeEventListener('focusout', handleFocusOut);
      container.removeEventListener('mousedown', handleMouseDown);
    };
  }, [containerRef, handleFocusIn, handleFocusOut, handleMouseDown]);
  return {
    selectionIndicatorProps: {
      focusRingClasses: focusRingClasses,
      isFocusVisible: isFocusVisible,
      style: _objectSpread(_objectSpread({}, indicatorStyle), {}, {
        transition: getTransition(transition)
      })
    },
    listContainerProps: {
      onFocus: handleFocusIn,
      onBlur: handleFocusOut,
      onMouseDown: handleMouseDown
    }
  };
}