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; }
/**
 * 视口 / 地图区尺寸、内容区宽高与偏移、缩放与全屏、fitBounds、拖拽图元后恢复 transform
 */
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { getContentSize, getPixelBoundingBox } from "../utils/layoutMeasurements";

/** 平面图包围盒单侧默认外扩（像素）；过大会导致首屏大量空白 */
var DEFAULT_BOUNDING_PADDING = 56;

/** 视口内与首屏对齐时，图元束左上与容器边缘的留白 */
var VIEWPORT_TOP_LEFT_MARGIN = 16;

/** react-zoom-pan-pinch TransformWrapper render 注入的上下文 */

export function useFloorMapTransformMetrics(params) {
  var items = params.items,
    cellSize = params.cellSize,
    itemGap = params.itemGap,
    effectiveItemUnit = params.effectiveItemUnit,
    isFloorMapView = params.isFloorMapView,
    mode = params.mode,
    zoom = params.zoom,
    transformRef = params.transformRef,
    contentOffsetRef = params.contentOffsetRef,
    boundingPaddingProp = params.boundingPadding,
    frameResetKey = params.frameResetKey;
  var padSingle = boundingPaddingProp !== null && boundingPaddingProp !== void 0 ? boundingPaddingProp : DEFAULT_BOUNDING_PADDING;
  var containerRef = useRef(null);
  var mapAreaRef = useRef(null);
  var _useState = useState({
      width: 0,
      height: 0
    }),
    _useState2 = _slicedToArray(_useState, 2),
    viewportSize = _useState2[0],
    setViewportSize = _useState2[1];
  useEffect(function () {
    var el = containerRef.current;
    if (!el) return;
    var ro = new ResizeObserver(function () {
      setViewportSize({
        width: el.clientWidth,
        height: el.clientHeight
      });
    });
    ro.observe(el);
    setViewportSize({
      width: el.clientWidth,
      height: el.clientHeight
    });
    return function () {
      return ro.disconnect();
    };
  }, []);
  var _useState3 = useState({
      width: 0,
      height: 0
    }),
    _useState4 = _slicedToArray(_useState3, 2),
    mapAreaSize = _useState4[0],
    setMapAreaSize = _useState4[1];
  useEffect(function () {
    var el = mapAreaRef.current;
    if (!el) return;
    var ro = new ResizeObserver(function () {
      setMapAreaSize({
        width: el.clientWidth,
        height: el.clientHeight
      });
    });
    ro.observe(el);
    setMapAreaSize({
      width: el.clientWidth,
      height: el.clientHeight
    });
    return function () {
      return ro.disconnect();
    };
  }, []);

  /** 默认开启：有空图元时首屏 fit 全图；仅 `autoFitOnMount: false` 关闭 */
  var autoFitOnMount = zoom.autoFitOnMount !== false;
  var zoomConfig = useMemo(function () {
    var _zoom$defaultScale, _zoom$min, _zoom$max, _zoom$step;
    return {
      initialScale: (_zoom$defaultScale = zoom.defaultScale) !== null && _zoom$defaultScale !== void 0 ? _zoom$defaultScale : 1,
      minScale: (_zoom$min = zoom.min) !== null && _zoom$min !== void 0 ? _zoom$min : 0.5,
      maxScale: (_zoom$max = zoom.max) !== null && _zoom$max !== void 0 ? _zoom$max : 2,
      step: (_zoom$step = zoom.step) !== null && _zoom$step !== void 0 ? _zoom$step : 0.1
    };
  }, [zoom.defaultScale, zoom.min, zoom.max, zoom.step]);
  var _useState5 = useState(zoomConfig.initialScale),
    _useState6 = _slicedToArray(_useState5, 2),
    scale = _useState6[0],
    setScale = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    isFullscreen = _useState8[0],
    setIsFullscreen = _useState8[1];
  var _useMemo = useMemo(function () {
      var fromItems = getContentSize(items, cellSize, itemGap, effectiveItemUnit);
      var pad = padSingle * 2;
      var zeroOffset = {
        contentOffsetX: 0,
        contentOffsetY: 0
      };
      var useBoundingBox = isFloorMapView && effectiveItemUnit === 'pixel' && items.length > 0;
      var box = useBoundingBox ? getPixelBoundingBox(items, cellSize) : null;
      var padded;
      var alignPad = null;
      if (box) {
        var w = box.maxRight - box.minLeft + pad;
        var h = box.maxBottom - box.minTop + pad;
        padded = {
          contentWidth: w,
          contentHeight: h,
          contentOffsetX: padSingle - box.minLeft,
          contentOffsetY: padSingle - box.minTop
        };
        alignPad = padSingle;
      } else {
        padded = _objectSpread({
          contentWidth: fromItems.contentWidth + pad,
          contentHeight: fromItems.contentHeight + pad
        }, zeroOffset);
      }
      var result = _objectSpread(_objectSpread({}, padded), {}, {
        alignPadSingle: alignPad
      });
      /** 像素平面图：阅读态与编辑态均将内容区至少撑满视口，便于大空白处平移 */
      if (!isFloorMapView || effectiveItemUnit !== 'pixel') return result;
      var vw = mapAreaSize.width > 0 ? mapAreaSize.width : viewportSize.width;
      var vh = mapAreaSize.height > 0 ? mapAreaSize.height : viewportSize.height;
      if (vw <= 0 || vh <= 0) return result;
      result = _objectSpread(_objectSpread({}, result), {}, {
        contentWidth: Math.max(padded.contentWidth, vw),
        contentHeight: Math.max(padded.contentHeight, vh)
      });
      return result;
    }, [items, cellSize, itemGap, effectiveItemUnit, isFloorMapView, mapAreaSize.width, mapAreaSize.height, viewportSize.width, viewportSize.height, padSingle]),
    contentWidth = _useMemo.contentWidth,
    contentHeight = _useMemo.contentHeight,
    contentOffsetX = _useMemo.contentOffsetX,
    contentOffsetY = _useMemo.contentOffsetY,
    alignPadSingle = _useMemo.alignPadSingle;
  var padForAlign = alignPadSingle !== null && alignPadSingle !== void 0 ? alignPadSingle : 0;
  var initialPositionX = VIEWPORT_TOP_LEFT_MARGIN - padForAlign * zoomConfig.initialScale;
  var initialPositionY = VIEWPORT_TOP_LEFT_MARGIN - padForAlign * zoomConfig.initialScale;
  contentOffsetRef.current = {
    x: contentOffsetX,
    y: contentOffsetY
  };

  /** 避免用 content 尺寸当 key 导致拖拽时整表 remount；切换画布或由空到有图元时再对齐一次 */
  var initialAlignRef = useRef({
    frame: '',
    done: false
  });
  useEffect(function () {
    if (!isFloorMapView || frameResetKey === undefined) return;
    if (initialAlignRef.current.frame !== frameResetKey) {
      initialAlignRef.current = {
        frame: frameResetKey,
        done: false
      };
    }
    if (autoFitOnMount) {
      initialAlignRef.current.done = true;
      return;
    }
    if (alignPadSingle == null) {
      initialAlignRef.current.done = false;
      return;
    }
    if (initialAlignRef.current.done) return;
    var cancelled = false;
    var raf = 0;
    var tick = function tick() {
      if (cancelled) return;
      var ctx = transformRef.current;
      if (!ctx) {
        raf = requestAnimationFrame(tick);
        return;
      }
      ctx.setTransform(initialPositionX, initialPositionY, zoomConfig.initialScale);
      initialAlignRef.current.done = true;
    };
    raf = requestAnimationFrame(tick);
    return function () {
      cancelled = true;
      cancelAnimationFrame(raf);
    };
  }, [isFloorMapView, frameResetKey, alignPadSingle, initialPositionX, initialPositionY, zoomConfig.initialScale, transformRef, autoFitOnMount]);
  useEffect(function () {
    var el = containerRef.current;
    if (!el) return;
    var onFullscreenChange = function onFullscreenChange() {
      return setIsFullscreen(document.fullscreenElement === el);
    };
    document.addEventListener('fullscreenchange', onFullscreenChange);
    return function () {
      return document.removeEventListener('fullscreenchange', onFullscreenChange);
    };
  }, []);
  var toggleFullscreen = useCallback(function () {
    var el = containerRef.current;
    if (!el) return;
    if (document.fullscreenElement) {
      var _document$exitFullscr, _document;
      (_document$exitFullscr = (_document = document).exitFullscreen) === null || _document$exitFullscr === void 0 || _document$exitFullscr.call(_document);
    } else {
      var _el$requestFullscreen;
      (_el$requestFullscreen = el.requestFullscreen) === null || _el$requestFullscreen === void 0 || _el$requestFullscreen.call(el);
    }
  }, []);

  /** @returns 是否已调用 setTransform（用于首屏 autoFit：避免空跑仍标记 done） */
  var fitBounds = useCallback(function () {
    var _zoom$max3;
    var ctx = transformRef.current;
    var container = containerRef.current;
    if (!ctx || !container) return false;
    var wrapper = container.querySelector('.react-transform-wrapper');
    if (!wrapper) return false;
    var wrapperRect = wrapper.getBoundingClientRect();
    if (wrapperRect.width <= 0 || wrapperRect.height <= 0) return false;

    /**
     * 平面图像素模式：按「图元轴对齐包围盒」缩放并居中，不按整块 content（含编辑态撑满视口的空白）适配。
     * 画布 DOM 尺寸与网格空白不变，仅改变视口 transform；视口边可贴边（edgePx=0）。
     */
    var pixelBox = isFloorMapView && effectiveItemUnit === 'pixel' && items.length > 0 ? getPixelBoundingBox(items, cellSize) : null;
    if (pixelBox) {
      var _zoom$max2;
      var bw = Math.max(1, pixelBox.maxRight - pixelBox.minLeft);
      var bh = Math.max(1, pixelBox.maxBottom - pixelBox.minTop);
      var edgePx = 0;
      var availW = Math.max(1, wrapperRect.width - 2 * edgePx);
      var availH = Math.max(1, wrapperRect.height - 2 * edgePx);
      var _raw = Math.min(availW / bw, availH / bh);
      var _nextScale = Math.min(_raw, (_zoom$max2 = zoom.max) !== null && _zoom$max2 !== void 0 ? _zoom$max2 : 2);
      var ap = alignPadSingle !== null && alignPadSingle !== void 0 ? alignPadSingle : padSingle;
      var bboxCx = ap + bw / 2;
      var bboxCy = ap + bh / 2;
      var _x = wrapperRect.width / 2 - bboxCx * _nextScale;
      var _y = wrapperRect.height / 2 - bboxCy * _nextScale;
      ctx.setTransform(_x, _y, _nextScale);
      return true;
    }
    if (contentWidth <= 0 || contentHeight <= 0) return false;
    /** 非平面图或无图元：仍按整块 content 适配 */
    var raw = Math.min(wrapperRect.width / contentWidth, wrapperRect.height / contentHeight);
    var nextScale = Math.min(raw, (_zoom$max3 = zoom.max) !== null && _zoom$max3 !== void 0 ? _zoom$max3 : 2);
    var padA = alignPadSingle !== null && alignPadSingle !== void 0 ? alignPadSingle : 0;
    var x = VIEWPORT_TOP_LEFT_MARGIN - padA * nextScale;
    var y = VIEWPORT_TOP_LEFT_MARGIN - padA * nextScale;
    ctx.setTransform(x, y, nextScale);
    return true;
  }, [contentWidth, contentHeight, zoom.max, transformRef, alignPadSingle, isFloorMapView, effectiveItemUnit, items, cellSize, padSingle]);

  /**
   * autoFitOnMount：每个画布在「有图元且 content 尺寸已按包围盒算好」后执行一次 fitBounds。
   * 避免首帧 items 仍为空时用占位尺寸 fit 完并标记 done，导致异步图元加载后不再适配。
   */
  var autoFitOnceRef = useRef({
    frame: '',
    done: false
  });
  var prevItemsCountForAutoFitRef = useRef(null);
  /**
   * 首屏 auto fit：时序上易出现「Transform 未挂载 / wrapper 尺寸为 0 / 内容区尚未提交」，
   * 用 layoutEffect + 双 rAF 贴近浏览器布局完成时刻；仅 fitBounds 真正 setTransform 后才记 done；
   * viewportSize 纳入依赖以便父级 flex 迟到的尺寸更新后重试（超次不伪造 done）。
   */
  useLayoutEffect(function () {
    if (!isFloorMapView || !autoFitOnMount || frameResetKey === undefined) return;
    var frame = String(frameResetKey);
    if (autoFitOnceRef.current.frame !== frame) {
      autoFitOnceRef.current = {
        frame: frame,
        done: false
      };
      prevItemsCountForAutoFitRef.current = null;
    }
    var itemCount = items.length;
    var prevN = prevItemsCountForAutoFitRef.current;
    if (prevN !== null && prevN === 0 && itemCount > 0) {
      autoFitOnceRef.current.done = false;
    }
    prevItemsCountForAutoFitRef.current = itemCount;
    if (autoFitOnceRef.current.done) return;
    if (effectiveItemUnit === 'pixel' && itemCount === 0) {
      return;
    }
    if (contentWidth <= 0 || contentHeight <= 0) return;
    var cancelled = false;
    var raf = 0;
    var attempts = 0;
    var MAX_AUTO_FIT_ATTEMPTS = 160;
    var tick = function tick() {
      if (cancelled) return;
      if (attempts >= MAX_AUTO_FIT_ATTEMPTS) return;
      var ctx = transformRef.current;
      var container = containerRef.current;
      var wrapper = container === null || container === void 0 ? void 0 : container.querySelector('.react-transform-wrapper');
      if (!ctx || !wrapper) {
        attempts += 1;
        raf = requestAnimationFrame(tick);
        return;
      }
      var rect = wrapper.getBoundingClientRect();
      if (rect.width <= 0 || rect.height <= 0) {
        attempts += 1;
        raf = requestAnimationFrame(tick);
        return;
      }

      /** 再等两帧：react-zoom-pan-pinch 与 TransformComponent 常在本帧之后才把可测布局写稳 */
      raf = requestAnimationFrame(function () {
        if (cancelled) return;
        raf = requestAnimationFrame(function () {
          if (cancelled) return;
          var ok = fitBounds();
          if (ok) {
            autoFitOnceRef.current.done = true;
            return;
          }
          attempts += 1;
          if (attempts < MAX_AUTO_FIT_ATTEMPTS) {
            raf = requestAnimationFrame(tick);
          }
        });
      });
    };
    raf = requestAnimationFrame(tick);
    return function () {
      cancelled = true;
      cancelAnimationFrame(raf);
    };
  }, [isFloorMapView, autoFitOnMount, frameResetKey, effectiveItemUnit, items.length, contentWidth, contentHeight, viewportSize.width, viewportSize.height, mapAreaSize.width, mapAreaSize.height, fitBounds, transformRef]);
  var lastTransformRef = useRef({
    x: 0,
    y: 0,
    scale: 1
  });
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    isInteractingWithElement = _useState10[0],
    setIsInteractingWithElement = _useState10[1];
  var prevInteractingRef = useRef(false);
  useEffect(function () {
    if (isInteractingWithElement) {
      prevInteractingRef.current = true;
      return;
    }
    if (!prevInteractingRef.current) return;
    prevInteractingRef.current = false;
    var saved = lastTransformRef.current;
    var raf = requestAnimationFrame(function () {
      var _transformRef$current;
      (_transformRef$current = transformRef.current) === null || _transformRef$current === void 0 || _transformRef$current.setTransform(saved.x, saved.y, saved.scale);
    });
    return function () {
      return cancelAnimationFrame(raf);
    };
  }, [isInteractingWithElement, transformRef]);
  return {
    containerRef: containerRef,
    mapAreaRef: mapAreaRef,
    viewportSize: viewportSize,
    mapAreaSize: mapAreaSize,
    contentWidth: contentWidth,
    contentHeight: contentHeight,
    contentOffsetX: contentOffsetX,
    contentOffsetY: contentOffsetY,
    initialPositionX: initialPositionX,
    initialPositionY: initialPositionY,
    zoomConfig: zoomConfig,
    scale: scale,
    setScale: setScale,
    isFullscreen: isFullscreen,
    toggleFullscreen: toggleFullscreen,
    fitBounds: fitBounds,
    lastTransformRef: lastTransformRef,
    isInteractingWithElement: isInteractingWithElement,
    setIsInteractingWithElement: setIsInteractingWithElement
  };
}