function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 React, { useState, useRef, useEffect } from 'react';
import classNames from 'classnames';
import { useDebounceFn } from 'ahooks';
import ChevronLeft from '@pisell/icon/es/ChevronLeft';
import ChevronRight from '@pisell/icon/es/ChevronRight';
import "./index.less";
var PisellAnchor = function PisellAnchor(_ref) {
  var _ref$options = _ref.options,
    options = _ref$options === void 0 ? [] : _ref$options,
    tab = _ref.tab,
    className = _ref.className,
    style = _ref.style,
    onChange = _ref.onChange,
    onTabClick = _ref.onTabClick,
    containerRef = _ref.containerRef,
    _ref$platform = _ref.platform,
    platform = _ref$platform === void 0 ? 'pc' : _ref$platform;
  var contentRef = useRef(null);
  var isClickScrolling = useRef(false);
  var _useState = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    leftWidth = _useState2[0],
    setLeftWidth = _useState2[1];
  var _useState3 = useState(40),
    _useState4 = _slicedToArray(_useState3, 2),
    rightWidth = _useState4[0],
    setRightWidth = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    showButtons = _useState6[0],
    setShowButtons = _useState6[1];

  // 检查是否需要显示左右滚动按钮
  useEffect(function () {
    if (contentRef.current) {
      var _contentRef$current = contentRef.current,
        scrollWidth = _contentRef$current.scrollWidth,
        clientWidth = _contentRef$current.clientWidth;
      setShowButtons(scrollWidth > clientWidth);
    }
  }, [options]);

  // 处理水平滚动
  var handleHorizontalScroll = useDebounceFn(function (e) {
    var target = e.target;
    var scrollLeft = target.scrollLeft,
      scrollWidth = target.scrollWidth,
      clientWidth = target.clientWidth;
    setLeftWidth(scrollLeft > 0 ? 40 : 0);
    setRightWidth(scrollLeft + clientWidth >= scrollWidth ? 0 : 40);
  }, {
    wait: 200
  }).run;

  // 处理内容区域滚动
  var handleContentScroll = useDebounceFn(function () {
    if (isClickScrolling.current || !(containerRef !== null && containerRef !== void 0 && containerRef.current)) return;
    var container = containerRef.current;
    var scrollTop = container.scrollTop;
    var containerHeight = container.clientHeight;
    var scrollHeight = container.scrollHeight;
    // 优先检查是否滚动到底部
    var isAtBottom = Math.abs(scrollTop + containerHeight - scrollHeight) < 1;
    if (isAtBottom) {
      var lastOption = options[options.length - 1];
      if (lastOption && tab !== lastOption.id) {
        onChange === null || onChange === void 0 || onChange(lastOption.id);
      }
      return; // 如果在底部，直接返回，不再计算可视占比
    }

    // 如果不在底部，再计算可视占比
    var maxVisibleRatio = 0;
    var activeOption = null;
    var _iterator = _createForOfIteratorHelper(options),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var option = _step.value;
        var element = document.querySelector("[data-section=\"".concat(option.id, "\"]"));
        if (element instanceof HTMLElement) {
          var elementTop = element.offsetTop;
          var elementHeight = element.offsetHeight;
          var elementBottom = elementTop + elementHeight;
          var visibleTop = Math.max(elementTop, scrollTop);
          var visibleBottom = Math.min(elementBottom, scrollTop + containerHeight);
          var visibleHeight = Math.max(0, visibleBottom - visibleTop);
          var visibleRatio = visibleHeight / elementHeight;
          if (visibleRatio > maxVisibleRatio) {
            maxVisibleRatio = visibleRatio;
            activeOption = option;
          }
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    if (activeOption && tab !== activeOption.id) {
      onChange === null || onChange === void 0 || onChange(activeOption.id);
    }
  }, {
    wait: 100
  }).run;

  // 监听容器滚动
  useEffect(function () {
    var container = containerRef === null || containerRef === void 0 ? void 0 : containerRef.current;
    if (!container) return;
    container.addEventListener('scroll', handleContentScroll);
    return function () {
      return container.removeEventListener('scroll', handleContentScroll);
    };
  }, [handleContentScroll]);

  // 点击锚点，滚动到对应位置
  var handleOptionClick = function handleOptionClick(item) {
    onChange === null || onChange === void 0 || onChange(item.id);
    onTabClick === null || onTabClick === void 0 || onTabClick();
    var targetElement = document.querySelector("[data-section=\"".concat(item.id, "\"]"));
    if (targetElement instanceof HTMLElement && containerRef !== null && containerRef !== void 0 && containerRef.current) {
      isClickScrolling.current = true;

      // 计算目标元素之前所有元素的高度总和
      var scrollDistance = 0;
      var _iterator2 = _createForOfIteratorHelper(options),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var option = _step2.value;
          if (option.id === item.id) break;
          var element = document.querySelector("[data-section=\"".concat(option.id, "\"]"));
          if (element instanceof HTMLElement) {
            scrollDistance += element.offsetHeight;
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      containerRef.current.scrollTo({
        top: scrollDistance,
        behavior: 'smooth'
      });
      setTimeout(function () {
        isClickScrolling.current = false;
      }, 1000);
    }
  };

  // 左右按钮点击处理
  var handlePageChange = function handlePageChange(type) {
    if (contentRef.current) {
      var _contentRef$current2 = contentRef.current,
        scrollLeft = _contentRef$current2.scrollLeft,
        clientWidth = _contentRef$current2.clientWidth;
      contentRef.current.scrollTo({
        left: scrollLeft + (type === 'left' ? -clientWidth : clientWidth),
        behavior: 'smooth'
      });
    }
  };
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-anchor-tabs', className),
    style: style
  }, showButtons && /*#__PURE__*/React.createElement("div", {
    className: "pisell-anchor-tabs-btn-left",
    style: {
      width: leftWidth
    },
    onClick: function onClick() {
      return handlePageChange('left');
    }
  }, /*#__PURE__*/React.createElement(ChevronLeft, {
    className: "pisell-anchor-tabs-btn-icon"
  })), /*#__PURE__*/React.createElement("div", {
    ref: contentRef,
    className: "pisell-anchor-tabs-content",
    onScroll: handleHorizontalScroll
  }, options.map(function (item) {
    return /*#__PURE__*/React.createElement("div", {
      key: item.id,
      className: classNames('pisell-anchor-tabs-tab', {
        'pisell-anchor-tabs-tab-active': tab === item.id
      }),
      onClick: function onClick() {
        return handleOptionClick(item);
      }
    }, /*#__PURE__*/React.createElement("span", {
      className: "pisell-anchor-tabs-tab-content"
    }, item.name));
  })), showButtons && /*#__PURE__*/React.createElement("div", {
    className: "pisell-anchor-tabs-btn-right",
    style: {
      width: rightWidth
    },
    onClick: function onClick() {
      return handlePageChange('right');
    }
  }, /*#__PURE__*/React.createElement(ChevronRight, {
    className: "pisell-anchor-tabs-btn-icon"
  })));
};
export default PisellAnchor;