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 _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 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 classNames from 'classnames';
import React, { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from 'react';
import PisellCards from "../../../PisellCards";
import SuperTabs from "../../../PisellSuperTabs";
import Iconfont from "../../../iconfont";
import { PisellFind } from "../../../pisellFind";
import "../../PisellTabbar.less";
import { useActiveKey, useExpand } from "../../hooks";
import mock from "../../mock";
import { DEFAULT_LEVEL_CONFIG, LEVEL_ADD_ITEMS, getExpandConfig } from "./constants";
import { addDataSourceItemsByKey, getDefaultActiveKey } from "./utils";

/**
 * PisellTabbar - 多层级 Tabbar 组件
 *
 * 支持最多 3 层级的 Tab 导航，每层级可独立展开/收起
 *
 * @component
 * @example
 * ```tsx
 * <PisellTabbar
 *   dataSource={categoryData}
 *   value={[1, 10, 100]}
 *   onChange={(value) => console.log('当前选中:', value)}
 * />
 * ```
 */
var PisellTabbar = function PisellTabbar(props, ref) {
  var _props$dataSource = props.dataSource,
    dataSource = _props$dataSource === void 0 ? props !== null && props !== void 0 && props.__designMode ? mock : mock : _props$dataSource,
    value = props.value,
    onChange = props.onChange,
    className = props.className,
    style = props.style,
    customLevelConfig = props.levelConfig,
    customExpandConfig = props.expandConfig,
    _props$maxLevel = props.maxLevel,
    maxLevel = _props$maxLevel === void 0 ? 3 : _props$maxLevel,
    _onSearch = props.onSearch,
    searchProps = props.searchProps;
  var containerRef = useRef(null);
  var searchRef = useRef(null);

  /**
   * 每个 PisellTabbarTemplate1 实例使用独立的 DOM id（保留历史前缀），
   * 避免同页面有多个 Tabbar（如资源选择 modal + View All modal 同时挂载，
   * 或前一个 modal 的 destroyOnClose 还在动画延迟期）时 `document.querySelector`
   * 命中错误那一个：PisellFind 的搜索弹窗 portal 会挂到隐藏节点 → 看似"无反应"，
   * 二级 panel 的 portalContainer 也会渲染到错误位置。
   *
   * 使用 `useId()` 保证 SSR 一致并避免 hydration 失配；冒号在 id selector 里
   * 不合法，统一替换。
   */
  var reactId = useId();
  var tabbarId = useMemo(function () {
    return "sku-list-tabbar-temp1-".concat(reactId.replace(/:/g, ''));
  }, [reactId]);

  // 激活的 key 管理
  var _useActiveKey = useActiveKey({
      initialActiveKey: value || getDefaultActiveKey(dataSource, 'id'),
      onChange: onChange
    }),
    setActiveKey = _useActiveKey.setActiveKey,
    getActiveKey = _useActiveKey.getActiveKey,
    _setActiveKey = _useActiveKey._setActiveKey,
    activeKey = _useActiveKey.activeKey,
    setCacheActiveKey = _useActiveKey.setCacheActiveKey,
    resetActiveKey = _useActiveKey.resetActiveKey;

  // 展开状态管理
  var _useExpand = useExpand(),
    expand = _useExpand.expand,
    toggleExpand = _useExpand.toggleExpand,
    getExpand = _useExpand.getExpand;

  // 展开配置
  var expandConfig = customExpandConfig || getExpandConfig();
  var level1Value = useMemo(function () {
    return getActiveKey(0);
  }, [activeKey]);
  var level2Value = useMemo(function () {
    return getActiveKey(1);
  }, [activeKey]);
  var level3Value = useMemo(function () {
    return getActiveKey(2);
  }, [activeKey]);

  /**
   * 搜索弹层是否展开：展开时隐藏分类切换，仅保留搜索入口。
   */
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isSearchOpen = _useState2[0],
    setIsSearchOpen = _useState2[1];

  /**
   * 打开搜索模式
   */
  var openSearchMode = function openSearchMode() {
    setCacheActiveKey(activeKey);
    _setActiveKey([]);
    onChange === null || onChange === void 0 || onChange([]);
    setIsSearchOpen(true);
  };

  /**
   * 关闭搜索模式
   */
  var closeSearchMode = function closeSearchMode() {
    _onSearch === null || _onSearch === void 0 || _onSearch('');
    resetActiveKey();
    setIsSearchOpen(false);
  };

  //@ts-ignore
  useImperativeHandle(ref, function () {
    var _searchRef$current;
    if (props !== null && props !== void 0 && props.__designMode) {
      return containerRef.current;
    }
    return {
      closeSearchMode: searchRef === null || searchRef === void 0 || (_searchRef$current = searchRef.current) === null || _searchRef$current === void 0 ? void 0 : _searchRef$current.close
    };
  });

  /**
   * 同步外部 value 到内部状态
   */
  useEffect(function () {
    if (value) {
      _setActiveKey(value);
    }
  }, [JSON.stringify(value)]);

  /**
   * 获取层级配置
   */
  var getLevelConfig = useCallback(function (level) {
    return _objectSpread(_objectSpread({}, DEFAULT_LEVEL_CONFIG[level]), customLevelConfig === null || customLevelConfig === void 0 ? void 0 : customLevelConfig[level]);
  }, [customLevelConfig]);

  /**
   * 处理一级 Tab 切换
   */
  var handleLevel1Change = useCallback(function (key, item) {
    var _item$children;
    setActiveKey(0, key, item !== null && item !== void 0 && (_item$children = item.children) !== null && _item$children !== void 0 && _item$children.length ? 0 : undefined);
  }, [setActiveKey, activeKey]);

  /**
   * 处理二级 Tab 切换
   */
  var handleLevel2Change = useCallback(function (key, item) {
    var _item$children2;
    setActiveKey(1, key, item !== null && item !== void 0 && (_item$children2 = item.children) !== null && _item$children2 !== void 0 && _item$children2.length ? 0 : undefined);
  }, [setActiveKey, activeKey]);

  /**
   * 处理三级 Tab 切换
   */
  var handleLevel3Change = useCallback(function (key) {
    setActiveKey(2, key);
  }, [setActiveKey, activeKey]);

  /**
   * 渲染 level2/level3 自定义点击卡片（展开按钮）
   */
  var renderExpandCard = useCallback(function (cardProps, level, isExpanded) {
    var _cardProps$active;
    var config = expandConfig[isExpanded ? 'active' : 'inactive'];
    var levelCfg = getLevelConfig(level);
    return /*#__PURE__*/React.createElement(PisellCards.TextCard, _extends({}, cardProps, {
      text: config.text,
      variant: "outlined",
      widthMode: "auto",
      prefixIcon: /*#__PURE__*/React.createElement(Iconfont, {
        type: config.icon,
        style: {
          color: '#000',
          fontSize: 20
        }
      }),
      textConfig: {
        textAlign: 'center',
        color: '#000000',
        flex: 'none'
      },
      style: {
        borderRadius: '20px',
        background: '#ffffff',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        height: levelCfg.cardHeight,
        minWidth: 100
      },
      width: 'auto',
      active: _objectSpread(_objectSpread({}, cardProps.active), {}, {
        style: _objectSpread(_objectSpread({}, (_cardProps$active = cardProps.active) === null || _cardProps$active === void 0 ? void 0 : _cardProps$active.style), {}, {
          color: '#ffffff',
          background: '#7f56d9'
        })
      })
    }));
  }, [expandConfig, activeKey, getLevelConfig]);
  var renderSearch = useCallback(function (itemProps, level) {
    return /*#__PURE__*/React.createElement(PisellFind, _extends({
      showHistory: false,
      modalWidth: '100%'
    }, searchProps, {
      /** 仅在搜索弹层打开时才开启扫码监听：tabbar 的 Find 常驻挂载，关闭时不应长期占用扫码焦点 */
      enableScanner: Boolean(searchProps === null || searchProps === void 0 ? void 0 : searchProps.enableScanner) && isSearchOpen,
      ref: searchRef,
      onSearch: function onSearch(e) {
        _onSearch === null || _onSearch === void 0 || _onSearch(e);
      },
      getContainer: function getContainer() {
        return document.querySelector("#".concat(tabbarId)) || document.body;
      },
      modalStyle: {
        width: '100%'
      },
      onOpen: openSearchMode,
      onClose: closeSearchMode,
      trigger: /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
        card: function card(cardProps) {
          var _cardProps = _objectSpread(_objectSpread({}, cardProps), {}, {
            text: /*#__PURE__*/React.createElement("div", {
              style: {
                display: 'flex',
                alignItems: 'center',
                gap: 4
              }
            }, /*#__PURE__*/React.createElement(Iconfont, {
              type: "pisell2-search-lg",
              style: {
                color: '#000',
                fontSize: 20
              }
            }), /*#__PURE__*/React.createElement(Iconfont, {
              type: "pisell2-scan",
              style: {
                color: '#000',
                fontSize: 20
              }
            }), /*#__PURE__*/React.createElement("span", null, "Find"))
          });
          return renderNormalCard(_cardProps, level);
        }
      }))
    }));
  }, [activeKey, tabbarId, isSearchOpen]);

  /**
   * 渲染 level2/level3 普通卡片
   */
  var renderNormalCard = useCallback(function (cardProps, level) {
    var _cardProps$active2;
    var itemData = cardProps.dataSource;
    var levelCfg = getLevelConfig(level);
    return /*#__PURE__*/React.createElement(PisellCards.TextCard, _extends({
      text: itemData.name
    }, cardProps, {
      variant: "outlined",
      widthMode: "auto",
      textConfig: {
        textAlign: 'center',
        color: '#000',
        maxLines: 2,
        ellipsis: true
      },
      style: {
        height: levelCfg.cardHeight,
        borderRadius: '20px',
        background: '#ffffff',
        minWidth: 100
      },
      width: 'auto',
      active: _objectSpread(_objectSpread({}, cardProps.active), {}, {
        style: _objectSpread(_objectSpread({}, (_cardProps$active2 = cardProps.active) === null || _cardProps$active2 === void 0 ? void 0 : _cardProps$active2.style), {}, {
          color: '#fff',
          background: '#7f56d9'
        })
      })
    }));
  }, [getLevelConfig]);

  /**
   * 一级 Tabbar 数据源
   */
  var level1DataSource = useMemo(function () {
    var full = addDataSourceItemsByKey(dataSource, LEVEL_ADD_ITEMS.level1);
    // 搜索弹层展开时，隐藏分类切换（普通分类 / 全部 / 展开），仅保留搜索入口本身。
    if (isSearchOpen) {
      return full.filter(function (item) {
        return (item === null || item === void 0 ? void 0 : item.key) === 'search';
      });
    }
    return full;
  }, [dataSource, isSearchOpen]);

  /**
   * 渲染一级 Tab Item
   */
  var renderLevel1Item = useCallback(function (itemProps) {
    var itemData = itemProps.dataSource;
    var isExpanded = getExpand('level1');
    if (itemData !== null && itemData !== void 0 && itemData.customClick) {
      if (itemProps.dataSource.key === 'search') {
        return renderSearch(itemProps, 'level1');
      }
      if (itemProps.dataSource.key === 'expand') {
        return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
          card: function card(cardProps) {
            return renderExpandCard(cardProps, 'level1', isExpanded);
          },
          onClick: function onClick() {
            return toggleExpand('level1');
          }
        }));
      }
      return null;
    }

    // 普通项
    return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
      card: function card(cardProps) {
        return renderNormalCard(cardProps, 'level1');
      },
      panel: function panel(panelProps) {
        var _panelProps$dataSourc;
        if (panelProps !== null && panelProps !== void 0 && (_panelProps$dataSourc = panelProps.dataSource) !== null && _panelProps$dataSourc !== void 0 && (_panelProps$dataSourc = _panelProps$dataSourc.children) !== null && _panelProps$dataSourc !== void 0 && _panelProps$dataSourc.length && maxLevel >= 2) {
          return renderLevel2Panel(panelProps);
        }
        return null;
      },
      panelContainer: function panelContainer() {
        return document.querySelector(".pisell-super-tabs-slot-bottom-".concat(tabbarId));
      }
    }));
  }, [getLevelConfig, getExpand, toggleExpand, maxLevel, activeKey, tabbarId]);

  /**
   * 渲染二级 Tabbar 面板
   */
  var renderLevel2Panel = useCallback(function (panelProps) {
    if (maxLevel < 2) return null;
    var _dataSource = panelProps.dataSource.children || [];
    if (_dataSource.length) {
      _dataSource = addDataSourceItemsByKey(_dataSource, LEVEL_ADD_ITEMS.level2);
    }
    var level2Config = getLevelConfig('level2');
    var isExpanded2 = getExpand('level2');
    var skuId = "sku-list-tabbar-".concat(panelProps.dataSource.id);
    return /*#__PURE__*/React.createElement(SuperTabs, {
      id: skuId,
      isControlled: true,
      tabItemStyle: {},
      dataSource: _dataSource,
      value: level2Value,
      onChange: handleLevel2Change,
      rowKey: "id",
      style: {
        flex: 1,
        background: level2Config.superTabsBg
      },
      gridProps: {
        direction: 'horizontal',
        gap: 4,
        wrap: isExpanded2 ? 'wrap' : 'nowrap',
        startSlot: /*#__PURE__*/React.createElement("div", {
          style: {
            paddingLeft: level2Config.paddingLeft
          }
        }, /*#__PURE__*/React.createElement(Iconfont, {
          type: "pisell2-trend-down-01",
          style: {
            color: '#fff',
            fontSize: 24,
            marginRight: 8
          }
        }))
      },
      scrollViewProps: {
        style: {
          padding: '4px 8px'
        },
        overflow: !isExpanded2 ? 'x' : 'hidden',
        scrollbarStyle: 'none',
        scrollActionsConfig: {
          type: 'lrArrows',
          show: true
        }
      },
      renderItem: function renderItem(itemProps) {
        var itemData = itemProps.dataSource;

        // 处理展开按钮
        if (itemData !== null && itemData !== void 0 && itemData.customClick) {
          return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
            card: function card(cardProps) {
              return renderExpandCard(cardProps, 'level2', isExpanded2);
            },
            onClick: function onClick() {
              return toggleExpand('level2');
            }
          }));
        }

        // 普通项
        return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
          card: function card(cardProps) {
            return renderNormalCard(cardProps, 'level2');
          },
          panel: function panel(panelProps2) {
            var _panelProps2$dataSour;
            if (panelProps2 !== null && panelProps2 !== void 0 && (_panelProps2$dataSour = panelProps2.dataSource) !== null && _panelProps2$dataSour !== void 0 && (_panelProps2$dataSour = _panelProps2$dataSour.children) !== null && _panelProps2$dataSour !== void 0 && _panelProps2$dataSour.length && maxLevel >= 3) {
              return renderLevel3Panel(panelProps2);
            }
            return null;
          },
          panelContainer: function panelContainer() {
            return document.querySelector(".pisell-super-tabs-slot-bottom-".concat(skuId));
          }
        }));
      }
    });
  }, [level2Value, maxLevel, activeKey, getActiveKey, handleLevel2Change, getExpand, toggleExpand, getLevelConfig, renderExpandCard, renderNormalCard]);

  /**
   * 渲染三级 Tabbar 面板
   */
  var renderLevel3Panel = useCallback(function (panelProps2) {
    if (maxLevel < 3) return null;
    var _dataSource2 = panelProps2.dataSource.children || [];
    if (_dataSource2.length) {
      _dataSource2 = addDataSourceItemsByKey(_dataSource2, LEVEL_ADD_ITEMS.level3);
    }
    var level3Config = getLevelConfig('level3');
    var isExpanded3 = getExpand('level3');
    var skuId = "sku-list-tabbar-".concat(panelProps2.dataSource.id);
    return /*#__PURE__*/React.createElement(SuperTabs, {
      id: skuId,
      isControlled: true,
      tabItemStyle: {},
      dataSource: _dataSource2,
      value: level3Value,
      onChange: handleLevel3Change,
      rowKey: "id",
      style: {
        flex: 1,
        background: level3Config.superTabsBg
      },
      gridProps: {
        direction: 'horizontal',
        gap: 4,
        wrap: isExpanded3 ? 'wrap' : 'nowrap',
        startSlot: /*#__PURE__*/React.createElement("div", {
          style: {
            paddingLeft: level3Config.paddingLeft
          }
        }, /*#__PURE__*/React.createElement(Iconfont, {
          type: "pisell2-trend-down-01",
          style: {
            color: '#fff',
            fontSize: 24,
            marginRight: 8
          }
        }))
      },
      scrollViewProps: {
        style: {
          padding: '4px 8px'
        },
        overflow: !isExpanded3 ? 'x' : 'hidden',
        scrollbarStyle: 'none',
        scrollActionsConfig: {
          type: 'lrArrows',
          show: true
        }
      },
      renderItem: function renderItem(itemProps) {
        var itemData = itemProps.dataSource;

        // 处理展开按钮
        if (itemData !== null && itemData !== void 0 && itemData.customClick) {
          return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
            card: function card(cardProps) {
              return renderExpandCard(cardProps, 'level3', isExpanded3);
            },
            onClick: function onClick() {
              return toggleExpand('level3');
            }
          }));
        }

        // 普通项
        return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
          card: function card(cardProps) {
            return renderNormalCard(cardProps, 'level3');
          }
        }));
      }
    });
  }, [level3Value, maxLevel, activeKey, getActiveKey, handleLevel3Change, getExpand, toggleExpand, getLevelConfig, renderExpandCard, renderNormalCard]);

  /**
   * 渲染一级 Tabbar
   */
  var level1Config = getLevelConfig('level1');
  var isExpanded1 = getExpand('level1');
  return dataSource.length ? /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-tabbar', className),
    style: style,
    ref: containerRef
  }, /*#__PURE__*/React.createElement(SuperTabs, {
    isControlled: true,
    id: tabbarId,
    tabItemStyle: {},
    dataSource: level1DataSource,
    value: level1Value,
    onChange: handleLevel1Change,
    rowKey: "id",
    style: {
      flex: 1,
      background: level1Config.superTabsBg
    },
    gridProps: {
      direction: 'horizontal',
      gap: 4,
      wrap: isExpanded1 ? 'wrap' : 'nowrap'
    },
    scrollViewProps: {
      style: {
        padding: '4px 8px'
      },
      overflow: !isExpanded1 ? 'x' : 'hidden',
      scrollbarStyle: 'none',
      scrollActionsConfig: {
        type: 'lrArrows',
        show: true
      }
    },
    renderItem: renderLevel1Item
  })) : null;
};
PisellTabbar.displayName = 'PisellTabbar';
export default /*#__PURE__*/forwardRef(PisellTabbar);