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 { useCallback, useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';
/**
 * 顶栏「跟随当前时间」：在每自然分钟整点（*: * :00）对齐日程，`at` 使用当前分钟的 `startOf('minute')`，
 * 并通过 flushCommittedSchedule 触发防抖链。
 *
 * @param wallClockFollowLocked 为 true 时（如大屏锁定 resourceWall）：定时器始终运行，且不可通过交互关闭跟随。
 */
export function useReservationWallClockFollow(scheduleValueProp, setInternalSchedule, flushCommittedSchedule, onScheduleChange) {
  var wallClockFollowLocked = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  var _useState = useState(true),
    _useState2 = _slicedToArray(_useState, 2),
    followWallClock = _useState2[0],
    setFollowWallClockInternal = _useState2[1];
  var onScheduleChangeRef = useRef(onScheduleChange);
  /** 避免 effect 依赖整个 `scheduleValueProp` 引用：父级每次 render 新对象会误重置定时器并多次首帧 tick */
  var scheduleValuePropRef = useRef(scheduleValueProp);
  scheduleValuePropRef.current = scheduleValueProp;
  var scheduleControlled = scheduleValueProp !== undefined;
  var followWallClockEffective = wallClockFollowLocked || followWallClock;

  /** 锁定模式下始终保持内部开关为 true，避免闭包里读到 false */
  useEffect(function () {
    if (wallClockFollowLocked) setFollowWallClockInternal(true);
  }, [wallClockFollowLocked]);
  useEffect(function () {
    onScheduleChangeRef.current = onScheduleChange;
  });
  useEffect(function () {
    if (!followWallClockEffective) return;
    var timeoutId = null;
    var cancelled = false;

    /** 距下一自然分钟整点的毫秒数（下一分钟的 :00.000） */
    var msUntilNextMinuteBoundary = function msUntilNextMinuteBoundary() {
      var now = dayjs();
      return Math.max(0, now.startOf('minute').add(1, 'minute').diff(now));
    };
    var tick = function tick() {
      var _onScheduleChangeRef$;
      var now = dayjs().startOf('minute');
      var next = {
        date: now.startOf('day'),
        at: now
      };
      if (scheduleValuePropRef.current === undefined) {
        setInternalSchedule(next);
      }
      (_onScheduleChangeRef$ = onScheduleChangeRef.current) === null || _onScheduleChangeRef$ === void 0 || _onScheduleChangeRef$.call(onScheduleChangeRef, next);
      /** 跟随当前：立即提交日程，patch / 外部 onSearch 由 debouncedSchedule effect 统一处理 */
      flushCommittedSchedule(next);
    };
    var scheduleNextBoundary = function scheduleNextBoundary() {
      if (cancelled) return;
      timeoutId = window.setTimeout(function () {
        if (cancelled) return;
        tick();
        scheduleNextBoundary();
      }, msUntilNextMinuteBoundary());
    };

    /** 首帧：立刻对齐到当前整分；之后仅在每分钟 rollover 时再 tick */
    tick();
    scheduleNextBoundary();
    return function () {
      cancelled = true;
      if (timeoutId != null) window.clearTimeout(timeoutId);
    };
    // setInternalSchedule 为 schedule hook 的 setState，引用稳定；不把 scheduleValueProp 放进 deps（见 ref）
    // eslint-disable-next-line react-hooks/exhaustive-deps -- scheduleControlled：仅受控/非受控切换时重启定时器
  }, [followWallClockEffective, flushCommittedSchedule, scheduleControlled]);
  var setFollowWallClock = useCallback(function (value) {
    if (wallClockFollowLocked) return;
    setFollowWallClockInternal(value);
  }, [wallClockFollowLocked]);
  var onFollowWallClockToggle = useCallback(function () {
    if (wallClockFollowLocked) return;
    setFollowWallClockInternal(function (v) {
      return !v;
    });
  }, [wallClockFollowLocked]);
  var onTimeNavigatorUserInteraction = useCallback(function () {
    if (wallClockFollowLocked) return;
    setFollowWallClockInternal(false);
  }, [wallClockFollowLocked]);
  return {
    followWallClock: followWallClockEffective,
    setFollowWallClock: setFollowWallClock,
    onFollowWallClockToggle: onFollowWallClockToggle,
    onTimeNavigatorUserInteraction: onTimeNavigatorUserInteraction
  };
}