"use strict";

var _dataSources = require("@mirai/data-sources");
var _services = require("@mirai/services");
var _react = _interopRequireDefault(require("react"));
var _client = require("react-dom/client");
var _contexts = require("./contexts");
var _Core = require("./Core");
var _Core2 = require("./Core.constants");
var _Core3 = require("./Core.ErrorBoundary");
var _helpers = require("./helpers");
var _package = require("../package.json");
require("./helpers/polyfills");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint-disable no-console */
window.Mirai = _objectSpread(_objectSpread({}, window.Mirai), {}, {
  components: undefined,
  config: undefined,
  environment: process.env.NODE_ENV,
  Event: _dataSources.Event,
  services: {
    booking: process.env.SERVICE_BOOKING,
    club: process.env.SERVICE_CLUB,
    dictionary: process.env.SERVICE_DICTIONARY,
    engine: process.env.SERVICE_ENGINE,
    static: process.env.SERVICE_STATIC,
    user: process.env.SERVICE_USER
  },
  trackError: _helpers.trackError,
  version: _package.version
});
let memoizedRoot;
window.Mirai.core = async () => {
  if (memoizedRoot) memoizedRoot.unmount();
  _dataSources.Event.publish(_Core2.EVENT.CORE_EVENTS_READY);
  const isProduction = process.env.NODE_ENV === 'production';
  const isDevelopment = process.env.NODE_ENV === 'development';
  const isPreproduction = process.env.NODE_ENV === 'preproduction';
  const log = "".concat(isProduction ? '🟢' : isPreproduction ? '🟡' : isDevelopment ? '🔴' : '⚫️', " ").concat(_package.name, " v").concat(_package.version);
  console.log(log, 'starting...');

  // 1. Find instance
  const urlParams = (0, _helpers.fetchUrlParams)(location.search);
  //Compatibility with 123 compare
  window.Mirai.urlParameters = urlParams;
  const instance = (0, _helpers.findInstance)({
    urlParams
  });
  if (!instance) return;

  // 2. Fetch client-side dataSources
  const cookies = (0, _helpers.fetchCookies)(Object.values(_Core2.COOKIE));
  let session = (0, _helpers.fetchSession)(urlParams);

  // 3. Analyze environment
  const environment = urlParams.env && isProduction ? (0, _helpers.loadEnvironment)(urlParams.env) : undefined;
  if (environment) return;

  // 4. Find components
  const components = (0, _helpers.findComponents)(_objectSpread(_objectSpread({}, instance), urlParams));
  window.Mirai = _objectSpread(_objectSpread({}, window.Mirai), {}, {
    components
  });

  // 5. Theming
  (0, _helpers.theme)(urlParams);
  const localeInstance = (0, _helpers.getLocale)(instance, urlParams);
  memoizedRoot = (0, _client.createRoot)(instance.el);
  // 7. 1st render
  window && !window.IS_PLAYWRIGHT && memoizedRoot.render(/*#__PURE__*/_react.default.createElement(_react.default.StrictMode, null, /*#__PURE__*/_react.default.createElement(_dataSources.StoreProvider, {
    value: _objectSpread({
      id: instance.id,
      session,
      skeleton: true,
      type: instance.type,
      urlParams
    }, localeInstance)
  }, /*#__PURE__*/_react.default.createElement(_Core.Core, {
    components
  }))));

  // 8. Analyze id to fetch its config
  const config = await (0, _helpers.fetchConfig)(_objectSpread(_objectSpread({}, instance), {}, {
    language: localeInstance.language
  }));
  if (!config) return;
  window.Mirai.config = config;

  // 8. Check session
  if (session && !(await (0, _helpers.checkSession)(instance.id, session, config))) session = undefined;
  if (urlParams.hsri == _Core2.SYNAPSE_COMMISSION_CODE && urlParams.fingerprint) {
    var _localStorage;
    (_localStorage = localStorage) === null || _localStorage === void 0 ? void 0 : _localStorage.setItem('MIRAI:FINGERPRINT', urlParams.fingerprint);
  }

  // 9. Fetch external session
  session = await (0, _helpers.fetchExternalSession)({
    config,
    cookies,
    session
  });

  // 10. Consolidate store
  const store = await (0, _helpers.consolidateStore)({
    components,
    config,
    cookies,
    instance,
    session,
    urlParams
  });

  // 11. Initialize features
  await _services.ServiceFeatures.initialize();

  // 12. Initialize dictionary
  if (!_services.ServiceDictionary.cache(store.locale)) await _services.ServiceDictionary.get(store.locale, false);

  // 13. Render components
  memoizedRoot.unmount();
  memoizedRoot = (0, _client.createRoot)(instance.el);
  memoizedRoot.render(/*#__PURE__*/_react.default.createElement(_react.default.StrictMode, null, /*#__PURE__*/_react.default.createElement(_Core3.ErrorBoundary, null, /*#__PURE__*/_react.default.createElement(_dataSources.MetricsProvider, {
    token: !urlParams.disableMetrics ? process.env.METRICS : undefined
  }, /*#__PURE__*/_react.default.createElement(_dataSources.StoreProvider, {
    value: store
  }, /*#__PURE__*/_react.default.createElement(_contexts.PerformanceManager, null), /*#__PURE__*/_react.default.createElement(_Core.Core, {
    components
  }), /*#__PURE__*/_react.default.createElement(_contexts.EventManager, null))))));

  // 14. Up & Ready
  window.Mirai.ready = true;
  setTimeout(() => _dataSources.Event.publish(_Core2.EVENT.CORE_READY, window.Mirai), 0);
  console.log(log, '[READY]', window.Mirai);
};
(async () => {
  try {
    !window.ON_DEMAND_INIT && (await window.Mirai.core());
  } catch (error) {
    (0, _helpers.trackError)((error === null || error === void 0 ? void 0 : error.message) || 'core:init', error === null || error === void 0 ? void 0 : error.stack);
    throw error;
  }
  const {
    components = [],
    ready
  } = window.Mirai;
  if (ready && components.filter(function () {
    let {
      component
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return ['booking', 'checkout', 'rates'].includes(component).length;
  })) {
    window.addEventListener('pageshow', event => event.persisted && window.Mirai.core());
  }
})();
//# sourceMappingURL=index.js.map