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/components/scanOrder/context.tsx
var context_exports = {};
__export(context_exports, {
  ScanOrderProvider: () => ScanOrderProvider,
  useScanOrderContext: () => useScanOrderContext
});
module.exports = __toCommonJS(context_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_hooks = require("./hooks");
var import_useEngineContext = require("../../hooks/useEngineContext");
var ScanOrderContext = (0, import_react.createContext)(
  void 0
);
var INITIAL_VIEW_MODEL = {
  menuItems: [],
  cartItems: [],
  summary: {},
  note: ""
};
function ScanOrderProvider({
  entryContext,
  children
}) {
  const pisellOS = (0, import_useEngineContext.usePisellOS)();
  const scanOrderModule = (0, import_hooks.useScanOrderModule)();
  const [isLoading, setIsLoading] = (0, import_react.useState)(true);
  const [errorMessage, setErrorMessage] = (0, import_react.useState)("");
  const [currentStep, setCurrentStep] = (0, import_react.useState)("init");
  const [viewModel, setViewModel] = (0, import_react.useState)(INITIAL_VIEW_MODEL);
  const [cartValidation, setCartValidation] = (0, import_react.useState)({
    passed: null,
    failures: []
  });
  const [footerActionText, setFooterActionText] = (0, import_react.useState)(
    String(import_utils.locales.getText("pisell2.scan.order.action.select.required") || "")
  );
  const [tableName, setTableName] = (0, import_react.useState)("");
  const [entryMode, setEntryMode] = (0, import_react.useState)("default");
  const [submitDisabledTips, setSubmitDisabledTips] = (0, import_react.useState)("");
  const [discountList, setDiscountList] = (0, import_react.useState)([]);
  const [isCacheHydrated, setIsCacheHydrated] = (0, import_react.useState)(false);
  const [resumeStep, setResumeStep] = (0, import_react.useState)(null);
  const hydratedRef = (0, import_react.useRef)(false);
  const stepList = [...import_hooks.SCAN_ORDER_STEPS];
  const isGatePassed = (0, import_react.useCallback)(
    (flag) => {
      var _a;
      const gate = (_a = scanOrderModule == null ? void 0 : scanOrderModule.getUIState) == null ? void 0 : _a.call(scanOrderModule, "gate");
      return Boolean(gate == null ? void 0 : gate[flag]);
    },
    [scanOrderModule]
  );
  const markGate = (0, import_react.useCallback)(
    (flag) => {
      var _a;
      if (!(scanOrderModule == null ? void 0 : scanOrderModule.setUIState)) return;
      const prev = ((_a = scanOrderModule.getUIState) == null ? void 0 : _a.call(scanOrderModule, "gate")) || {};
      scanOrderModule.setUIState("gate", { ...prev, [flag]: true });
    },
    [scanOrderModule]
  );
  const clearStepCache = (0, import_react.useCallback)(() => {
    var _a;
    (_a = scanOrderModule == null ? void 0 : scanOrderModule.clearUIState) == null ? void 0 : _a.call(scanOrderModule);
    setResumeStep(null);
  }, [scanOrderModule]);
  const consumeResumeStep = (0, import_react.useCallback)(() => {
    setResumeStep(null);
  }, []);
  const refreshViewModel = async () => {
    if (scanOrderModule && typeof scanOrderModule.getSummary === "function") {
      try {
        await scanOrderModule.getSummary();
      } catch (error) {
        console.warn("[scanOrder] getSummary failed during refreshViewModel", error);
      }
    }
    setViewModel((0, import_hooks.createScanOrderViewModel)(scanOrderModule));
    if (scanOrderModule && typeof scanOrderModule.getDiscountList === "function") {
      setDiscountList(scanOrderModule.getDiscountList() || []);
    }
  };
  const updateOrderNote = async (note) => {
    await (0, import_hooks.safeRunModuleAction)(scanOrderModule, "updateTempOrderNote", note);
    await refreshViewModel();
  };
  const goToStep = (step) => {
    if (!stepList.includes(step)) return;
    setCurrentStep(step);
  };
  const nextStep = () => {
    const currentIndex = stepList.findIndex((step) => step === currentStep);
    if (currentIndex < 0) return;
    if (currentIndex >= stepList.length - 1) return;
    setCurrentStep(stepList[currentIndex + 1]);
  };
  const prevStep = () => {
    const currentIndex = stepList.findIndex((step) => step === currentStep);
    if (currentIndex <= 0) return;
    setCurrentStep(stepList[currentIndex - 1]);
  };
  const runModuleAction = async (actionName, ...args) => {
    return (0, import_hooks.safeRunModuleAction)(scanOrderModule, actionName, ...args);
  };
  (0, import_react.useEffect)(() => {
    var _a, _b, _c, _d, _e, _f;
    if (hydratedRef.current || !scanOrderModule) return;
    hydratedRef.current = true;
    const normalizedResourceId = String((entryContext == null ? void 0 : entryContext.resource_id) ?? "");
    const normalizedBiz = String((entryContext == null ? void 0 : entryContext.biz) ?? "");
    const currentHasOrderId = Boolean(entryContext == null ? void 0 : entryContext.order_id);
    const cachedEntry = (_a = scanOrderModule.getUIState) == null ? void 0 : _a.call(scanOrderModule, "entryContext");
    const entrySame = Boolean(cachedEntry) && String((cachedEntry == null ? void 0 : cachedEntry.resourceId) ?? "") === normalizedResourceId && String((cachedEntry == null ? void 0 : cachedEntry.biz) ?? "") === normalizedBiz;
    if (!entrySame) {
      (_b = scanOrderModule.clearUIState) == null ? void 0 : _b.call(scanOrderModule);
      (_c = scanOrderModule.setUIState) == null ? void 0 : _c.call(scanOrderModule, "entryContext", {
        resourceId: normalizedResourceId,
        hasOrderId: currentHasOrderId,
        biz: normalizedBiz
      });
      setIsCacheHydrated(true);
      return;
    }
    const isResumable = (s) => s === "product" || s === "check";
    const pending = (_d = scanOrderModule.getUIState) == null ? void 0 : _d.call(scanOrderModule, "pendingStep");
    if (isResumable(pending)) {
      (_e = scanOrderModule.deleteUIState) == null ? void 0 : _e.call(scanOrderModule, "pendingStep");
      setResumeStep(pending);
      setIsCacheHydrated(true);
      return;
    }
    const cached = (_f = scanOrderModule.getUIState) == null ? void 0 : _f.call(scanOrderModule, "step");
    if (isResumable(cached)) setResumeStep(cached);
    setIsCacheHydrated(true);
  }, [scanOrderModule, entryContext == null ? void 0 : entryContext.resource_id, entryContext == null ? void 0 : entryContext.order_id, entryContext == null ? void 0 : entryContext.biz]);
  (0, import_react.useEffect)(() => {
    var _a;
    if (!hydratedRef.current || !isCacheHydrated || !scanOrderModule) return;
    if (currentStep === "init") return;
    (_a = scanOrderModule.setUIState) == null ? void 0 : _a.call(scanOrderModule, "step", currentStep);
  }, [currentStep, isCacheHydrated, scanOrderModule]);
  (0, import_react.useEffect)(() => {
    var _a, _b;
    if (!scanOrderModule) return;
    let cancelled = false;
    const syncCartValidation = async () => {
      try {
        const value2 = await (0, import_hooks.safeRunModuleAction)(scanOrderModule, "getCartValidation");
        if (!cancelled) {
          setCartValidation({
            passed: typeof (value2 == null ? void 0 : value2.passed) === "boolean" || (value2 == null ? void 0 : value2.passed) === null ? value2.passed : null,
            failures: Array.isArray(value2 == null ? void 0 : value2.failures) ? value2.failures : []
          });
        }
      } catch (error) {
        if (!cancelled) {
          setCartValidation({
            passed: null,
            failures: []
          });
        }
      }
    };
    const onCartValidationChanged = (payload) => {
      const nextValue = payload == null ? void 0 : payload.cartValidation;
      setCartValidation({
        passed: typeof (nextValue == null ? void 0 : nextValue.passed) === "boolean" || (nextValue == null ? void 0 : nextValue.passed) === null ? nextValue.passed : typeof (payload == null ? void 0 : payload.cartValidationPassed) === "boolean" ? payload.cartValidationPassed : null,
        failures: Array.isArray(nextValue == null ? void 0 : nextValue.failures) ? nextValue.failures : []
      });
    };
    void syncCartValidation();
    (_b = (_a = pisellOS == null ? void 0 : pisellOS.effects) == null ? void 0 : _a.on) == null ? void 0 : _b.call(_a, "scanOrder:onCartValidationChanged", onCartValidationChanged);
    return () => {
      var _a2, _b2;
      cancelled = true;
      (_b2 = (_a2 = pisellOS == null ? void 0 : pisellOS.effects) == null ? void 0 : _a2.off) == null ? void 0 : _b2.call(_a2, "scanOrder:onCartValidationChanged", onCartValidationChanged);
    };
  }, [pisellOS, scanOrderModule]);
  (0, import_react.useEffect)(() => {
    let unmounted = false;
    const bootstrap = async () => {
      try {
        if (!scanOrderModule) {
          setErrorMessage("scanOrder module not ready");
          setIsLoading(false);
          return;
        }
        const canEnter = typeof scanOrderModule.checkAccess === "function" ? await scanOrderModule.checkAccess(entryContext) : true;
        if (!canEnter) {
          throw new Error("scanOrder access denied");
        }
        if (typeof scanOrderModule.getPageConfig === "function") {
          await scanOrderModule.getPageConfig(entryContext);
        }
        await refreshViewModel();
        if (!unmounted) {
          setErrorMessage("");
          setIsLoading(false);
        }
      } catch (error) {
        if (!unmounted) {
          setErrorMessage((error == null ? void 0 : error.message) || "scanOrder load failed");
          setIsLoading(false);
        }
      }
    };
    bootstrap();
    return () => {
      unmounted = true;
    };
  }, [scanOrderModule, entryContext == null ? void 0 : entryContext.biz, entryContext == null ? void 0 : entryContext.resource_id]);
  const value = (0, import_react.useMemo)(() => {
    return {
      entryContext,
      scanOrderModule,
      cartValidation,
      isLoading,
      errorMessage,
      currentStep,
      stepList,
      viewModel,
      footerActionText,
      tableName,
      entryMode,
      submitDisabledTips,
      discountList,
      isReady: !isLoading && !errorMessage,
      setCurrentStep,
      goToStep,
      nextStep,
      prevStep,
      refreshViewModel,
      runModuleAction,
      setFooterActionText,
      setTableName,
      setEntryMode,
      setSubmitDisabledTips,
      updateOrderNote,
      isCacheHydrated,
      markGate,
      isGatePassed,
      clearStepCache,
      resumeStep,
      consumeResumeStep
    };
  }, [
    entryContext,
    scanOrderModule,
    cartValidation,
    isLoading,
    errorMessage,
    currentStep,
    stepList,
    viewModel,
    footerActionText,
    tableName,
    entryMode,
    submitDisabledTips,
    discountList,
    isCacheHydrated,
    markGate,
    isGatePassed,
    clearStepCache,
    resumeStep,
    consumeResumeStep
  ]);
  return /* @__PURE__ */ import_react.default.createElement(ScanOrderContext.Provider, { value }, children);
}
function useScanOrderContext() {
  const context = (0, import_react.useContext)(ScanOrderContext);
  if (context) return context;
  throw new Error("useScanOrderContext must be used within ScanOrderProvider");
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ScanOrderProvider,
  useScanOrderContext
});
