var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/pisellReservation/PisellReservation.tsx
var PisellReservation_exports = {};
__export(PisellReservation_exports, {
  PisellReservationCore: () => PisellReservationCore
});
module.exports = __toCommonJS(PisellReservation_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_zh_cn = require("dayjs/locale/zh-cn");
var import_en = require("dayjs/locale/en");
var import_zh_tw = require("dayjs/locale/zh-tw");
var import_classnames = __toESM(require("classnames"));
var import_date_picker = require("@pisell/date-picker");
var import_AdapterDayjs = require("@pisell/date-picker/es/AdapterDayjs");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_ReservationBookingDetailModal = require("./components/bookingDetailModal/ReservationBookingDetailModal");
var import_floorPlanApi = require("./floorMap/floorPlanApi");
var import_useBookingPerspective = require("../pisellSalesManagement/hooks/useBookingPerspective");
var import_booking = require("../pisellSalesManagement/config/booking");
var import_usePisellReservationBookingData = require("./hooks/usePisellReservationBookingData");
var import_usePisellReservationResourceTableData = require("./hooks/usePisellReservationResourceTableData");
var import_utils2 = require("../../utils");
var import_PisellReservation = require("./PisellReservation.less");
var import_ahooks = require("ahooks");
var import_serve = require("../pisellSalesManagement/serve");
var import_reservationTablesMerge = require("./data/reservationTablesMerge");
var import_bookingToReservationTables = require("./data/bookingToReservationTables");
var import_calendarAdapter = require("./data/calendarAdapter");
var import_reservationDataUtils = require("./data/reservationDataUtils");
var import_floorMapBoundRecordIds = require("./floorMap/floorMapBoundRecordIds");
var import_PisellReservationSubcomponents = require("./components/PisellReservationSubcomponents");
var import_useReservationFloorPlan = require("./floorMap/useReservationFloorPlan");
var import_useReservationFloorMapMerged = require("./floorMap/useReservationFloorMapMerged");
var import_reservationConstants = require("./reservationConstants");
var import_mapReservationToVenueWallCards = require("./data/mapReservationToVenueWallCards");
var import_reservationOperatingDayRange = require("./data/reservationOperatingDayRange");
var import_useReservationScheduleDebounced = require("./hooks/useReservationScheduleDebounced");
var import_useReservationSalesHostData = require("./hooks/useReservationSalesHostData");
var import_useReservationLoadingShownDebounced = require("./hooks/useReservationLoadingShownDebounced");
var import_useFloorMapBookingInteraction = require("./hooks/useFloorMapBookingInteraction");
var import_useReservationCalendarSlot = require("./hooks/useReservationCalendarSlot");
var import_useReservationToolBarMerged = require("./hooks/useReservationToolBarMerged");
var import_ReservationNewReservationModal = require("./components/ReservationNewReservationModal");
var import_usePicoCodingOpenData = require("./hooks/usePicoCodingOpenData");
var import_useReservationWallClockFollow = require("./hooks/useReservationWallClockFollow");
var import_useReservationHudDrawer = require("./hooks/useReservationHudDrawer");
var import_useReservationResourceWallPersist = require("./hooks/useReservationResourceWallPersist");
var import_useReservationDebugLoggers = require("./hooks/useReservationDebugLoggers");
var import_ReservationHudDrawer = require("./components/ReservationHudDrawer");
var import_buildReservationMobileTableConfig = require("./mobileTable/buildReservationMobileTableConfig");
var import_useReservationPhoneGridInfiniteData = require("./hooks/useReservationPhoneGridInfiniteData");
var PREVIEW_HTTP_CLIENT = {
  get: async () => ({ data: {} }),
  post: async () => ({ data: {} }),
  put: async () => ({ data: {} }),
  remove: async () => ({ data: {} }),
  custom: async () => ({ data: {} })
};
var PisellReservationCore = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
  const {
    gridDataSourceKey = import_reservationConstants.GRID_DS_KEY,
    dataSources: dataSourcesProp,
    scheduleValue: scheduleValueProp,
    onScheduleChange,
    reservationBiz: reservationBizProp,
    associatedMenuListIds: associatedMenuListIdsProp,
    toolBar: toolBarProp,
    floorMap: floorMapProp,
    scheduleStartSlot: scheduleStartSlotProp,
    scheduleEndSlot: scheduleEndSlotProp,
    onNewReservation,
    timeNavigatorProps: timeNavigatorPropsProp,
    scheduleProps: schedulePropsProp,
    fab,
    /** 不再作为首屏来源：从 props 剔除以免进入 rest（旧页面 schema 可能仍带此字段） */
    defaultBodyView: _unusedDefaultBodyView,
    data: dataProp,
    total: totalProp,
    pagination: paginationProp,
    onPageChange: onPageChangeProp,
    onSearch: onSearchProp,
    onReset: onResetProp,
    searchParams: searchParamsProp,
    loading: loadingProp,
    rowKey = "id",
    __id,
    className,
    style,
    floorPlanId: floorPlanIdProp,
    floorPlanCanvasWidth,
    floorPlanCanvasHeight,
    floorPlanCode,
    floorPlanName,
    floorPlanSort,
    floorPlanStatus,
    onFloorPlanPersisted,
    putFloorPlan,
    onFloorMapBookingClick,
    bodyViewSwitchable = true,
    lockedBodyView,
    bodyViewStorageKey,
    floorMapHudTableDrawer = false,
    variant,
    forceFollowWallClock: forceFollowWallClockProp,
    resourceSelectMode,
    ...rest
  } = props;
  const isPhoneLayout = variant === "phone";
  const isInternalListData = (0, import_reservationDataUtils.shouldUseBuiltinReservationList)(
    dataProp,
    totalProp,
    paginationProp,
    onPageChangeProp
  );
  const resolvedFloorPlanId = floorPlanIdProp === null ? null : floorPlanIdProp === void 0 ? import_floorPlanApi.RESERVATION_DEFAULT_FLOOR_PLAN_ID : floorPlanIdProp;
  const engineCtx = (0, import_useEngineContext.default)();
  const r = (_b = (_a = engineCtx == null ? void 0 : engineCtx.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.request;
  import_utils2.request.setRequest(r ?? PREVIEW_HTTP_CLIENT);
  const pisellos = (0, import_useEngineContext.usePisellOS)();
  const pisellosRef = (0, import_react.useRef)(pisellos);
  pisellosRef.current = pisellos;
  const hasPisellosGetModule = typeof (pisellos == null ? void 0 : pisellos.getModule) === "function";
  const engineLocale = ((_d = (_c = engineCtx == null ? void 0 : engineCtx.engine) == null ? void 0 : _c.props) == null ? void 0 : _d.locale) || "zh-CN";
  const app = (_g = (_f = (_e = engineCtx == null ? void 0 : engineCtx.appHelper) == null ? void 0 : _e.utils) == null ? void 0 : _f.getApp) == null ? void 0 : _g.call(_f);
  const router = (_i = (_h = app == null ? void 0 : app.router) == null ? void 0 : _h.getRoutes) == null ? void 0 : _i.call(_h);
  const params = (_k = (_j = app == null ? void 0 : app.history) == null ? void 0 : _j.useParams) == null ? void 0 : _k.call(_j);
  const BIZ = reservationBizProp ?? (params == null ? void 0 : params.business_code);
  const bookingListBusinessCodeExtra = (0, import_react.useMemo)(() => {
    const s = BIZ != null && BIZ !== "" ? String(BIZ).trim() : "";
    if (!s) return {};
    return { business_code: s };
  }, [BIZ]);
  const {
    reservationRuleProduct,
    reservationAssociatedMenuListIds: picoAssociatedMenuListIds
  } = (0, import_usePicoCodingOpenData.usePicoCodingOpenData)(engineCtx, BIZ);
  const reservationAssociatedMenuListIds = associatedMenuListIdsProp ?? picoAssociatedMenuListIds;
  const effectiveFloorPlanCode = BIZ || floorPlanCode || import_floorPlanApi.PISELL_RESERVATION_FLOOR_PLAN_CODE;
  const muiDatePickerAdapterLocale = (0, import_react.useMemo)(() => {
    const loc = String(engineLocale).toLowerCase();
    if (loc.startsWith("zh-cn")) return "zh-cn";
    if (loc.startsWith("zh-tw") || loc.startsWith("zh-hk"))
      return "zh-tw";
    return "en";
  }, [engineLocale]);
  const operatingDayBoundary = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    try {
      const store = (_g2 = (_f2 = (_e2 = (_d2 = (_c2 = (_b2 = (_a2 = engineCtx == null ? void 0 : engineCtx.appHelper) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.getApp) == null ? void 0 : _c2.call(_b2)) == null ? void 0 : _d2.data) == null ? void 0 : _e2.store) == null ? void 0 : _f2.getStore) == null ? void 0 : _g2.call(_f2);
      const coreData = (_h2 = store == null ? void 0 : store.getDataByModel) == null ? void 0 : _h2.call(store, "core", "core");
      const boundary = (0, import_reservationOperatingDayRange.resolveOperatingDayBoundaryFromCoreModel)(coreData);
      if (process.env.NODE_ENV !== "production") {
        let coreSnapshot = coreData;
        try {
          coreSnapshot = JSON.parse(JSON.stringify(coreData));
        } catch {
          coreSnapshot = coreData;
        }
        const rec = coreData;
        const underCore = (rec == null ? void 0 : rec.core) != null && typeof rec.core === "object" ? rec.core.operating_day_boundary : void 0;
        const onRoot = rec == null ? void 0 : rec.operating_day_boundary;
        console.info(
          '[PisellReservation][engine store getDataByModel("core","core")]',
          {
            hasStore: Boolean(store),
            coreSnapshot,
            operating_day_boundary_under_core: underCore,
            operating_day_boundary_on_model_root: onRoot,
            operating_day_boundary_RESOLVED: boundary
          }
        );
      }
      return boundary;
    } catch (e) {
      if (process.env.NODE_ENV !== "production") {
        console.warn(
          "[PisellReservation][engine] read core / operating_day_boundary failed",
          e
        );
      }
      return void 0;
    }
  }, [engineCtx]);
  const timelineRangeFromCore = (0, import_react.useMemo)(() => {
    const range = (0, import_reservationOperatingDayRange.timelineRangeFromOperatingDayBoundary)(operatingDayBoundary);
    if (process.env.NODE_ENV !== "production") {
      console.info(
        "[PisellReservation][timeline] derived from operating_day_boundary",
        {
          operatingDayBoundary,
          timelineRangeFromCore: range
        }
      );
    }
    return range;
  }, [operatingDayBoundary]);
  const effectiveTimelineRange = (0, import_react.useMemo)(() => {
    const fromProp = timeNavigatorPropsProp == null ? void 0 : timeNavigatorPropsProp.range;
    const effective = fromProp ?? timelineRangeFromCore;
    if (process.env.NODE_ENV !== "production") {
      console.info(
        "[PisellReservation][timeline] effective (timeNavigatorProps.range overrides core)",
        {
          timeNavigatorPropsRange: fromProp,
          effectiveTimelineRange: effective
        }
      );
    }
    return effective;
  }, [timeNavigatorPropsProp == null ? void 0 : timeNavigatorPropsProp.range, timelineRangeFromCore]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    const r2 = (_b2 = (_a2 = engineCtx == null ? void 0 : engineCtx.appHelper) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.request;
    if (r2) {
      import_utils2.request.setRequest(r2);
    }
  }, [(_m = (_l = engineCtx == null ? void 0 : engineCtx.appHelper) == null ? void 0 : _l.utils) == null ? void 0 : _m.request]);
  import_utils.locales.init(import_reservationConstants.PISELL_RESERVATION_PAGE_LOCALES, engineLocale);
  const getGridBookingInitialSearchParams = (0, import_react.useCallback)(
    () => (0, import_usePisellReservationBookingData.getGridTableBookingSearchParams)(
      operatingDayBoundary,
      effectiveTimelineRange
    ),
    [operatingDayBoundary, effectiveTimelineRange]
  );
  const resourceBoardData = (0, import_usePisellReservationResourceTableData.usePisellReservationResourceTableData)(isInternalListData);
  const gridBookingData = (0, import_usePisellReservationBookingData.usePisellReservationBookingData)(isInternalListData, {
    listPageSize: 50,
    getInitialSearchParams: getGridBookingInitialSearchParams,
    extraRequestParams: bookingListBusinessCodeExtra,
    /**
     * 必须为 false：与 `floorDayBookingData` 两路并发开 `osServer` 时，宿主侧常共用一个
     * booking 订阅槽或同 URL 请求互 abort，平面图那路 HTTP/推送会被挤掉，表现为 floor map 无预约。
     * 表格只信 HTTP；实时合并以 `floorDayBookingData`（带 form_record_ids）为准。
     */
    subscribeRealtimePush: true
  });
  const [shellBodyView, setShellBodyView] = (0, import_react.useState)(
    () => (0, import_reservationDataUtils.readBodyViewFromStorageKey)(bodyViewStorageKey)
  );
  const wallClockFollowLocked = (0, import_react.useMemo)(
    () => Boolean(forceFollowWallClockProp) || lockedBodyView === "resourceWall" || shellBodyView === "resourceWall",
    [forceFollowWallClockProp, lockedBodyView, shellBodyView]
  );
  const { baseFloorConfig, floorPlanRemoteId, setRemoteFloorPlanView } = (0, import_useReservationFloorPlan.useReservationFloorPlan)({
    resolvedFloorPlanId,
    effectiveFloorPlanCode,
    gridDataSourceKey,
    floorMapConfigFromProp: floorMapProp == null ? void 0 : floorMapProp.floorMapConfig,
    engineLocale
  });
  const floorConfigForBindings = (0, import_react.useMemo)(() => {
    const patch = floorMapProp == null ? void 0 : floorMapProp.floorMapConfig;
    if (!patch) return baseFloorConfig;
    const patchScene = patch.sceneElements;
    const usePatchScene = Array.isArray(patchScene) && patchScene.length > 0;
    return {
      ...baseFloorConfig,
      ...patch,
      sceneElements: usePatchScene ? patchScene : baseFloorConfig.sceneElements ?? patchScene
    };
  }, [floorMapProp == null ? void 0 : floorMapProp.floorMapConfig, baseFloorConfig]);
  const floorBoundFormRecordIds = (0, import_react.useMemo)(
    () => (0, import_floorMapBoundRecordIds.sceneElementsToBoundFormRecordIds)(
      floorConfigForBindings.sceneElements,
      gridDataSourceKey
    ),
    [floorConfigForBindings.sceneElements, gridDataSourceKey]
  );
  const resourceWallFilterIdsForFloorBooking = (0, import_react.useMemo)(() => {
    if (!isInternalListData) return [];
    const sp = gridBookingData.searchParams;
    const fv = sp == null ? void 0 : sp.filter;
    if (!fv || typeof fv !== "object" || fv === null) return [];
    const vals = fv.values;
    if (!vals || typeof vals !== "object") return [];
    const raw = vals[import_materials.DEFAULT_RESOURCE_WALL_FILTER_FIELD_KEY];
    if (!Array.isArray(raw)) return [];
    return raw.map(String).filter(Boolean);
  }, [isInternalListData, gridBookingData.searchParams]);
  const floorBookingResourceReady = isInternalListData && !resourceBoardData.loading;
  const floorBookingExtraParams = (0, import_react.useMemo)(() => {
    const normalizeIds = (ids) => {
      const out = [];
      for (const id of ids) {
        const t = String(id).trim();
        if (!t) continue;
        const n = Number(t);
        if (Number.isFinite(n) && n > 0 && /^\d+$/.test(t)) {
          out.push(Math.trunc(n));
        } else {
          out.push(t);
        }
      }
      return out;
    };
    if (shellBodyView === "resourceWall" && resourceWallFilterIdsForFloorBooking.length > 0) {
      return {
        ...bookingListBusinessCodeExtra,
        form_record_ids: normalizeIds(resourceWallFilterIdsForFloorBooking)
      };
    }
    return {
      ...bookingListBusinessCodeExtra,
      form_record_ids: floorBoundFormRecordIds
    };
  }, [
    bookingListBusinessCodeExtra,
    shellBodyView,
    resourceWallFilterIdsForFloorBooking,
    floorBoundFormRecordIds
  ]);
  const getFloorDayBookingInitialSearchParams = (0, import_react.useCallback)(
    () => (0, import_usePisellReservationBookingData.getDefaultMonitorSearchParams)(
      (0, import_dayjs.default)(),
      operatingDayBoundary,
      effectiveTimelineRange
    ),
    [operatingDayBoundary, effectiveTimelineRange]
  );
  const floorDayBookingData = (0, import_usePisellReservationBookingData.usePisellReservationBookingData)(
    floorBookingResourceReady,
    {
      listPageSize: 9999,
      extraRequestParams: floorBookingExtraParams,
      getInitialSearchParams: getFloorDayBookingInitialSearchParams
    }
  );
  const _getRelationTables = (0, import_ahooks.useRequest)(import_serve.getRelationTables);
  const bookingPerspectiveParams = (0, import_react.useMemo)(
    () => ({ relationTables: _getRelationTables.data }),
    [_getRelationTables.data]
  );
  const bookingPerspective = (0, import_useBookingPerspective.useBookingPerspective)(bookingPerspectiveParams);
  const runtimeContext = (0, import_react.useMemo)(
    () => ({
      refresh: () => {
        resourceBoardData.refresh();
        gridBookingData.refresh();
        floorDayBookingData.refresh();
      },
      refreshAsync: async () => {
        await Promise.all([
          resourceBoardData.refreshAsync(),
          gridBookingData.refreshAsync(),
          floorDayBookingData.refreshAsync()
        ]);
      },
      currentPerspective: "monitor"
    }),
    [
      resourceBoardData.refresh,
      resourceBoardData.refreshAsync,
      gridBookingData.refresh,
      gridBookingData.refreshAsync,
      floorDayBookingData.refresh,
      floorDayBookingData.refreshAsync
    ]
  );
  const bookingChildProps = (0, import_react.useMemo)(() => {
    const build = bookingPerspective.getChildComponentProps;
    return build ? build(runtimeContext) : {};
  }, [bookingPerspective, runtimeContext]);
  const bookingColumnStorageKey = (0, import_react.useMemo)(
    () => (0, import_booking.resolveBookingMonitorColumnStorageKey)(__id),
    [__id]
  );
  const {
    internalSchedule,
    setInternalSchedule,
    schedule,
    debouncedSchedule,
    flushCommittedSchedule,
    queueCommittedSchedule
  } = (0, import_useReservationScheduleDebounced.useReservationScheduleDebounced)({
    scheduleValueProp
  });
  const mergedTimeNavigatorProps = (0, import_react.useMemo)(
    () => {
      const isViewingToday = (0, import_dayjs.default)(schedule.date).startOf("day").isSame((0, import_dayjs.default)().startOf("day"), "day");
      return {
        ...timeNavigatorPropsProp ?? {},
        range: effectiveTimelineRange,
        snapToStep: false,
        cursorMode: isPhoneLayout ? "axis-moves" : "cursor-moves",
        referenceDate: (timeNavigatorPropsProp == null ? void 0 : timeNavigatorPropsProp.referenceDate) ?? (isViewingToday ? void 0 : (0, import_reservationOperatingDayRange.timelineReferenceDateForScheduleDay)(
          schedule.date,
          operatingDayBoundary
        ))
      };
    },
    [
      timeNavigatorPropsProp,
      effectiveTimelineRange,
      schedule.date,
      operatingDayBoundary,
      isPhoneLayout
    ]
  );
  const {
    followWallClock,
    setFollowWallClock,
    onFollowWallClockToggle,
    onTimeNavigatorUserInteraction
  } = (0, import_useReservationWallClockFollow.useReservationWallClockFollow)(
    scheduleValueProp,
    setInternalSchedule,
    flushCommittedSchedule,
    onScheduleChange,
    wallClockFollowLocked
  );
  const { salesResourceBookings, salesTimelineHighlights } = (0, import_useReservationSalesHostData.useReservationSalesHostData)({
    isInternalListData,
    pisellosRef,
    hasPisellosGetModule,
    debouncedSchedule,
    followWallClock,
    resourceBoardLoading: resourceBoardData.loading,
    floorDayBookingLoading: floorDayBookingData.loading,
    floorDayBookingData: floorDayBookingData.data,
    /**
     * 兜底：每次 WS 推送 mutate 都让 `floorDayBookingDataVersion` 自增，
     * 哪怕 cheap hash 没捕获到字段变化也能强制刷新宿主 sales 列表。
     */
    floorDayBookingDataVersion: floorDayBookingData.pushDataVersion,
    scheduleDate: schedule.date,
    timeNavigatorPropsProp,
    timelineRange: effectiveTimelineRange,
    operatingDayBoundary
  });
  const tables = (0, import_react.useMemo)(
    () => (0, import_reservationTablesMerge.buildReservationMergedTableRows)({
      dataSourcesProp,
      gridDataSourceKey,
      isInternalListData,
      resourceList: resourceBoardData.data,
      floorDayBookingList: floorDayBookingData.data,
      schedule,
      dataProp,
      salesResourceBookings
    }),
    [
      dataSourcesProp,
      gridDataSourceKey,
      isInternalListData,
      resourceBoardData.data,
      floorDayBookingData.data,
      salesResourceBookings,
      dataProp
    ]
  );
  const calendarOrderedResourceIds = (0, import_react.useMemo)(() => {
    const fromScene = (0, import_calendarAdapter.orderedCanvasResourceRecordIdStrings)(
      floorConfigForBindings.sceneElements,
      gridDataSourceKey
    );
    if (fromScene.length > 0) return fromScene;
    const fromTables = [
      ...new Set(
        tables.map((r2) => String(r2.id)).filter((id) => id !== "" && id !== "undefined" && id !== "null")
      )
    ];
    if (fromTables.length > 0) return fromTables;
    const fromBookings = /* @__PURE__ */ new Set();
    const list = floorDayBookingData.data;
    if (Array.isArray(list)) {
      for (const raw of list) {
        if (!raw || typeof raw !== "object") continue;
        for (const id of (0, import_bookingToReservationTables.extractResourceRecordIds)(
          raw
        )) {
          if (id) fromBookings.add(id);
        }
      }
    }
    return [...fromBookings];
  }, [
    floorConfigForBindings.sceneElements,
    gridDataSourceKey,
    tables,
    floorDayBookingData.data
  ]);
  const calendarCanvasIdSet = (0, import_react.useMemo)(
    () => new Set(calendarOrderedResourceIds),
    [calendarOrderedResourceIds]
  );
  const calendarResources = (0, import_react.useMemo)(
    () => (0, import_calendarAdapter.buildCalendarResourcesFromMergedTables)({
      orderedResourceIds: calendarOrderedResourceIds,
      tables
    }),
    [calendarOrderedResourceIds, tables]
  );
  const calendarBookings = (0, import_react.useMemo)(
    () => (0, import_calendarAdapter.mapFloorDayBookingsToCalendarItems)({
      bookings: floorDayBookingData.data,
      canvasResourceIdSet: calendarCanvasIdSet
    }),
    [floorDayBookingData.data, calendarCanvasIdSet]
  );
  const venueWallCards = (0, import_react.useMemo)(
    () => (0, import_mapReservationToVenueWallCards.mapReservationRowsToVenueWallCards)(tables),
    [tables]
  );
  const debouncedScheduleKey = (0, import_react.useMemo)(
    () => `${(0, import_dayjs.default)(debouncedSchedule.date).startOf("day").valueOf()}_${(0, import_dayjs.default)(
      debouncedSchedule.at
    ).valueOf()}`,
    [debouncedSchedule.date, debouncedSchedule.at]
  );
  const bodyViewRef = (0, import_react.useRef)(
    (0, import_reservationDataUtils.readBodyViewFromStorageKey)(bodyViewStorageKey)
  );
  const floorMapLayoutRef = (0, import_react.useRef)(null);
  const newReservationModalRef = (0, import_react.useRef)(null);
  const searchParamsRefControlled = (0, import_react.useRef)(searchParamsProp);
  (0, import_react.useEffect)(() => {
    searchParamsRefControlled.current = searchParamsProp;
  }, [searchParamsProp]);
  const onSearchRef = (0, import_react.useRef)(onSearchProp);
  const onScheduleChangeRef = (0, import_react.useRef)(onScheduleChange);
  (0, import_react.useEffect)(() => {
    onSearchRef.current = onSearchProp;
    onScheduleChangeRef.current = onScheduleChange;
  });
  (0, import_react.useEffect)(() => {
    var _a2;
    if (isInternalListData && bodyViewRef.current !== "calendar") {
      const d = debouncedSchedule.date;
      floorDayBookingData.patchSearchParams(
        (prevParams) => (0, import_reservationDataUtils.mergeSearchParamsBookingWindow)(
          prevParams,
          d,
          operatingDayBoundary,
          effectiveTimelineRange,
          (0, import_dayjs.default)()
        )
      );
    }
    if ((bodyViewRef.current === "floorMap" || bodyViewRef.current === "calendar" || bodyViewRef.current === "resourceWall") && !isInternalListData) {
      (_a2 = onSearchRef.current) == null ? void 0 : _a2.call(onSearchRef, {
        ...searchParamsRefControlled.current ?? {},
        reservationDate: debouncedSchedule.date.toISOString(),
        reservationAt: debouncedSchedule.at.toISOString()
      });
    }
  }, [
    debouncedSchedule,
    isInternalListData,
    floorDayBookingData.patchSearchParams,
    operatingDayBoundary,
    effectiveTimelineRange
  ]);
  const handleScheduleChange = (0, import_react.useCallback)(
    (next) => {
      if (!wallClockFollowLocked) {
        setFollowWallClock(false);
      }
      if (scheduleValueProp === void 0) {
        setInternalSchedule(next);
      }
      onScheduleChange == null ? void 0 : onScheduleChange(next);
      queueCommittedSchedule(next);
    },
    [
      scheduleValueProp,
      onScheduleChange,
      setFollowWallClock,
      queueCommittedSchedule,
      wallClockFollowLocked
    ]
  );
  const dataSources = (0, import_react.useMemo)(() => {
    return {
      ...dataSourcesProp,
      [gridDataSourceKey]: tables
    };
  }, [gridDataSourceKey, tables, dataSourcesProp]);
  const isFloorModeControlled = (floorMapProp == null ? void 0 : floorMapProp.mode) !== void 0;
  const [mapEditInternal, setMapEditInternal] = (0, import_react.useState)(false);
  const effectiveMapMode = (floorMapProp == null ? void 0 : floorMapProp.mode) ?? (mapEditInternal ? "edit" : "read");
  const {
    showVenueHudDock,
    handleOpenHudTableDrawer,
    closeHudTableDrawer,
    hudDrawerRef,
    hudDrawerOpen,
    hudMapItems,
    hudDrawerResourceRootBuckets,
    hudDrawerPagedRows,
    hudDrawerFilteredTotal,
    hudDrawerLoading,
    hudDrawerBookingPagination,
    hudDrawerOnSearch,
    hudDrawerOnReset,
    hudDrawerOnPageChange,
    hudDrawerToolBar,
    hudDrawerLocalSearchParams,
    handleHudDrawerFormRecordIdsChange,
    reservationFloorMapViewportOverlay,
    renderItemByKind
  } = (0, import_useReservationHudDrawer.useReservationHudDrawer)({
    floorMapHudTableDrawer,
    dataSources,
    gridDataSourceKey,
    isInternalListData,
    floorDayBookingData,
    searchParamsProp,
    dataProp,
    loadingProp,
    bookingChildProps,
    resourceBoardData,
    phoneLayout: isPhoneLayout,
    hideViewportHudStats: isPhoneLayout && effectiveMapMode === "edit"
  });
  const [floorMapAppearanceMode, setFloorMapAppearanceMode] = (0, import_react.useState)(() => (0, import_reservationDataUtils.readReservationFloorMapAppearanceMode)(effectiveFloorPlanCode));
  (0, import_react.useEffect)(() => {
    setFloorMapAppearanceMode(
      (0, import_reservationDataUtils.readReservationFloorMapAppearanceMode)(effectiveFloorPlanCode)
    );
  }, [effectiveFloorPlanCode]);
  const toggleFloorMapAppearanceMode = (0, import_react.useCallback)(() => {
    setFloorMapAppearanceMode((prev) => {
      const next = prev === "light" ? "dark" : "light";
      (0, import_reservationDataUtils.writeReservationFloorMapAppearanceMode)(effectiveFloorPlanCode, next);
      return next;
    });
  }, [effectiveFloorPlanCode]);
  const {
    bookingDetailOpen,
    bookingDetailRaw,
    bookingDetailRow,
    bookingDetailSceneName,
    closeBookingDetailModal,
    closeBookingDetailNow,
    floorMapItemClickBefore,
    openBookingDetailFromRaw,
    readModeSelectedFloorItemId
  } = (0, import_useFloorMapBookingInteraction.useFloorMapBookingInteraction)({
    engineCtx,
    onFloorMapBookingClick,
    dataSources,
    mergedTableRows: tables,
    reservationBiz: BIZ,
    resourceSelectMode,
    associatedMenuListIds: reservationAssociatedMenuListIds,
    reservationRuleProduct
  });
  const handleBookingDetailActionSuccess = (0, import_react.useCallback)(async () => {
    closeBookingDetailNow();
    await runtimeContext.refreshAsync();
  }, [closeBookingDetailNow, runtimeContext]);
  const {
    reservationCalendarSlotProps,
    calendarGranularity,
    setCalendarGranularity
  } = (0, import_useReservationCalendarSlot.useReservationCalendarSlot)({
    isInternalListData,
    floorDayBookingData,
    operatingDayBoundary,
    tables,
    openBookingDetailFromRaw,
    schedule,
    handleScheduleChange,
    calendarResources,
    calendarBookings,
    effectiveTimelineRange,
    runtimeContext
  });
  const floorMapMerged = (0, import_useReservationFloorMapMerged.useReservationFloorMapMerged)({
    floorMapProp,
    baseFloorConfig,
    dataSources,
    renderItemByKind,
    gridDataSourceKey,
    effectiveMapMode,
    resolvedFloorPlanId,
    floorPlanRemoteId,
    effectiveFloorPlanCode,
    floorPlanCanvasWidth,
    floorPlanCanvasHeight,
    floorPlanName,
    floorPlanSort,
    floorPlanStatus,
    onFloorPlanPersisted,
    putFloorPlan,
    isFloorModeControlled,
    mapEditInternal,
    setMapEditInternal,
    floorMapLayoutRef,
    reservationFloorMapViewportOverlay,
    setRemoteFloorPlanView,
    floorMapItemClickBefore,
    engineLocale,
    floorMapHudTableDrawer,
    readModeSelectedItemId: readModeSelectedFloorItemId,
    editTopBarPhoneLayout: isPhoneLayout,
    appearanceMode: floorMapAppearanceMode,
    onToggleAppearanceMode: toggleFloorMapAppearanceMode
  });
  const data = isInternalListData ? gridBookingData.data : dataProp ?? [];
  const loadingShown = (0, import_useReservationLoadingShownDebounced.useReservationLoadingShownDebounced)(
    isInternalListData ? false : loadingProp ?? false
  );
  const total = isInternalListData ? gridBookingData.total : totalProp ?? 0;
  const pagination = isInternalListData ? gridBookingData.pagination : paginationProp ?? {
    pageNumber: 1,
    pageSize: import_reservationConstants.PISELL_RESERVATION_DEFAULT_PAGE_SIZE
  };
  const onPageChange = isInternalListData ? gridBookingData.onPageChange : onPageChangeProp;
  const searchParams = isInternalListData ? gridBookingData.searchParams : searchParamsProp ?? {};
  const phoneGridInfiniteData = (0, import_useReservationPhoneGridInfiniteData.useReservationPhoneGridInfiniteData)({
    enabled: isPhoneLayout,
    isInternalListData,
    rowKey,
    data,
    pagination,
    searchParams
  });
  const recordBoardListData = isPhoneLayout ? phoneGridInfiniteData : data;
  const onGridBookingSearch = (0, import_react.useCallback)(
    (params2) => {
      gridBookingData.onSearch((0, import_reservationDataUtils.mergeGridBookingSearchParams)(params2));
    },
    [gridBookingData.onSearch]
  );
  const onSearch = isInternalListData ? onGridBookingSearch : onSearchProp;
  const onReset = isInternalListData ? gridBookingData.onReset : onResetProp;
  const {
    venueWallAppearanceTheme,
    setVenueWallAppearanceTheme,
    venueWallAppearanceMode,
    setVenueWallAppearanceMode,
    venueWallResourceLayout,
    setVenueWallResourceLayout
  } = (0, import_useReservationResourceWallPersist.useReservationResourceWallPersist)({
    bodyViewStorageKey,
    isInternalListData,
    searchParams,
    onSearch,
    venueWallCards,
    floorDayBookingLoading: floorDayBookingData.loading
  });
  (0, import_useReservationDebugLoggers.useReservationDebugLoggers)({
    isInternalListData,
    resourceList: resourceBoardData.data,
    resourceListLoading: resourceBoardData.loading,
    salesResourceBookings,
    debouncedScheduleKey,
    debouncedSchedule,
    gridBookingData,
    floorDayBookingData,
    tables,
    dataProp: dataProp ?? void 0,
    dataSourcesProp,
    gridDataSourceKey,
    floorConfigForBindings,
    floorBoundFormRecordIds,
    shellBodyView,
    calendarGranularity,
    schedule,
    effectiveTimelineRange,
    calendarOrderedResourceIds,
    calendarResources,
    calendarBookings,
    venueWallCards,
    searchParams,
    floorBookingExtraParams
  });
  const { toolBarMerged } = (0, import_useReservationToolBarMerged.useReservationToolBarMerged)({
    toolBarProp,
    bookingToolBar: bookingChildProps.toolBar,
    isInternalListData,
    tables,
    schedule,
    handleScheduleChange,
    scheduleStartSlotProp,
    scheduleEndSlotProp,
    schedulePropsProp,
    mergedTimeNavigatorProps,
    followWallClock,
    onFollowWallClockToggle,
    onTimeNavigatorUserInteraction,
    calendarGranularity,
    setCalendarGranularity,
    onNewReservation: () => {
      var _a2;
      return (_a2 = newReservationModalRef.current) == null ? void 0 : _a2.requestOpen();
    },
    salesTimelineHighlights,
    floorDayBookingData: floorDayBookingData.data,
    data,
    effectiveTimelineRange,
    phoneLayout: isPhoneLayout,
    bodyView: shellBodyView
  });
  const recordBoardGrid = (0, import_react.useMemo)(() => {
    return bookingChildProps.grid;
  }, [bookingChildProps.grid]);
  const mobileRecordBoardGrid = (0, import_react.useMemo)(() => {
    if (!isPhoneLayout || recordBoardGrid == null || typeof recordBoardGrid !== "object") {
      return recordBoardGrid;
    }
    return (0, import_buildReservationMobileTableConfig.buildReservationMobileTableGridConfig)(
      recordBoardGrid
    );
  }, [isPhoneLayout, recordBoardGrid]);
  const hudDrawerMobileGrid = (0, import_react.useMemo)(() => {
    if (recordBoardGrid == null || typeof recordBoardGrid !== "object") {
      return recordBoardGrid;
    }
    return (0, import_buildReservationMobileTableConfig.buildReservationMobileTableGridConfig)(
      recordBoardGrid
    );
  }, [recordBoardGrid]);
  const hudDrawerGrid = (0, import_react.useMemo)(() => {
    const g = hudDrawerMobileGrid;
    const scrollBase = g != null && typeof g === "object" && "scroll" in g && g.scroll != null && typeof g.scroll === "object" ? { ...g.scroll } : {};
    if (g == null || typeof g !== "object") {
      return {
        size: "small",
        infiniteScroll: true,
        scroll: { ...scrollBase, autoCalc: true }
      };
    }
    return {
      ...g,
      size: "small",
      infiniteScroll: true,
      scroll: { ...scrollBase, autoCalc: true }
    };
  }, [hudDrawerMobileGrid]);
  const fillHeight = ((_n = mobileRecordBoardGrid == null ? void 0 : mobileRecordBoardGrid.scroll) == null ? void 0 : _n.autoCalc) ?? true;
  const reservationResourceWallSlotProps = (0, import_react.useMemo)(
    () => ({
      cards: venueWallCards,
      loading: floorDayBookingData.loading,
      filterFieldKey: import_materials.DEFAULT_RESOURCE_WALL_FILTER_FIELD_KEY,
      appearanceTheme: venueWallAppearanceTheme,
      onAppearanceThemeChange: setVenueWallAppearanceTheme,
      appearanceMode: venueWallAppearanceMode,
      onAppearanceModeChange: setVenueWallAppearanceMode,
      resourceWallLayout: venueWallResourceLayout,
      onResourceWallLayoutChange: setVenueWallResourceLayout
    }),
    [
      venueWallCards,
      floorDayBookingData.loading,
      venueWallAppearanceTheme,
      venueWallAppearanceMode,
      venueWallResourceLayout
    ]
  );
  return /* @__PURE__ */ import_react.default.createElement(
    import_date_picker.LocalizationProvider,
    {
      dateAdapter: import_AdapterDayjs.AdapterDayjs,
      adapterLocale: muiDatePickerAdapterLocale
    },
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: (0, import_classnames.default)(
          "pisell-reservation-page",
          isPhoneLayout && "pisell-reservation-page--phone",
          className
        ),
        style
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellRecordBoard,
        {
          ...rest,
          columnVisibilityStorageKey: bookingColumnStorageKey,
          layoutVariant: isPhoneLayout ? "phone" : "default",
          fillHeight,
          rowKey,
          data: recordBoardListData,
          dataSources,
          loading: loadingShown,
          total,
          pagination,
          onPageChange,
          searchParams,
          onSearch,
          onReset,
          grid: mobileRecordBoardGrid,
          toolBar: toolBarMerged,
          search: bookingChildProps.search,
          batchActionBar: bookingChildProps.batchActionBar,
          floorMap: floorMapMerged,
          calendar: reservationCalendarSlotProps,
          resourceWall: reservationResourceWallSlotProps,
          defaultBodyView: "floorMap",
          bodyViewStorageKey,
          bodyViewSwitchable,
          lockedBodyView,
          floorMapLayoutRef
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_PisellReservationSubcomponents.RecordBoardBodyViewCapture,
          {
            bodyViewRef,
            onBodyViewChange: setShellBodyView
          }
        ),
        /* @__PURE__ */ import_react.default.createElement(
          import_PisellReservationSubcomponents.ScheduleSyncOnFloorEnter,
          {
            schedule,
            isInternalListData,
            patchSearchParams: floorDayBookingData.patchSearchParams,
            operatingDayBoundary,
            timelineRange: effectiveTimelineRange
          }
        ),
        /* @__PURE__ */ import_react.default.createElement(import_materials.PisellRecordBoard.ShellFrame, null, /* @__PURE__ */ import_react.default.createElement(import_materials.PisellRecordBoard.GridLayout, null), /* @__PURE__ */ import_react.default.createElement(import_materials.PisellRecordBoard.FloorMap, null), /* @__PURE__ */ import_react.default.createElement(import_materials.PisellRecordBoard.Calendar, { ...reservationCalendarSlotProps }), /* @__PURE__ */ import_react.default.createElement(import_materials.PisellRecordBoard.ResourceWall, null))
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_ReservationNewReservationModal.ReservationNewReservationModal,
        {
          ref: newReservationModalRef,
          router,
          app
        }
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_ReservationBookingDetailModal.ReservationBookingDetailModal,
        {
          open: bookingDetailOpen,
          onClose: closeBookingDetailModal,
          onActionSuccess: handleBookingDetailActionSuccess,
          raw: bookingDetailRaw,
          tableRow: bookingDetailRow,
          sceneElementName: bookingDetailSceneName,
          reservationBiz: BIZ,
          associatedMenuListIds: reservationAssociatedMenuListIds,
          reservationRuleProduct,
          floorDayBookingList: floorDayBookingData.data,
          currentTime: debouncedSchedule.at,
          followWallClock
        }
      ),
      fab ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-reservation-fab" }, fab) : null,
      /* @__PURE__ */ import_react.default.createElement(
        import_ReservationHudDrawer.ReservationHudDrawer,
        {
          floorMapHudTableDrawer,
          showVenueHudDock,
          hudDrawerOpen,
          hudDrawerRef,
          hudMapItems,
          dataSources,
          handleOpenHudTableDrawer,
          closeHudTableDrawer,
          rowKey,
          hudDrawerPagedRows,
          hudDrawerLoading,
          hudDrawerFilteredTotal,
          hudDrawerBookingPagination,
          hudDrawerOnPageChange,
          hudDrawerLocalSearchParams,
          hudDrawerOnSearch,
          hudDrawerOnReset,
          hudDrawerGrid,
          hudDrawerToolBar,
          batchActionBar: bookingChildProps.batchActionBar,
          hudDrawerResourceRootBuckets,
          handleHudDrawerFormRecordIdsChange
        }
      )
    )
  );
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PisellReservationCore
});
