function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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, useRef, useMemo, useCallback } from 'react';
export var useWaterfall = function useWaterfall(items, options) {
  // 用于强制重新计算的版本号
  var _useState = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    recalcVersion = _useState2[0],
    setRecalcVersion = _useState2[1];

  // 分别存储高度和宽度
  var itemSizes = useRef(new Map());
  var itemRefs = useRef(new Map());

  // 注册元素引用的函数
  var registerItemRef = useCallback(function (id, element) {
    if (element) {
      itemRefs.current.set(id, element);
    } else {
      itemRefs.current.delete(id);
    }
  }, []);

  // 测量元素尺寸（高度和宽度）
  var measureItemSize = useCallback(function (id) {
    var element = itemRefs.current.get(id);
    if (element) {
      var rect = element.getBoundingClientRect();
      var size = {
        width: rect.width,
        height: rect.height
      };
      itemSizes.current.set(id, size);
      return size;
    }
    return itemSizes.current.get(id) || {
      width: 200,
      height: 200
    }; // 默认尺寸
  }, []);

  // 根据direction获取相关尺寸
  var getItemSize = useCallback(function (item) {
    var direction = options.direction;
    if (direction === 'vertical') {
      // 垂直模式：使用高度
      if (item.height) return item.height;
      var measured = itemSizes.current.get(item.id);
      return (measured === null || measured === void 0 ? void 0 : measured.height) || 200;
    } else {
      // 水平模式：使用宽度
      if (item.width) return item.width;
      var _measured = itemSizes.current.get(item.id);
      return (_measured === null || _measured === void 0 ? void 0 : _measured.width) || 200;
    }
  }, [options]);

  // 直接使用useMemo计算布局，支持垂直和水平两种模式
  var layout = useMemo(function () {
    var trackCount = options.tracks,
      trackGap = options.trackGap,
      itemGap = options.itemGap,
      direction = options.direction;

    // 初始化轨道（垂直模式为列，水平模式为行）
    var newTracks = Array.from({
      length: trackCount
    }, function () {
      return {
        items: [],
        size: 0
      };
    });

    // 为每个项目分配到最短的轨道
    items.forEach(function (item) {
      // 找到当前尺寸最小的轨道
      var shortestTrackIndex = newTracks.reduce(function (minIndex, track, index, arr) {
        return track.size < arr[minIndex].size ? index : minIndex;
      }, 0);
      var targetTrack = newTracks[shortestTrackIndex];

      // 获取项目在当前方向上的尺寸
      var itemSize = getItemSize(item);

      // 将项目添加到目标轨道
      targetTrack.items.push(item);

      // 更新轨道尺寸（如果不是第一个项目，需要加上项目间距）
      if (targetTrack.items.length > 1) {
        targetTrack.size += itemGap;
      }
      targetTrack.size += itemSize;
    });

    // 计算总尺寸
    var totalSize = Math.max.apply(Math, _toConsumableArray(newTracks.map(function (track) {
      return track.size;
    })).concat([0]));
    return {
      tracks: newTracks,
      totalSize: totalSize
    };
  }, [items, options, recalcVersion, getItemSize]);

  // 重新计算布局的函数 - 重新测量元素尺寸，然后触发重新计算
  var recalculateLayout = useCallback(function () {
    // 重新测量所有已注册的元素尺寸
    var hasChanges = false;
    itemRefs.current.forEach(function (element, id) {
      var rect = element.getBoundingClientRect();
      var newSize = {
        width: rect.width,
        height: rect.height
      };
      var oldSize = itemSizes.current.get(id);
      if (!oldSize || oldSize.width !== newSize.width || oldSize.height !== newSize.height) {
        hasChanges = true;
        itemSizes.current.set(id, newSize);
      }
    });

    // 如果有变化，更新版本号来触发重新计算
    if (hasChanges) {
      setRecalcVersion(function (prev) {
        return prev + 1;
      });
    }
  }, []);

  // 监听窗口大小变化，重新计算布局
  useEffect(function () {
    var timeoutId;
    var handleResize = function handleResize() {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(function () {
        recalculateLayout();
      }, 100);
    };
    window.addEventListener('resize', handleResize);
    return function () {
      window.removeEventListener('resize', handleResize);
      clearTimeout(timeoutId);
    };
  }, [recalculateLayout]);
  return {
    layout: layout,
    registerItemRef: registerItemRef,
    measureItemSize: measureItemSize,
    recalculateLayout: recalculateLayout
  };
};
export default useWaterfall;