'use strict';

var dayjs = require('dayjs');
var vue = require('vue');
var calendar = require('./calendar.js');
var calendarUtils = require('./calendar-utils.js');

"use strict";
const resolveExposedElement = (rawRef) => {
  if (!rawRef) {
    return null;
  }
  if (rawRef instanceof HTMLElement) {
    return rawRef;
  }
  const maybeRef = rawRef;
  return maybeRef.value instanceof HTMLElement ? maybeRef.value : null;
};
const createPointAnchorRect = (x, y) => ({
  left: x,
  right: x,
  top: y,
  bottom: y,
  width: 0,
  height: 0
});
const resolveAnchorRect = (anchor) => {
  if (!anchor) {
    return null;
  }
  if (anchor instanceof MouseEvent) {
    const anchorElement = anchor.currentTarget instanceof HTMLElement ? anchor.currentTarget : anchor.target instanceof HTMLElement ? anchor.target : null;
    if (anchorElement) {
      return anchorElement.getBoundingClientRect();
    }
    return createPointAnchorRect(anchor.clientX, anchor.clientY);
  }
  if (anchor instanceof HTMLElement) {
    return anchor.getBoundingClientRect();
  }
  const maybeRect = anchor;
  if (typeof maybeRect.left === "number" && typeof maybeRect.top === "number" && typeof maybeRect.right === "number" && typeof maybeRect.bottom === "number" && typeof maybeRect.width === "number" && typeof maybeRect.height === "number") {
    return {
      left: maybeRect.left,
      top: maybeRect.top,
      right: maybeRect.right,
      bottom: maybeRect.bottom,
      width: maybeRect.width,
      height: maybeRect.height
    };
  }
  const maybePoint = anchor;
  if (typeof maybePoint.x === "number" && typeof maybePoint.y === "number") {
    return createPointAnchorRect(maybePoint.x, maybePoint.y);
  }
  return null;
};
const useCalendarEditor = (options) => {
  const {
    props,
    emit,
    defaultEventTitle,
    slotStepMinutes,
    editableDisplayFields,
    internalEvents,
    currentEditableEvent,
    canQuickCreate,
    canSelectCreate,
    getEventIdentifier,
    commitEvents,
    patchEvent,
    canCreateAtRange,
    calendarContainerRef
  } = options;
  const editPanelRef = vue.ref(null);
  const editBoundaryStyle = vue.ref({
    position: "fixed",
    left: "-9999px",
    top: "-9999px",
    width: "0px",
    height: "0px",
    visibility: "hidden"
  });
  const syncEditBoundaryStyle = () => {
    const containerEl = calendarContainerRef?.value;
    if (!(containerEl instanceof HTMLElement)) {
      editBoundaryStyle.value = {
        ...editBoundaryStyle.value,
        left: "-9999px",
        top: "-9999px",
        width: "0px",
        height: "0px",
        visibility: "hidden"
      };
      return;
    }
    const rect = containerEl.getBoundingClientRect();
    editBoundaryStyle.value = {
      ...editBoundaryStyle.value,
      left: `${rect.left}px`,
      top: `${rect.top}px`,
      width: `${Math.max(rect.width, 0)}px`,
      height: `${Math.max(rect.height, 0)}px`,
      visibility: "hidden"
    };
  };
  const resolveBoundaryProxyRect = () => {
    const boundaryEl = resolveExposedElement(editPanelRef.value?.boundaryRef);
    if (boundaryEl instanceof HTMLElement) {
      const boundaryRect = boundaryEl.getBoundingClientRect();
      if (boundaryRect.width > 0 && boundaryRect.height > 0) {
        return boundaryRect;
      }
    }
    return {
      left: 0,
      top: 0,
      right: window.innerWidth,
      bottom: window.innerHeight,
      width: window.innerWidth,
      height: window.innerHeight
    };
  };
  const editPopoverOpen = vue.ref(false);
  const editPresentationMode = vue.ref("popover");
  const editPopoverPlacement = vue.ref("right");
  const editingEventIdentifier = vue.ref("");
  const editingDraftClassToken = vue.ref("");
  const newDraftEventIdRef = vue.ref("");
  const createDraftEventRef = vue.ref(null);
  const contextMenuPanelRef = vue.ref(null);
  const contextMenuOpen = vue.ref(false);
  const contextMenuEvent = vue.ref(null);
  const contextMenuStyle = vue.ref({
    position: "fixed",
    left: "-9999px",
    top: "-9999px",
    visibility: "hidden"
  });
  const editPopoverStyle = vue.ref({
    position: "absolute",
    left: "-9999px",
    top: "-9999px",
    visibility: "hidden"
  });
  const editFormData = vue.reactive({
    title: "",
    timeRange: []
  });
  const isCreatingEvent = vue.computed(() => Boolean(createDraftEventRef.value));
  const editingEventTitle = vue.computed(
    () => String(editFormData.title || "").trim() || defaultEventTitle
  );
  const isEditingTargetEvent = (event, identifier = editingEventIdentifier.value, draftToken = editingDraftClassToken.value) => {
    const matchedByIdentifier = Boolean(identifier) && getEventIdentifier(event) === identifier;
    const matchedByDraftToken = Boolean(draftToken) && calendarUtils.hasClassToken(event.class, draftToken);
    return matchedByIdentifier || matchedByDraftToken;
  };
  const resetEditFormData = () => {
    Object.keys(editFormData).forEach((key) => {
      delete editFormData[key];
    });
    editFormData.title = "";
    editFormData.timeRange = [];
  };
  const mergeEditFormData = (source) => {
    resetEditFormData();
    if (!source || typeof source !== "object") {
      return;
    }
    Object.keys(source).forEach((key) => {
      editFormData[key] = source[key];
    });
  };
  const applyEventTitle = (event, nextTitle) => {
    const sourceTitle = nextTitle ?? String(
      event.title || (props.eventTitleKey ? event[props.eventTitleKey] : "") || ""
    ).trim();
    const normalizedTitle = sourceTitle || defaultEventTitle;
    event.title = normalizedTitle;
    if (props.eventTitleKey && props.eventTitleKey !== "title") {
      event[props.eventTitleKey] = normalizedTitle;
    }
    return normalizedTitle;
  };
  const closeContextMenu = () => {
    contextMenuOpen.value = false;
    contextMenuEvent.value = null;
  };
  const openContextMenu = async (event, nativeEvent) => {
    syncEditBoundaryStyle();
    contextMenuEvent.value = event;
    contextMenuStyle.value = {
      ...contextMenuStyle.value,
      left: "-9999px",
      top: "-9999px",
      visibility: "hidden"
    };
    contextMenuOpen.value = true;
    await vue.nextTick();
    const menuEl = resolveExposedElement(contextMenuPanelRef.value?.menuRef);
    const boundaryRect = resolveBoundaryProxyRect();
    const margin = 12;
    const menuWidth = menuEl?.offsetWidth || 180;
    const menuHeight = menuEl?.offsetHeight || 88;
    const nextLeft = calendarUtils.clamp(
      nativeEvent.clientX,
      boundaryRect.left + margin,
      boundaryRect.right - menuWidth - margin
    );
    const nextTop = calendarUtils.clamp(
      nativeEvent.clientY,
      boundaryRect.top + margin,
      boundaryRect.bottom - menuHeight - margin
    );
    contextMenuStyle.value = {
      ...contextMenuStyle.value,
      left: `${nextLeft}px`,
      top: `${nextTop}px`,
      visibility: "visible"
    };
  };
  const openEditPopover = async (event, draftClassToken = "", anchor) => {
    if (props.readonly) {
      return;
    }
    closeContextMenu();
    editPresentationMode.value = "popover";
    const start = calendarUtils.toDateValue(event.start) || /* @__PURE__ */ new Date();
    const end = calendarUtils.toDateValue(event.end) || new Date(
      start.getTime() + Math.max(slotStepMinutes.value, 30) * 60 * 1e3
    );
    mergeEditFormData(event);
    editFormData.title = String(
      event.title || (props.eventTitleKey ? event[props.eventTitleKey] : "")
    ).trim() || defaultEventTitle;
    editFormData.timeRange = [dayjs(start), dayjs(end)];
    editableDisplayFields.value.forEach((field) => {
      editFormData[field.key] = event[field.key];
    });
    editingEventIdentifier.value = getEventIdentifier(event);
    editingDraftClassToken.value = draftClassToken;
    editPopoverStyle.value = {
      ...editPopoverStyle.value,
      position: "absolute",
      left: "-9999px",
      top: "-9999px",
      visibility: "hidden"
    };
    syncEditBoundaryStyle();
    editPopoverOpen.value = true;
    await vue.nextTick();
    let popupEl = resolveExposedElement(editPanelRef.value?.popoverRef);
    if (!popupEl && editPresentationMode.value === "popover") {
      await vue.nextTick();
      popupEl = resolveExposedElement(editPanelRef.value?.popoverRef);
    }
    if (!popupEl) {
      return;
    }
    const margin = 12;
    const gap = 10;
    const applyPosition = (resolvedAnchor) => {
      const currentPopupEl = resolveExposedElement(editPanelRef.value?.popoverRef);
      if (!currentPopupEl) {
        return;
      }
      const currentPopupRect = {
        width: currentPopupEl.offsetWidth,
        height: currentPopupEl.offsetHeight
      };
      const currentBoundaryRect = resolveBoundaryProxyRect();
      const clampLeft = (v) => calendarUtils.clamp(
        v,
        margin,
        currentBoundaryRect.width - currentPopupRect.width - margin
      );
      const clampTop = (v) => calendarUtils.clamp(
        v,
        margin,
        currentBoundaryRect.height - currentPopupRect.height - margin
      );
      const anchorRect = resolveAnchorRect(resolvedAnchor);
      const localAnchorRect = anchorRect ? {
        left: anchorRect.left - currentBoundaryRect.left,
        right: anchorRect.right - currentBoundaryRect.left,
        top: anchorRect.top - currentBoundaryRect.top,
        bottom: anchorRect.bottom - currentBoundaryRect.top,
        width: anchorRect.width,
        height: anchorRect.height
      } : null;
      let nextLeft = clampLeft(
        (currentBoundaryRect.width - currentPopupRect.width) / 2
      );
      let nextTop = clampTop(
        (currentBoundaryRect.height - currentPopupRect.height) / 2
      );
      let nextPlacement = "top";
      if (localAnchorRect) {
        const preferRight = currentBoundaryRect.width - localAnchorRect.right >= localAnchorRect.left;
        const preferBottom = currentBoundaryRect.height - localAnchorRect.bottom >= localAnchorRect.top;
        const placements = [
          preferRight ? "right" : "left",
          preferRight ? "left" : "right",
          preferBottom ? "bottom" : "top",
          preferBottom ? "top" : "bottom"
        ];
        const candidates = placements.map((placement) => {
          let rawLeft = 0;
          let rawTop = 0;
          if (placement === "right") {
            rawLeft = localAnchorRect.right + gap;
            rawTop = localAnchorRect.top + (localAnchorRect.height - currentPopupRect.height) / 2;
          } else if (placement === "left") {
            rawLeft = localAnchorRect.left - currentPopupRect.width - gap;
            rawTop = localAnchorRect.top + (localAnchorRect.height - currentPopupRect.height) / 2;
          } else if (placement === "bottom") {
            rawLeft = localAnchorRect.left + (localAnchorRect.width - currentPopupRect.width) / 2;
            rawTop = localAnchorRect.bottom + gap;
          } else {
            rawLeft = localAnchorRect.left + (localAnchorRect.width - currentPopupRect.width) / 2;
            rawTop = localAnchorRect.top - currentPopupRect.height - gap;
          }
          const overflow = Math.max(0, margin - rawLeft) + Math.max(
            0,
            rawLeft + currentPopupRect.width - (currentBoundaryRect.width - margin)
          ) + Math.max(0, margin - rawTop) + Math.max(
            0,
            rawTop + currentPopupRect.height - (currentBoundaryRect.height - margin)
          );
          return {
            placement,
            left: clampLeft(rawLeft),
            top: clampTop(rawTop),
            overflow
          };
        });
        const bestCandidate = candidates.find((c) => c.overflow === 0) || candidates.reduce(
          (best, c) => c.overflow < best.overflow ? c : best
        );
        nextLeft = bestCandidate.left;
        nextTop = bestCandidate.top;
        nextPlacement = bestCandidate.placement;
      }
      editPopoverPlacement.value = nextPlacement;
      editPopoverStyle.value = {
        ...editPopoverStyle.value,
        position: "absolute",
        left: `${nextLeft}px`,
        top: `${nextTop}px`,
        visibility: "visible"
      };
    };
    const findDraftAnchorEl = () => {
      const container = calendarContainerRef?.value;
      if (!container || !draftClassToken) return void 0;
      return container.querySelector(".is-new") ?? container.querySelector(`.${draftClassToken}`) ?? void 0;
    };
    const immediateAnchor = anchor || findDraftAnchorEl();
    if (immediateAnchor || !draftClassToken) {
      applyPosition(immediateAnchor);
    } else if (calendarContainerRef?.value) {
      const container = calendarContainerRef.value;
      const snapshotToken = draftClassToken;
      setTimeout(() => {
        if (!editPopoverOpen.value || editingDraftClassToken.value !== snapshotToken) {
          return;
        }
        const draftEl = container.querySelector(".is-new") ?? container.querySelector(`.${snapshotToken}`) ?? void 0;
        applyPosition(draftEl);
      }, 500);
    }
  };
  const clearEditingDraftToken = () => {
    const token = editingDraftClassToken.value;
    const identifier = editingEventIdentifier.value;
    if (!token || !identifier) {
      return;
    }
    const nextEvents = internalEvents.value.map((event) => {
      if (getEventIdentifier(event) !== identifier) {
        return event;
      }
      return {
        ...event,
        class: calendarUtils.stripClassName(event.class, token)
      };
    });
    commitEvents(nextEvents);
    editingDraftClassToken.value = "";
  };
  const closeEditPopover = () => {
    editingEventIdentifier.value = "";
    editingDraftClassToken.value = "";
    newDraftEventIdRef.value = "";
    createDraftEventRef.value = null;
    closeContextMenu();
    editPopoverOpen.value = false;
  };
  const openCreateEventDrawer = (baseEvent) => {
    if (props.readonly) {
      return;
    }
    if (!canQuickCreate.value) {
      return;
    }
    const now = /* @__PURE__ */ new Date();
    const start = calendarUtils.toDateValue(baseEvent?.start) || now;
    const end = calendarUtils.toDateValue(baseEvent?.end) || new Date(
      start.getTime() + Math.max(slotStepMinutes.value, 30) * 60 * 1e3
    );
    if (!canCreateAtRange(start, end)) {
      return;
    }
    mergeEditFormData(baseEvent);
    editFormData.title = String(baseEvent?.title || baseEvent?.[props.eventTitleKey] || "").trim() || defaultEventTitle;
    editFormData.timeRange = [dayjs(start), dayjs(end)];
    editableDisplayFields.value.forEach((field) => {
      editFormData[field.key] = baseEvent?.[field.key];
    });
    createDraftEventRef.value = {
      ...baseEvent,
      start,
      end,
      split: baseEvent?.split,
      class: baseEvent?.class
    };
    editingEventIdentifier.value = "";
    editingDraftClassToken.value = "";
    newDraftEventIdRef.value = String(createDraftEventRef.value?.id ?? "");
    editPresentationMode.value = "drawer";
    editPopoverOpen.value = true;
  };
  const handleSwitchPresentation = () => {
    editPresentationMode.value = editPresentationMode.value === "popover" ? "drawer" : "popover";
    if (editPresentationMode.value === "popover") {
      const currentEvent = internalEvents.value.find(
        (event) => isEditingTargetEvent(event)
      );
      if (currentEvent) {
        openEditPopover(currentEvent, editingDraftClassToken.value);
      }
    }
  };
  const removeEventWithMatcher = (matcher) => {
    if (props.readonly) {
      return false;
    }
    if (currentEditableEvent.value.delete === false) {
      return false;
    }
    let deletedEvent;
    const nextEvents = internalEvents.value.filter((event) => {
      const matched = matcher(event);
      if (matched && !deletedEvent) {
        deletedEvent = calendar.normalizeCalendarEvent(event);
      }
      return !matched;
    });
    if (!deletedEvent) {
      return false;
    }
    commitEvents(nextEvents);
    emit("event-delete", {
      raw: {
        event: deletedEvent
      },
      event: deletedEvent,
      events: calendar.normalizeCalendarEvents(nextEvents)
    });
    return true;
  };
  const deleteEvent = (target) => {
    if (props.readonly) {
      return false;
    }
    if (!target) {
      return false;
    }
    const identifier = getEventIdentifier(target);
    if (!identifier) {
      return false;
    }
    return removeEventWithMatcher(
      (event) => getEventIdentifier(event) === identifier
    );
  };
  const copyEvent = (target) => {
    if (props.readonly) {
      return false;
    }
    if (!target) {
      return false;
    }
    const identifier = getEventIdentifier(target);
    const sourceEvent = internalEvents.value.find(
      (event) => getEventIdentifier(event) === identifier
    ) || target;
    const sourceStart = calendarUtils.toDateValue(sourceEvent.start);
    if (!sourceStart || Number.isNaN(sourceStart.getTime())) {
      return false;
    }
    const sourceEnd = calendarUtils.toDateValue(sourceEvent.end) || new Date(
      sourceStart.getTime() + Math.max(slotStepMinutes.value, 30) * 60 * 1e3
    );
    const shiftMs = 60 * 60 * 1e3;
    const clonedEvent = {
      ...sourceEvent,
      id: `event-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
      _eid: void 0,
      class: calendarUtils.stripClassName(sourceEvent.class, editingDraftClassToken.value),
      start: new Date(sourceStart.getTime() + shiftMs),
      end: new Date(sourceEnd.getTime() + shiftMs)
    };
    const nextEvents = [...internalEvents.value, clonedEvent];
    const normalizedClonedEvent = calendar.normalizeCalendarEvent(clonedEvent);
    commitEvents(nextEvents);
    emit("event-edit", {
      raw: {
        event: normalizedClonedEvent,
        originalEvent: calendar.normalizeCalendarEvent(sourceEvent),
        isCreate: true
      },
      event: normalizedClonedEvent,
      events: calendar.normalizeCalendarEvents(nextEvents)
    });
    return true;
  };
  const handleDeleteEditEvent = () => {
    if (props.readonly) {
      return;
    }
    const removed = removeEventWithMatcher((event) => isEditingTargetEvent(event));
    if (!removed) {
      closeEditPopover();
      return;
    }
    closeEditPopover();
  };
  const handleMaskClose = () => {
    if (calendarUtils.hasActiveTextSelection()) {
      window.getSelection?.()?.removeAllRanges();
      return;
    }
    handleConfirmEdit();
  };
  const handleConfirmEdit = () => {
    if (props.readonly) {
      closeEditPopover();
      return;
    }
    if (!editPopoverOpen.value) {
      return;
    }
    const identifier = editingEventIdentifier.value;
    const draftToken = editingDraftClassToken.value;
    const [rangeStart, rangeEnd] = Array.isArray(editFormData.timeRange) ? editFormData.timeRange : [];
    const nextStart = calendarUtils.toEditDate(rangeStart);
    const nextEnd = calendarUtils.toEditDate(rangeEnd);
    const nextTitle = String(editFormData.title || "").trim() || defaultEventTitle;
    if (createDraftEventRef.value) {
      const baseEvent = createDraftEventRef.value;
      const createdEvent = {
        ...baseEvent,
        id: baseEvent.id ?? `event-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
        title: nextTitle,
        start: nextStart || calendarUtils.toDateValue(baseEvent.start) || /* @__PURE__ */ new Date(),
        end: nextEnd || calendarUtils.toDateValue(baseEvent.end) || new Date(
          (nextStart || calendarUtils.toDateValue(baseEvent.start) || /* @__PURE__ */ new Date()).getTime() + Math.max(slotStepMinutes.value, 30) * 60 * 1e3
        )
      };
      if (!canCreateAtRange(createdEvent.start, createdEvent.end)) {
        return;
      }
      applyEventTitle(createdEvent, nextTitle);
      editableDisplayFields.value.forEach((field) => {
        createdEvent[field.key] = editFormData[field.key];
      });
      const nextEvents2 = [...internalEvents.value, createdEvent];
      const normalizedCreatedEvent = calendar.normalizeCalendarEvent(
        nextEvents2.find((e) => getEventIdentifier(e) === getEventIdentifier(createdEvent)) ?? createdEvent
      );
      commitEvents(nextEvents2);
      emit("event-edit", {
        raw: {
          event: normalizedCreatedEvent,
          isCreate: true
        },
        event: normalizedCreatedEvent,
        events: calendar.normalizeCalendarEvents(nextEvents2)
      });
      closeEditPopover();
      return;
    }
    if (!identifier && !draftToken) {
      closeEditPopover();
      return;
    }
    let hasMatchedTarget = false;
    let originalTargetEvent;
    let editedTargetEvent;
    const nextEvents = internalEvents.value.map((event) => {
      if (!isEditingTargetEvent(event, identifier, draftToken)) {
        return event;
      }
      hasMatchedTarget = true;
      if (!originalTargetEvent) {
        originalTargetEvent = calendar.normalizeCalendarEvent(event);
      }
      const nextEvent = {
        ...event,
        title: nextTitle,
        class: calendarUtils.stripClassName(event.class, editingDraftClassToken.value)
      };
      applyEventTitle(nextEvent, nextTitle);
      if (nextStart) {
        nextEvent.start = nextStart;
      }
      if (nextEnd) {
        nextEvent.end = nextEnd;
      }
      editableDisplayFields.value.forEach((field) => {
        nextEvent[field.key] = editFormData[field.key];
      });
      if (!editedTargetEvent) {
        editedTargetEvent = calendar.normalizeCalendarEvent(nextEvent);
      }
      return nextEvent;
    });
    if (!hasMatchedTarget) {
      closeEditPopover();
      return;
    }
    commitEvents(nextEvents);
    if (editedTargetEvent) {
      emit("event-edit", {
        raw: {
          event: editedTargetEvent,
          originalEvent: originalTargetEvent,
          isCreate: false
        },
        event: editedTargetEvent,
        events: calendar.normalizeCalendarEvents(nextEvents)
      });
    }
    closeEditPopover();
  };
  const handleConfirmAndAdd = () => {
    if (!isCreatingEvent.value) {
      handleConfirmEdit();
      return;
    }
    const [rangeStart, rangeEnd] = Array.isArray(editFormData.timeRange) ? editFormData.timeRange : [];
    const nextStart = calendarUtils.toEditDate(rangeStart);
    const nextEnd = calendarUtils.toEditDate(rangeEnd);
    const split = createDraftEventRef.value?.split;
    handleConfirmEdit();
    openCreateEventDrawer({
      start: nextStart || void 0,
      end: nextEnd || void 0,
      split
    });
  };
  const createDraftEventAndOpenEditor = (baseEvent, fallbackSplit) => {
    if (props.readonly) {
      return;
    }
    if (!props.selectable) {
      return;
    }
    const start = calendarUtils.toDateValue(baseEvent.start) || /* @__PURE__ */ new Date();
    const end = calendarUtils.toDateValue(baseEvent.end) || new Date(
      start.getTime() + Math.max(slotStepMinutes.value, 30) * 60 * 1e3
    );
    const isMonthViewEvent = start.getHours() === 0 && start.getMinutes() === 0 && start.getSeconds() === 0 && end.getHours() === 0 && end.getMinutes() === 0 && end.getSeconds() === 0;
    if (props.disableCreateInPast) {
      if (isMonthViewEvent) {
        const today = /* @__PURE__ */ new Date();
        today.setHours(0, 0, 0, 0);
        if (start.getTime() < today.getTime()) {
          return;
        }
      } else if (!canCreateAtRange(start, end)) {
        return;
      }
    }
    const draftClassToken = calendarUtils.createDraftClassToken();
    const baseTitle = applyEventTitle(baseEvent);
    const cleanBaseEvent = { ...baseEvent };
    delete cleanBaseEvent._;
    delete cleanBaseEvent.style;
    delete cleanBaseEvent.startMinutes;
    delete cleanBaseEvent.endMinutes;
    const draftEvent = {
      ...cleanBaseEvent,
      id: cleanBaseEvent.id ?? `event-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
      title: baseTitle,
      start,
      end,
      split: cleanBaseEvent.split ?? fallbackSplit,
      class: calendarUtils.mergeClassName(cleanBaseEvent.class, draftClassToken)
    };
    applyEventTitle(draftEvent, baseTitle);
    newDraftEventIdRef.value = String(draftEvent.id ?? "");
    if (editPopoverOpen.value) {
      clearEditingDraftToken();
      closeEditPopover();
    }
    const nextEvents = patchEvent(draftEvent, baseEvent);
    commitEvents(nextEvents);
    emit("select", {
      raw: {
        start,
        end,
        split: draftEvent.split
      },
      // 对外暴露的事件数据中去掉内部实现类（draftClassToken），避免污染外部消费者数据
      events: calendar.normalizeCalendarEvents(
        nextEvents.map((e) => ({
          ...e,
          class: calendarUtils.stripClassName(e.class, draftClassToken)
        }))
      )
    });
    openEditPopover(draftEvent, draftClassToken);
  };
  const resolveCreatedEventFromPayload = (payload) => {
    const candidate = payload?.event && typeof payload.event === "object" ? payload.event : payload;
    if (!candidate || typeof candidate !== "object") {
      return void 0;
    }
    return candidate;
  };
  const removeCreatedDraftEvent = (event) => {
    if (!event) {
      return;
    }
    if (typeof event.delete === "function") {
      event.delete(3);
    }
    const removeTask = () => {
      const targetIdentifier = getEventIdentifier(event);
      const targetStart = calendarUtils.toDateValue(event.start)?.getTime();
      const targetEnd = calendarUtils.toDateValue(event.end)?.getTime();
      let removed = false;
      const nextEvents = internalEvents.value.filter((item) => {
        const matchedByIdentifier = Boolean(targetIdentifier) && getEventIdentifier(item) === targetIdentifier;
        const itemStart = calendarUtils.toDateValue(item.start)?.getTime();
        const itemEnd = calendarUtils.toDateValue(item.end)?.getTime();
        const matchedByExactTime = calendarUtils.normalizeDateLikeValue(item.start) === calendarUtils.normalizeDateLikeValue(event.start) && calendarUtils.normalizeDateLikeValue(item.end) === calendarUtils.normalizeDateLikeValue(event.end);
        const matchedByNearTime = targetStart !== void 0 && itemStart !== void 0 && Math.abs(itemStart - targetStart) <= 60 * 1e3 && (targetEnd !== void 0 && itemEnd !== void 0 && Math.abs(itemEnd - targetEnd) <= 60 * 1e3 || targetEnd === void 0 && itemEnd === void 0);
        const matched = matchedByIdentifier || matchedByExactTime || matchedByNearTime;
        if (matched) {
          removed = true;
        }
        return !matched;
      });
      if (removed) {
        commitEvents(nextEvents);
      }
    };
    removeTask();
    void vue.nextTick(() => {
      requestAnimationFrame(() => {
        removeTask();
      });
    });
  };
  const handleEventDragCreate = (payload) => {
    if (props.readonly) {
      return;
    }
    const event = resolveCreatedEventFromPayload(payload);
    if (!event) {
      return;
    }
    if (!canSelectCreate.value) {
      removeCreatedDraftEvent(event);
      return;
    }
    if (!canCreateAtRange(event.start, event.end)) {
      removeCreatedDraftEvent(event);
      return;
    }
    createDraftEventAndOpenEditor(event, event.split);
  };
  return {
    editPanelRef,
    editPopoverOpen,
    editPresentationMode,
    editPopoverPlacement,
    createDraftEventRef,
    contextMenuPanelRef,
    contextMenuOpen,
    contextMenuEvent,
    contextMenuStyle,
    editPopoverStyle,
    editBoundaryStyle,
    editFormData,
    isCreatingEvent,
    editingEventTitle,
    applyEventTitle,
    closeContextMenu,
    openContextMenu,
    openEditPopover,
    newDraftEventIdRef,
    clearEditingDraftToken,
    closeEditPopover,
    openCreateEventDrawer,
    handleSwitchPresentation,
    deleteEvent,
    copyEvent,
    handleDeleteEditEvent,
    handleMaskClose,
    handleConfirmEdit,
    handleConfirmAndAdd,
    createDraftEventAndOpenEditor,
    resolveCreatedEventFromPayload,
    removeCreatedDraftEvent,
    handleEventDragCreate
  };
};

exports.useCalendarEditor = useCalendarEditor;
//# sourceMappingURL=use-calendar-editor.js.map
