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); }
var _excluded = ["children", "className"],
  _excluded2 = ["children", "isSelected", "isDisabled", "className", "onClick", "tabId", "autoRegister"],
  _excluded3 = ["children", "className"],
  _excluded4 = ["focusRingClasses", "isFocusVisible", "style", "className"],
  _excluded5 = ["visible", "location", "className"],
  _excluded6 = ["direction", "disabled", "onClick", "className", "aria-label"],
  _excluded7 = ["isPrevDisabled", "isNextDisabled", "onPrevClick", "onNextClick", "prevAction", "nextAction", "className"],
  _excluded8 = ["selectedTab", "onTabChange", "autoScrollToSelected", "children", "className", "railRef"];
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 _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { forwardRef, useMemo, useContext, createContext, useCallback, useRef, useEffect } from 'react';
import classNames from 'classnames';
import { tabWrapperClasses, tabListClasses, tabItemClasses, railClasses, selectionClasses, shadowClasses, chevronClasses, chevronButtonClasses } from "./styles";
import { safeScrollTo } from "./utils";
import ChevronLeft from '@pisell/icon/es/ChevronLeft';
import ChevronRight from '@pisell/icon/es/ChevronRight';

// WeakRef 类型声明（用于兼容性检测）

// Tab上下文
var TabContext = /*#__PURE__*/createContext({});

// Hook to use tab context
var useTabContext = function useTabContext() {
  var context = useContext(TabContext);
  if (!context) {
    throw new Error('useTabContext must be used within a TabContext.Provider');
  }
  return context;
};
var TabListContainer = /*#__PURE__*/forwardRef(function (_ref, ref) {
  var children = _ref.children,
    className = _ref.className,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React.createElement("ul", _extends({
    ref: ref,
    className: classNames(tabListClasses.list, className),
    role: "tablist"
  }, props), children);
});
var TabItem = /*#__PURE__*/forwardRef(function (_ref2, ref) {
  var children = _ref2.children,
    _ref2$isSelected = _ref2.isSelected,
    isSelected = _ref2$isSelected === void 0 ? false : _ref2$isSelected,
    _ref2$isDisabled = _ref2.isDisabled,
    isDisabled = _ref2$isDisabled === void 0 ? false : _ref2$isDisabled,
    className = _ref2.className,
    onClick = _ref2.onClick,
    tabId = _ref2.tabId,
    _ref2$autoRegister = _ref2.autoRegister,
    autoRegister = _ref2$autoRegister === void 0 ? true : _ref2$autoRegister,
    props = _objectWithoutProperties(_ref2, _excluded2);
  var _useTabContext = useTabContext(),
    selectedTab = _useTabContext.selectedTab,
    onTabChange = _useTabContext.onTabChange,
    registerTab = _useTabContext.registerTab,
    unregisterTab = _useTabContext.unregisterTab;
  var elementRef = useRef(null);

  // ref 合并逻辑已在 combinedRef 中处理

  // 组合内部ref和外部ref
  var combinedRef = useCallback(function (element) {
    elementRef.current = element;
    if (typeof ref === 'function') {
      ref(element);
    } else if (ref && 'current' in ref) {
      ref.current = element;
    }
  }, [ref]);

  // 自动注册tab
  useEffect(function () {
    if (autoRegister && tabId && elementRef.current && registerTab) {
      registerTab(tabId, elementRef.current);
      return function () {
        if (unregisterTab) {
          unregisterTab(tabId);
        }
      };
    }
  }, [tabId, autoRegister, registerTab, unregisterTab]);

  // 处理点击事件
  var handleClick = useCallback(function () {
    if (!isDisabled) {
      if (tabId && onTabChange) {
        onTabChange(tabId);
      }
      onClick === null || onClick === void 0 || onClick(tabId);
    }
  }, [isDisabled, tabId, onTabChange, onClick]);

  // 确定是否选中
  var isTabSelected = tabId ? selectedTab === tabId : isSelected;
  return /*#__PURE__*/React.createElement("li", _extends({
    id: tabId,
    ref: combinedRef,
    className: classNames(tabItemClasses.item, isTabSelected && tabItemClasses.selected, isDisabled && tabItemClasses.disabled, className),
    role: "tab",
    "aria-selected": isTabSelected,
    "aria-disabled": isDisabled,
    disabled: isDisabled,
    onClick: handleClick,
    tabIndex: isTabSelected ? 0 : -1
  }, props), /*#__PURE__*/React.createElement("span", null, children));
});
var Rail = /*#__PURE__*/forwardRef(function (_ref3, ref) {
  var children = _ref3.children,
    className = _ref3.className,
    props = _objectWithoutProperties(_ref3, _excluded3);
  var _useTabContext2 = useTabContext(),
    contextRailRef = _useTabContext2.railRef;

  // 合并context ref和外部ref
  var mergedRef = useCallback(function (element) {
    // 安全地设置context中的railRef
    if (contextRailRef && 'current' in contextRailRef) {
      contextRailRef.current = element;
    }

    // 设置外部传入的ref
    if (typeof ref === 'function') {
      ref(element);
    } else if (ref && 'current' in ref) {
      ref.current = element;
    }
  }, [ref, contextRailRef]);
  return /*#__PURE__*/React.createElement("div", _extends({
    ref: mergedRef,
    className: classNames(railClasses.rail, className)
  }, props), children);
});
var SelectionIndicator = /*#__PURE__*/forwardRef(function (_ref4, ref) {
  var focusRingClasses = _ref4.focusRingClasses,
    _ref4$isFocusVisible = _ref4.isFocusVisible,
    isFocusVisible = _ref4$isFocusVisible === void 0 ? false : _ref4$isFocusVisible,
    style = _ref4.style,
    className = _ref4.className,
    props = _objectWithoutProperties(_ref4, _excluded4);
  return /*#__PURE__*/React.createElement("div", _extends({
    ref: ref,
    className: classNames(selectionClasses.selection, selectionClasses.position, _defineProperty({}, selectionClasses.focused, isFocusVisible && focusRingClasses), className),
    style: style,
    "aria-hidden": "true"
  }, props));
});
var ScrollShadow = /*#__PURE__*/forwardRef(function (_ref5, ref) {
  var visible = _ref5.visible,
    location = _ref5.location,
    className = _ref5.className,
    props = _objectWithoutProperties(_ref5, _excluded5);
  return /*#__PURE__*/React.createElement("div", _extends({
    ref: ref,
    className: classNames(shadowClasses.shadow, _defineProperty(_defineProperty(_defineProperty({}, shadowClasses.isVisible, visible), shadowClasses.locationStart, location === 'start'), shadowClasses.locationEnd, location === 'end'), className)
  }, props));
});
var ChevronButton = /*#__PURE__*/forwardRef(function (_ref6, ref) {
  var direction = _ref6.direction,
    _ref6$disabled = _ref6.disabled,
    disabled = _ref6$disabled === void 0 ? false : _ref6$disabled,
    onClick = _ref6.onClick,
    className = _ref6.className,
    ariaLabel = _ref6['aria-label'],
    props = _objectWithoutProperties(_ref6, _excluded6);
  var defaultAriaLabel = direction === 'prev' ? 'prev' : 'next';
  return /*#__PURE__*/React.createElement("button", _extends({
    ref: ref,
    className: classNames(chevronButtonClasses.button, _defineProperty(_defineProperty(_defineProperty({}, chevronButtonClasses.disabled, disabled), chevronButtonClasses.prev, direction === 'prev'), chevronButtonClasses.next, direction === 'next'), className),
    disabled: disabled,
    onClick: onClick,
    "aria-label": ariaLabel || defaultAriaLabel,
    type: "button"
  }, props), direction === 'prev' ? /*#__PURE__*/React.createElement(ChevronLeft, null) : /*#__PURE__*/React.createElement(ChevronRight, null));
});
var ChevronControls = function ChevronControls(_ref7) {
  var _ref7$isPrevDisabled = _ref7.isPrevDisabled,
    isPrevDisabled = _ref7$isPrevDisabled === void 0 ? false : _ref7$isPrevDisabled,
    _ref7$isNextDisabled = _ref7.isNextDisabled,
    isNextDisabled = _ref7$isNextDisabled === void 0 ? false : _ref7$isNextDisabled,
    onPrevClick = _ref7.onPrevClick,
    onNextClick = _ref7.onNextClick,
    prevAction = _ref7.prevAction,
    nextAction = _ref7.nextAction,
    className = _ref7.className,
    props = _objectWithoutProperties(_ref7, _excluded7);
  // 支持两种命名方式
  var handlePrevClick = onPrevClick || prevAction;
  var handleNextClick = onNextClick || nextAction;
  return /*#__PURE__*/React.createElement("div", _extends({
    className: classNames(chevronClasses.controls, className)
  }, props), /*#__PURE__*/React.createElement(ChevronButton, {
    direction: "prev",
    disabled: isPrevDisabled,
    onClick: handlePrevClick
  }), /*#__PURE__*/React.createElement(ChevronButton, {
    direction: "next",
    disabled: isNextDisabled,
    onClick: handleNextClick
  }));
};
var TabsStructure = function TabsStructure(_ref8) {
  var selectedTab = _ref8.selectedTab,
    onTabChange = _ref8.onTabChange,
    _ref8$autoScrollToSel = _ref8.autoScrollToSelected,
    autoScrollToSelected = _ref8$autoScrollToSel === void 0 ? true : _ref8$autoScrollToSel,
    children = _ref8.children,
    className = _ref8.className,
    externalRailRef = _ref8.railRef,
    props = _objectWithoutProperties(_ref8, _excluded8);
  // 使用WeakRef优化内存管理，避免内存泄漏（支持降级到直接引用）
  var tabElementsRef = useRef(new Map());
  var internalRailRef = useRef(null);

  // 使用外部传入的railRef，如果没有则使用内部的
  var railRef = externalRailRef || internalRailRef;
  if (!selectedTab && children) {
    console.warn('TabsStructure: No selectedTab provided, consider setting a default value');
  }
  var registerTab = useCallback(function (tabId, element) {
    if (!tabId || !element) {
      console.warn('TabsStructure: Invalid tabId or element provided to registerTab');
      return;
    }

    // 特性检测：检查浏览器是否支持 WeakRef
    if (typeof WeakRef !== 'undefined') {
      // 支持 WeakRef 的现代浏览器
      tabElementsRef.current.set(tabId, new WeakRef(element));
    } else {
      // 降级到直接引用（需要手动清理）
      tabElementsRef.current.set(tabId, element);
    }
  }, []);

  // 注销tab元素
  var unregisterTab = useCallback(function (tabId) {
    if (tabId) {
      tabElementsRef.current.delete(tabId);
    }
  }, []);

  // 清理所有tab引用（主要用于降级模式的内存管理）
  var clearAllTabs = useCallback(function () {
    tabElementsRef.current.clear();
  }, []);

  // 组件卸载时清理所有引用
  useEffect(function () {
    return function () {
      // 在降级模式下，确保清理所有直接引用
      if (typeof WeakRef === 'undefined') {
        clearAllTabs();
      }
    };
  }, [clearAllTabs]);
  var getTabElement = useCallback(function (tabId) {
    var ref = tabElementsRef.current.get(tabId);
    if (!ref) return null;

    // 特性检测：检查是否为 WeakRef 实例
    if (typeof WeakRef !== 'undefined' && ref instanceof WeakRef) {
      var element = ref.deref();
      if (!element) {
        // 元素已被垃圾回收，清理引用
        tabElementsRef.current.delete(tabId);
        return null;
      }
      return element;
    } else {
      // 降级模式：直接返回元素
      return ref;
    }
  }, []);

  // 优化的滚动函数，包含错误处理和边界检查
  var scrollToTab = useCallback(function (tabId) {
    if (!tabId || !railRef.current) {
      return;
    }
    var targetElement = getTabElement(tabId);
    if (!targetElement) {
      console.warn("TabsStructure: Tab element with id \"".concat(tabId, "\" not found"));
      return;
    }

    // 检查元素是否有有效的offsetParent（即是否在DOM中且可见）
    if (!targetElement.offsetParent) {
      console.warn("TabsStructure: Tab element \"".concat(tabId, "\" is not visible or not in DOM"));
      return;
    }
    var rail = railRef.current;
    var targetLeft = targetElement.offsetLeft;
    var currentScrollLeft = rail.scrollLeft;

    // 只有当需要滚动时才执行
    if (Math.abs(targetLeft - currentScrollLeft) > 1) {
      safeScrollTo(rail, {
        left: targetLeft,
        behavior: 'smooth'
      });
    }
  }, [getTabElement]);

  // 自动滚动到选中的tab
  useEffect(function () {
    if (autoScrollToSelected && selectedTab) {
      scrollToTab(selectedTab);
    }
  }, [selectedTab, autoScrollToSelected, scrollToTab]);

  // 上下文值
  var contextValue = useMemo(function () {
    return {
      selectedTab: selectedTab,
      onTabChange: onTabChange,
      registerTab: registerTab,
      unregisterTab: unregisterTab,
      railRef: railRef
    };
  }, [selectedTab, onTabChange, registerTab, unregisterTab, railRef]);
  return /*#__PURE__*/React.createElement(TabContext.Provider, {
    value: contextValue
  }, /*#__PURE__*/React.createElement("div", _extends({}, props, {
    className: classNames(tabWrapperClasses.wrapper, className)
  }), children));
};
var TabsStructureWithSubComponents = TabsStructure;
TabsStructureWithSubComponents.Rail = Rail;
TabsStructureWithSubComponents.ListContainer = TabListContainer;
TabsStructureWithSubComponents.Item = TabItem;
TabsStructureWithSubComponents.SelectionIndicator = SelectionIndicator;
TabsStructureWithSubComponents.ScrollShadow = ScrollShadow;
TabsStructureWithSubComponents.ChevronControls = ChevronControls;
TabsStructureWithSubComponents.ChevronButton = ChevronButton;
TabsStructure.displayName = 'TabsStructure';
Rail.displayName = 'TabsStructure.Rail';
TabListContainer.displayName = 'TabsStructure.ListContainer';
TabItem.displayName = 'TabsStructure.Item';
SelectionIndicator.displayName = 'TabsStructure.SelectionIndicator';
ScrollShadow.displayName = 'TabsStructure.ScrollShadow';
ChevronControls.displayName = 'TabsStructure.ChevronControls';
ChevronButton.displayName = 'TabsStructure.ChevronButton';
export default TabsStructureWithSubComponents;

// 导出所有子组件
export { TabListContainer, TabItem, Rail, SelectionIndicator, ScrollShadow, ChevronControls, ChevronButton };