var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/salesSdk/adjustTime/hooks/useAdjustTimeModalController.ts
var useAdjustTimeModalController_exports = {};
__export(useAdjustTimeModalController_exports, {
  useAdjustTimeModalController: () => useAdjustTimeModalController
});
module.exports = __toCommonJS(useAdjustTimeModalController_exports);
var import_react = require("react");
var import_utils = require("@pisell/utils");
var import_time = require("../utils/time");
var import_useSalesSdk = require("../../hooks/useSalesSdk");
var import_ahooks = require("ahooks");
var import_preferences = require("../utils/preferences");
var t = (key) => import_utils.locales.getText(key);
var DEBUG_SHOP_CLOSING_EVENT = "pisell-adjust-time-shop-closing-time";
var createUnavailablePricing = (targetMinutes) => ({
  available: false,
  unavailableReason: "NO_COVERAGE",
  targetMinutes: Math.max(0, Math.ceil(Number(targetMinutes) || 0)),
  coveredMinutes: 0,
  totalPrice: 0,
  lines: []
});
var isProductAction = (action) => action.startsWith("product:");
var resolveDefaultManualEndDate = (bookingEnd, current) => {
  return bookingEnd.getTime() > current.getTime() ? bookingEnd : current;
};
var getManualDefaultEndTime = (bookingEnd, current) => {
  return (0, import_time.formatTime)(resolveDefaultManualEndDate(bookingEnd, current));
};
var normalizeShopClosingTime = (time) => {
  if (typeof time !== "string") return void 0;
  const trimmed = time.trim();
  const match = /^(\d{1,2}):(\d{2})$/.exec(trimmed);
  if (!match) return void 0;
  const hours = Number(match[1]);
  const minutes = Number(match[2]);
  if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return void 0;
  return `${`${hours}`.padStart(2, "0")}:${`${minutes}`.padStart(2, "0")}`;
};
var resolveManualEndDateByClock = (referenceDate, bookingEnd, timeStr) => {
  const candidate = (0, import_time.applyTimeToDate)(referenceDate, timeStr);
  return candidate.getTime() < bookingEnd.getTime() ? (0, import_time.addMinutes)(candidate, 24 * 60) : candidate;
};
var resolveOptionalDate = (value) => {
  if (!value) return void 0;
  const date = value instanceof Date ? value : new Date(value);
  return Number.isNaN(date.getTime()) ? void 0 : date;
};
var clampToBusinessEnd = (date, businessEnd) => {
  return date.getTime() > businessEnd.getTime() ? businessEnd : date;
};
var isSameLocalDate = (left, right) => left.getFullYear() === right.getFullYear() && left.getMonth() === right.getMonth() && left.getDate() === right.getDate();
var resolveAdjustTimeContext = ({
  current,
  start,
  end,
  resourceEndTime,
  shopClosingTime
}) => {
  const businessEnd = (0, import_time.resolveFlexibleBusinessEnd)(start, resourceEndTime, shopClosingTime);
  return {
    current,
    start,
    end,
    businessEnd,
    resourceEndDate: resolveOptionalDate(resourceEndTime),
    isFutureBooking: start.getTime() > current.getTime(),
    hasBusinessEndConflict: end.getTime() > businessEnd.getTime()
  };
};
var resolveAdjustTimePolicy = (context, bookingDuration) => {
  const { current, start, end, businessEnd, resourceEndDate, isFutureBooking, hasBusinessEndConflict } = context;
  const isCurrentBookingDay = isSameLocalDate(end, current);
  const configuredDuration = Number(bookingDuration);
  const restartDuration = Number.isFinite(configuredDuration) && configuredDuration > 0 ? configuredDuration : (0, import_time.minutesBetween)(start, end);
  const canRestart = isCurrentBookingDay && current.getTime() >= start.getTime() && current.getTime() < businessEnd.getTime();
  const restartUncappedEnd = canRestart ? (0, import_time.addMinutes)(current, restartDuration) : end;
  const restartEnd = canRestart ? clampToBusinessEnd(restartUncappedEnd, businessEnd) : end;
  return {
    start,
    end,
    businessEnd,
    resourceEndDate,
    hasBusinessEndConflict,
    addTimeStart: start,
    addTimeBaseEnd: end,
    addTimeEndLimit: businessEnd,
    manualReferenceDate: end,
    manualDefaultEndDate: resolveDefaultManualEndDate(end, current),
    canProductAddTime: isCurrentBookingDay || isFutureBooking,
    canManualAddTime: isCurrentBookingDay || isFutureBooking,
    canPayOvertime: isCurrentBookingDay && current.getTime() > end.getTime(),
    canRestart,
    payOvertimeEnd: isCurrentBookingDay && current.getTime() > end.getTime() ? current : end,
    restartStart: canRestart ? current : start,
    restartEnd,
    restartUncappedEnd
  };
};
var resolveBusinessConflictScenario = (activeAction, start, end, products) => {
  const productId = isProductAction(activeAction) ? activeAction.slice("product:".length) : void 0;
  const product = productId ? products.find((item) => String(item.id) === productId) : void 0;
  const title = activeAction === "restart" ? t("pisell2.adjust-time.restart") : (product == null ? void 0 : product.title) || t("pisell2.adjust-time.pay-overtime");
  const subtitle = activeAction === "restart" ? t("pisell2.adjust-time.restart-subtitle") : isProductAction(activeAction) ? t("pisell2.adjust-time.product-subtitle") : t("pisell2.adjust-time.pay-overtime-subtitle");
  const icon = activeAction === "restart" ? "⟳" : (product == null ? void 0 : product.unlimited) ? "Day" : product ? `${Number(product.minMinutes || 0)}m` : "◷";
  return {
    title,
    subtitle,
    icon,
    newStart: start,
    newEnd: end,
    uncappedNewEnd: end,
    targetMinutes: 0,
    selectedProductId: product == null ? void 0 : product.id,
    unlimited: product == null ? void 0 : product.unlimited,
    valid: false
  };
};
var buildAdjustTimeScenario = ({
  activeAction,
  manualEndDate,
  policy,
  products
}) => {
  const {
    start,
    end,
    addTimeStart,
    addTimeBaseEnd,
    addTimeEndLimit,
    hasBusinessEndConflict
  } = policy;
  if (activeAction !== "manualDuration" && hasBusinessEndConflict) {
    return resolveBusinessConflictScenario(activeAction, start, end, products);
  }
  if (activeAction === "restart") {
    return {
      title: t("pisell2.adjust-time.restart"),
      subtitle: t("pisell2.adjust-time.restart-subtitle"),
      icon: "⟳",
      newStart: policy.restartStart,
      newEnd: policy.restartEnd,
      uncappedNewEnd: policy.restartUncappedEnd,
      effectiveEndLimit: addTimeEndLimit,
      targetMinutes: policy.canRestart ? (0, import_time.minutesBetween)(policy.restartStart, policy.restartEnd) : 0,
      valid: policy.canRestart && policy.restartEnd.getTime() > policy.restartStart.getTime()
    };
  }
  if (activeAction === "manualDuration") {
    const targetMinutes2 = (0, import_time.minutesBetween)(addTimeBaseEnd, manualEndDate);
    return {
      title: t("pisell2.adjust-time.manual-add-time"),
      subtitle: t("pisell2.adjust-time.manual-subtitle"),
      icon: "⌁",
      newStart: addTimeStart,
      newEnd: manualEndDate,
      uncappedNewEnd: manualEndDate,
      targetMinutes: targetMinutes2,
      valid: policy.canManualAddTime && targetMinutes2 > 0
    };
  }
  if (isProductAction(activeAction)) {
    const productId = activeAction.slice("product:".length);
    const product = products.find((item) => String(item.id) === productId);
    if (product == null ? void 0 : product.unlimited) {
      const newEnd3 = addTimeEndLimit;
      const targetMinutes3 = (0, import_time.minutesBetween)(addTimeBaseEnd, newEnd3);
      return {
        title: product.title || t("pisell2.adjust-time.add-time-fallback"),
        subtitle: t("pisell2.adjust-time.unlimited-subtitle"),
        icon: "Day",
        newStart: addTimeStart,
        newEnd: newEnd3,
        uncappedNewEnd: newEnd3,
        effectiveEndLimit: addTimeEndLimit,
        targetMinutes: targetMinutes3,
        selectedProductId: product.id,
        unlimited: true,
        valid: policy.canProductAddTime && targetMinutes3 > 0
      };
    }
    const targetMinutes2 = Number((product == null ? void 0 : product.minMinutes) || 0);
    const uncappedNewEnd2 = (0, import_time.addMinutes)(addTimeBaseEnd, targetMinutes2);
    const newEnd2 = clampToBusinessEnd(uncappedNewEnd2, addTimeEndLimit);
    return {
      title: (product == null ? void 0 : product.title) || t("pisell2.adjust-time.add-time-fallback"),
      subtitle: t("pisell2.adjust-time.product-subtitle"),
      icon: `${targetMinutes2}m`,
      newStart: addTimeStart,
      newEnd: newEnd2,
      uncappedNewEnd: uncappedNewEnd2,
      effectiveEndLimit: addTimeEndLimit,
      targetMinutes: targetMinutes2,
      selectedProductId: product == null ? void 0 : product.id,
      valid: policy.canProductAddTime && Boolean(product) && targetMinutes2 > 0 && newEnd2.getTime() > addTimeBaseEnd.getTime()
    };
  }
  const targetMinutes = (0, import_time.minutesBetween)(addTimeBaseEnd, policy.payOvertimeEnd);
  const uncappedNewEnd = policy.payOvertimeEnd;
  const newEnd = clampToBusinessEnd(uncappedNewEnd, addTimeEndLimit);
  return {
    title: t("pisell2.adjust-time.pay-overtime"),
    subtitle: t("pisell2.adjust-time.pay-overtime-subtitle"),
    icon: "◷",
    newStart: addTimeStart,
    newEnd,
    uncappedNewEnd,
    effectiveEndLimit: addTimeEndLimit,
    targetMinutes,
    valid: policy.canPayOvertime && newEnd.getTime() > addTimeBaseEnd.getTime()
  };
};
var resolveAutoPricing = ({
  activeAction,
  products,
  scenario,
  resolveBestAddTimePlan
}) => {
  if (!scenario.valid) {
    return createUnavailablePricing(scenario.targetMinutes);
  }
  if (activeAction === "restart") {
    return {
      available: true,
      targetMinutes: scenario.targetMinutes,
      coveredMinutes: 0,
      totalPrice: 0,
      lines: []
    };
  }
  if (isProductAction(activeAction) && scenario.selectedProductId != null) {
    const product = products.find((item) => item.id === scenario.selectedProductId);
    if (product) {
      if (product.unlimited && scenario.targetMinutes <= 0) {
        return createUnavailablePricing(0);
      }
      return {
        available: true,
        targetMinutes: scenario.targetMinutes,
        coveredMinutes: scenario.targetMinutes,
        totalPrice: product.price,
        lines: [
          {
            product_id: product.id,
            product_title: product.title,
            product_add_schedule_time: scenario.targetMinutes,
            num: 1,
            price: product.price,
            _originalProduct: product
          }
        ]
      };
    }
  }
  try {
    return (resolveBestAddTimePlan == null ? void 0 : resolveBestAddTimePlan(products, scenario.targetMinutes)) ?? createUnavailablePricing(scenario.targetMinutes);
  } catch (error) {
    console.warn("[AdjustTime] resolve best add time plan failed", error);
    return createUnavailablePricing(scenario.targetMinutes);
  }
};
var resolvePricedNewEnd = (activeAction, bookingEnd, scenario, autoPricing) => {
  if (activeAction === "restart" || activeAction === "manualDuration" || !autoPricing.available) {
    return scenario.newEnd;
  }
  const pricedEnd = (0, import_time.addMinutes)(bookingEnd, autoPricing.coveredMinutes);
  return scenario.effectiveEndLimit ? clampToBusinessEnd(pricedEnd, scenario.effectiveEndLimit) : pricedEnd;
};
var resolveUncappedPricedNewEnd = (activeAction, bookingEnd, scenario, autoPricing) => {
  if (activeAction === "restart" || activeAction === "manualDuration" || !autoPricing.available) {
    return scenario.uncappedNewEnd;
  }
  return (0, import_time.addMinutes)(bookingEnd, autoPricing.coveredMinutes);
};
var resolveAdjustTimeHints = ({
  activeAction,
  addedMinutes,
  policy,
  scenario,
  pricedNewEnd,
  uncappedPricedNewEnd
}) => {
  const { businessEnd, hasBusinessEndConflict, resourceEndDate } = policy;
  const businessEndTime = (0, import_time.formatTime)(businessEnd);
  const cappedEffectiveUntilTime = scenario.valid && pricedNewEnd.getTime() < uncappedPricedNewEnd.getTime() ? (0, import_time.formatTime)(pricedNewEnd) : void 0;
  const isManualBeyondBusinessEnd = activeAction === "manualDuration" && pricedNewEnd.getTime() > businessEnd.getTime();
  const shouldShowEffectiveUntilHint = isManualBeyondBusinessEnd || Boolean(cappedEffectiveUntilTime) || Boolean(hasBusinessEndConflict) || Boolean(scenario.unlimited);
  const shouldShowResourceAvailabilityWarning = resourceEndDate ? !shouldShowEffectiveUntilHint && activeAction !== "restart" && addedMinutes > 0 && resourceEndDate.getTime() < businessEnd.getTime() && pricedNewEnd.getTime() > resourceEndDate.getTime() : false;
  return {
    shouldShowEffectiveUntilHint,
    effectiveUntilTime: cappedEffectiveUntilTime || businessEndTime,
    resourceAvailabilityWarning: shouldShowResourceAvailabilityWarning ? t("pisell2.adjust-time.resource-available-time-exceeded") : void 0
  };
};
var useAdjustTimeModalController = ({
  open,
  booking,
  products,
  resourceEndTime,
  shopClosingTime,
  onSave,
  onCheckout
}) => {
  const sales = (0, import_useSalesSdk.useSalesSdk)();
  const [activeAction, setActiveAction] = (0, import_react.useState)("payOvertime");
  const start = (0, import_react.useMemo)(() => (0, import_time.toDate)(booking.start), [booking.start]);
  const end = (0, import_react.useMemo)(() => (0, import_time.toDate)(booking.end), [booking.end]);
  const [liveNow, setLiveNow] = (0, import_react.useState)(() => (0, import_time.resolveBillableMinuteDate)(/* @__PURE__ */ new Date()));
  const [manualEndTime, setManualEndTime] = (0, import_react.useState)(() => getManualDefaultEndTime(end, liveNow));
  const [manualEndDate, setManualEndDate] = (0, import_react.useState)(
    () => resolveDefaultManualEndDate(end, liveNow)
  );
  const [manualDueAmount, setManualDueAmount] = (0, import_react.useState)();
  const [priceInputState, setPriceInputState] = (0, import_react.useState)();
  const [debugShopClosingTime, setDebugShopClosingTime] = (0, import_react.useState)();
  const prevOpenRef = (0, import_react.useRef)(false);
  const resetManualEnd = (0, import_react.useCallback)((defaultManualEnd) => {
    setManualEndDate(defaultManualEnd);
    setManualEndTime((0, import_time.formatTime)(defaultManualEnd));
  }, []);
  (0, import_react.useEffect)(() => {
    if (!open) return void 0;
    let timeoutId;
    let intervalId;
    const tick = () => {
      const now = (0, import_time.resolveBillableMinuteDate)(/* @__PURE__ */ new Date());
      setLiveNow((prev) => prev.getTime() === now.getTime() ? prev : now);
    };
    tick();
    timeoutId = window.setTimeout(() => {
      tick();
      intervalId = window.setInterval(tick, 60 * 1e3);
    }, (0, import_time.getDelayToNextBillableMinuteChange)());
    return () => {
      if (timeoutId != null) window.clearTimeout(timeoutId);
      if (intervalId != null) window.clearInterval(intervalId);
    };
  }, [open]);
  (0, import_react.useEffect)(() => {
    if (typeof window === "undefined") return void 0;
    const setDebugClosingTime = (time) => {
      const normalized = normalizeShopClosingTime(time);
      setDebugShopClosingTime(normalized);
      return normalized;
    };
    const handleDebugEvent = (event) => {
      const detail = event.detail;
      setDebugClosingTime(typeof detail === "object" && detail !== null ? detail.time : detail);
    };
    const handleStorage = (event) => {
      if (event.key === "shopOpeningHours") {
        setDebugClosingTime(event.newValue);
      }
    };
    const debugSetter = (time) => {
      return setDebugClosingTime(time);
    };
    window.__pisellAdjustTimeSetShopClosingTime = debugSetter;
    window.addEventListener(DEBUG_SHOP_CLOSING_EVENT, handleDebugEvent);
    window.addEventListener("storage", handleStorage);
    return () => {
      if (window.__pisellAdjustTimeSetShopClosingTime === debugSetter) {
        delete window.__pisellAdjustTimeSetShopClosingTime;
      }
      window.removeEventListener(DEBUG_SHOP_CLOSING_EVENT, handleDebugEvent);
      window.removeEventListener("storage", handleStorage);
    };
  }, []);
  const current = liveNow;
  const effectiveShopClosingTime = debugShopClosingTime || shopClosingTime;
  const context = (0, import_react.useMemo)(
    () => resolveAdjustTimeContext({
      current,
      start,
      end,
      resourceEndTime,
      shopClosingTime: effectiveShopClosingTime
    }),
    [
      current,
      effectiveShopClosingTime,
      end,
      resourceEndTime,
      start
    ]
  );
  const policy = (0, import_react.useMemo)(
    () => resolveAdjustTimePolicy(context, booking.duration),
    [booking.duration, context]
  );
  const resolvePolicyByCurrent = (0, import_react.useCallback)(
    (nextCurrent) => resolveAdjustTimePolicy(
      resolveAdjustTimeContext({
        current: nextCurrent,
        start,
        end,
        resourceEndTime,
        shopClosingTime: effectiveShopClosingTime
      }),
      booking.duration
    ),
    [
      booking.duration,
      effectiveShopClosingTime,
      end,
      resourceEndTime,
      start
    ]
  );
  (0, import_react.useEffect)(() => {
    const justOpened = open && !prevOpenRef.current;
    prevOpenRef.current = open;
    if (!justOpened) return;
    const now = (0, import_time.resolveBillableMinuteDate)(/* @__PURE__ */ new Date());
    const nextPolicy = resolvePolicyByCurrent(now);
    const preferences = (0, import_preferences.readAdjustTimePreferences)();
    const restoredAction = (0, import_preferences.resolvePersistedAdjustTimeAction)(
      preferences == null ? void 0 : preferences.action,
      products,
      nextPolicy
    );
    const restoredManualEndDate = restoredAction === "manualDuration" && (preferences == null ? void 0 : preferences.manualEndTime) ? resolveManualEndDateByClock(
      nextPolicy.manualReferenceDate,
      nextPolicy.addTimeBaseEnd,
      preferences.manualEndTime
    ) : nextPolicy.manualDefaultEndDate;
    const restoredPriceInputState = (0, import_preferences.resolvePersistedPriceInputState)(preferences, restoredAction);
    setLiveNow(now);
    setActiveAction(restoredAction);
    resetManualEnd(
      restoredAction === "manualDuration" ? restoredManualEndDate : resolveDefaultManualEndDate(end, now)
    );
    setManualDueAmount(void 0);
    setPriceInputState(restoredPriceInputState);
  }, [end, open, products, resetManualEnd, resolvePolicyByCurrent]);
  const scenario = (0, import_react.useMemo)(
    () => buildAdjustTimeScenario({
      activeAction,
      manualEndDate,
      policy,
      products
    }),
    [
      activeAction,
      manualEndDate,
      policy,
      products
    ]
  );
  const autoPricing = (0, import_react.useMemo)(
    () => resolveAutoPricing({
      activeAction,
      products,
      scenario,
      resolveBestAddTimePlan: sales.resolveBestAddTimePlan
    }),
    [
      activeAction,
      products,
      sales.resolveBestAddTimePlan,
      scenario
    ]
  );
  const dueAmount = manualDueAmount == null ? autoPricing.totalPrice : Math.min(manualDueAmount, autoPricing.totalPrice);
  const pricedNewEnd = (0, import_react.useMemo)(
    () => resolvePricedNewEnd(activeAction, policy.addTimeBaseEnd, scenario, autoPricing),
    [
      activeAction,
      autoPricing.available,
      autoPricing.coveredMinutes,
      policy.addTimeBaseEnd,
      scenario.effectiveEndLimit,
      scenario.newEnd
    ]
  );
  const uncappedPricedNewEnd = (0, import_react.useMemo)(
    () => resolveUncappedPricedNewEnd(activeAction, policy.addTimeBaseEnd, scenario, autoPricing),
    [
      activeAction,
      autoPricing.available,
      autoPricing.coveredMinutes,
      policy.addTimeBaseEnd,
      scenario.uncappedNewEnd
    ]
  );
  const addedMinutes = (0, import_time.minutesBetween)(policy.addTimeBaseEnd, pricedNewEnd);
  const pricedTotalMinutes = (0, import_time.minutesBetween)(scenario.newStart, pricedNewEnd);
  const hints = (0, import_react.useMemo)(
    () => resolveAdjustTimeHints({
      activeAction,
      addedMinutes,
      policy,
      scenario,
      pricedNewEnd,
      uncappedPricedNewEnd
    }),
    [
      activeAction,
      addedMinutes,
      policy,
      pricedNewEnd,
      scenario,
      uncappedPricedNewEnd
    ]
  );
  const {
    shouldShowEffectiveUntilHint,
    effectiveUntilTime,
    resourceAvailabilityWarning
  } = hints;
  const checkoutDisabled = !scenario.valid || !autoPricing.available;
  const handleReset = (0, import_react.useCallback)(() => {
    const now = (0, import_time.resolveBillableMinuteDate)(/* @__PURE__ */ new Date());
    const nextPolicy = resolvePolicyByCurrent(now);
    setLiveNow(now);
    setActiveAction("payOvertime");
    resetManualEnd(nextPolicy.manualDefaultEndDate);
    setManualDueAmount(void 0);
    setPriceInputState(void 0);
    (0, import_preferences.writeAdjustTimePreferences)({ action: "payOvertime" });
  }, [resetManualEnd, resolvePolicyByCurrent]);
  const handleActionChange = (0, import_react.useCallback)((action) => {
    if (action === "manualDuration") {
      const now = (0, import_time.resolveBillableMinuteDate)(/* @__PURE__ */ new Date());
      const nextPolicy = resolvePolicyByCurrent(now);
      setLiveNow(now);
      resetManualEnd(nextPolicy.manualDefaultEndDate);
      (0, import_preferences.writeAdjustTimePreferences)({
        action,
        manualEndTime: (0, import_time.formatTime)(nextPolicy.manualDefaultEndDate)
      });
    } else {
      (0, import_preferences.writeAdjustTimePreferences)({ action });
    }
    setActiveAction(action);
    setManualDueAmount(void 0);
    setPriceInputState(void 0);
  }, [resetManualEnd, resolvePolicyByCurrent]);
  const handleManualEndTimeChange = (0, import_react.useCallback)((value) => {
    setManualEndDate(
      resolveManualEndDateByClock(policy.manualReferenceDate, policy.addTimeBaseEnd, value)
    );
    setManualEndTime(value);
    setManualDueAmount(void 0);
    setPriceInputState(void 0);
    (0, import_preferences.writeAdjustTimePreferences)({
      action: "manualDuration",
      manualEndTime: value
    });
  }, [policy.addTimeBaseEnd, policy.manualReferenceDate]);
  const handlePriceInputStateChange = (0, import_react.useCallback)((state) => {
    setPriceInputState(state);
  }, []);
  const handleDueAmountChange = (0, import_react.useCallback)(
    (value, state) => {
      const ticketCount = Math.max(1, Number(booking.quantity || 1));
      setManualDueAmount(value / ticketCount);
      if (state) {
        setPriceInputState(state);
      }
      (0, import_preferences.writeAdjustTimePreferences)({
        action: activeAction,
        // Manual Add time 再次打开时需要先恢复时间，否则价格基准可能变成 0。
        manualEndTime: activeAction === "manualDuration" ? manualEndTime : void 0,
        priceAction: activeAction,
        priceInputState: state || priceInputState,
        dueAmount: value
      });
    },
    [activeAction, booking.quantity, manualEndTime, priceInputState]
  );
  const handleAutoAmount = (0, import_react.useCallback)(() => {
    setManualDueAmount(void 0);
    setPriceInputState(void 0);
    (0, import_preferences.writeAdjustTimePreferences)({
      action: activeAction,
      manualEndTime: activeAction === "manualDuration" ? manualEndTime : void 0
    });
  }, [activeAction, manualEndTime]);
  const buildSubmitResult = (0, import_react.useCallback)(() => {
    const actionType = isProductAction(activeAction) ? "product" : activeAction;
    return {
      actionType,
      bookingId: booking.id,
      newStart: scenario.newStart,
      newEnd: pricedNewEnd,
      addedMinutes,
      autoPricing,
      dueAmount,
      manualDueAmount,
      selectedProductId: scenario.selectedProductId
    };
  }, [
    activeAction,
    addedMinutes,
    autoPricing,
    booking.id,
    dueAmount,
    manualDueAmount,
    scenario.newStart,
    scenario.selectedProductId,
    pricedNewEnd
  ]);
  const handleSave = (0, import_ahooks.useMemoizedFn)(() => {
    if (checkoutDisabled) return;
    onSave == null ? void 0 : onSave(buildSubmitResult());
  });
  const handleCheckout = (0, import_ahooks.useMemoizedFn)(() => {
    if (checkoutDisabled) return;
    onCheckout == null ? void 0 : onCheckout(buildSubmitResult());
  });
  return {
    activeAction,
    autoPricing,
    checkoutDisabled,
    dueAmount,
    addedMinutes,
    pricedNewEnd,
    pricedTotalMinutes,
    shouldShowEffectiveUntilHint,
    effectiveUntilTime,
    resourceAvailabilityWarning,
    manualEndTime,
    scenario,
    handleActionChange,
    handleCheckout,
    handleSave,
    handleManualEndTimeChange,
    handleReset,
    priceInputState,
    handleDueAmountChange,
    handleAutoAmount,
    handlePriceInputStateChange,
    setManualDueAmount
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useAdjustTimeModalController
});
