"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ModalTwin = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _components = require("./components");
var _helpers = require("./helpers");
var _ModalTwin = require("./ModalTwin.l10n");
var style = _interopRequireWildcard(require("./ModalTwin.module.css"));
var _ModalTwin2 = require("./ModalTwin.Skeleton");
var _helpers2 = require("../../../../helpers");
var _helpers3 = require("../../../helpers");
var _helpers4 = require("../../helpers");
var _Filters = require("../Filters");
const _excluded = ["dataSource", "filters", "priceFactor", "selected", "onClose", "onFilter", "onSelect"];
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
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); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
const ModalTwin = _ref => {
  var _select;
  let dataSource = _ref.dataSource,
    filters = _ref.filters,
    priceFactor = _ref.priceFactor,
    selected = _ref.selected,
    _ref$onClose = _ref.onClose,
    onClose = _ref$onClose === void 0 ? () => {} : _ref$onClose,
    _ref$onFilter = _ref.onFilter,
    onFilter = _ref$onFilter === void 0 ? () => {} : _ref$onFilter,
    _ref$onSelect = _ref.onSelect,
    onSelect = _ref$onSelect === void 0 ? () => {} : _ref$onSelect,
    others = _objectWithoutProperties(_ref, _excluded);
  const _useLocale = (0, _locale.useLocale)(),
    translate = _useLocale.translate;
  const _useDevice = (0, _ui.useDevice)(),
    isMobile = _useDevice.isMobile;
  const _useStore = (0, _dataSources.useStore)(),
    _useStore$value = _useStore.value,
    _useStore$value2 = _useStore$value === void 0 ? {} : _useStore$value,
    currency = _useStore$value2.currency,
    _useStore$value2$find = _useStore$value2.finder,
    finder = _useStore$value2$find === void 0 ? {} : _useStore$value2$find,
    _useStore$value2$find2 = _useStore$value2.finder,
    _useStore$value2$find3 = _useStore$value2$find2 === void 0 ? {} : _useStore$value2$find2,
    _useStore$value2$find4 = _useStore$value2$find3.place,
    _useStore$value2$find5 = _useStore$value2$find4 === void 0 ? {} : _useStore$value2$find4,
    _useStore$value2$find6 = _useStore$value2$find5.id,
    _useStore$value2$find7 = _useStore$value2$find6 === void 0 ? [] : _useStore$value2$find6,
    _useStore$value2$find8 = _slicedToArray(_useStore$value2$find7, 1),
    hotelId = _useStore$value2$find8[0],
    isHotel = _useStore$value2$find5.isHotel,
    _useStore$value2$hote = _useStore$value2.hotel,
    hotel = _useStore$value2$hote === void 0 ? {} : _useStore$value2$hote,
    language = _useStore$value2.language,
    locale = _useStore$value2.locale,
    urlParams = _useStore$value2.urlParams;
  const iframeRef = (0, _react.useRef)();
  const itemsRef = (0, _react.useRef)([]);
  const _useState = (0, _react.useState)(),
    _useState2 = _slicedToArray(_useState, 2),
    expanded = _useState2[0],
    setExpanded = _useState2[1];
  const _useState3 = (0, _react.useState)(),
    _useState4 = _slicedToArray(_useState3, 2),
    loaded = _useState4[0],
    setLoaded = _useState4[1];
  const _useState5 = (0, _react.useState)(),
    _useState6 = _slicedToArray(_useState5, 2),
    scrollTo = _useState6[0],
    setScrollTo = _useState6[1];
  const _useState7 = (0, _react.useState)(),
    _useState8 = _slicedToArray(_useState7, 2),
    selectedId = _useState8[0],
    setSelectedId = _useState8[1];
  const loadStartRef = (0, _react.useRef)();
  const loadedTrackedRef = (0, _react.useRef)(false);
  const selectedByUserRef = (0, _react.useRef)(false);
  (0, _react.useEffect)(() => {
    const callback = _ref2 => {
      let displayName = _ref2.displayName;
      if (displayName !== ModalTwin.displayName) {
        selected && _dataSources.Event.publish(_helpers3.EVENT.MODAL_VISIBLE, {
          displayName: ModalTwin.displayName,
          visible: true
        });
      }
    };
    _dataSources.Event.subscribe(_helpers3.EVENT.MODAL_VISIBLE, callback);
    return () => _dataSources.Event.unsubscribe(_helpers3.EVENT.MODAL_VISIBLE, callback);
  }, [selected]);
  (0, _react.useEffect)(() => {
    const callback = function () {
      let event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      if (!event || !event.data || event.origin !== process.env.TWIN_URL) return;
      const _event$data = event.data,
        _event$data2 = _event$data === void 0 ? {} : _event$data,
        isLoaded = _event$data2.isLoaded,
        roomId = _event$data2.roomId;
      debounceSelectId(roomId);
      if (roomId) {
        _dataSources.Event.publish(_helpers3.EVENT.METRICS, {
          id: _helpers3.METRICS_EVENTS.THREE_D_INTERACTION,
          action: 'change_room',
          method: 'map'
        });
      }
      if (isLoaded && !loadedTrackedRef.current) {
        const loadTime = loadStartRef.current ? Math.round(performance.now() - loadStartRef.current) : undefined;
        _dataSources.Event.publish(_helpers3.EVENT.METRICS, {
          id: _helpers3.METRICS_EVENTS.THREE_D_INTERACTION,
          action: 'loaded',
          load_time_ms: loadTime
        });
        loadedTrackedRef.current = true;
        setLoaded(true);
      }
    };
    if (!isMobile && selectedId) setTimeout(() => {
      var _itemsRef$current$sel;
      return setScrollTo(((_itemsRef$current$sel = itemsRef.current[selectedId]) === null || _itemsRef$current$sel === void 0 ? void 0 : _itemsRef$current$sel.offsetTop) - 74);
    }, 400);
    window.addEventListener('message', callback);
    return () => window.removeEventListener('message', callback);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedId]);
  (0, _react.useEffect)(() => {
    setExpanded();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource, selected]);
  (0, _react.useEffect)(() => {
    if (!loaded) return;
    setTimeout(() => {
      handleFilters();
      const selectedIndex = filteredItems.findIndex(function () {
        let _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          id = _ref3.id;
        return id === selected;
      });
      handleChange(selectedIndex !== -1 ? selectedIndex : 0);
    }, 1500);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loaded]);
  (0, _react.useEffect)(() => {
    if (!handleFilters()) return;
    const selectedIndex = filteredItems.findIndex(function () {
      let _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        id = _ref4.id;
      return id === selectedId;
    });
    if (selectedIndex === -1) handleChange(0);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters]);
  const handleChange = index => {
    if (index < 0 || index === selectedIndex || index >= filteredItems.length) return;
    const id = filteredItems[index].id;
    if (id !== selectedId) {
      var _iframeRef$current;
      setSelectedId(id);
      iframeRef === null || iframeRef === void 0 || (_iframeRef$current = iframeRef.current) === null || _iframeRef$current === void 0 || (_iframeRef$current = _iframeRef$current.contentWindow) === null || _iframeRef$current === void 0 || _iframeRef$current.postMessage({
        roomId: id
      }, process.env.TWIN_URL);
      _dataSources.Event.publish(_helpers3.EVENT.METRICS, {
        id: _helpers3.METRICS_EVENTS.THREE_D_INTERACTION,
        action: 'change_room',
        method: 'card'
      });
    }
  };
  const handleClose = () => {
    setSelectedId();
    setLoaded();
    setExpanded();
    setScrollTo();
    if (!selectedByUserRef.current) {
      _dataSources.Event.publish(_helpers3.EVENT.METRICS, {
        id: _helpers3.METRICS_EVENTS.THREE_D_INTERACTION,
        action: 'close'
      });
    }
    onClose();
  };
  const handleFilters = () => {
    var _iframeRef$current2;
    if (!filters || Object.keys(filters).length === 0) return;
    iframeRef === null || iframeRef === void 0 || (_iframeRef$current2 = iframeRef.current) === null || _iframeRef$current2 === void 0 || (_iframeRef$current2 = _iframeRef$current2.contentWindow) === null || _iframeRef$current2 === void 0 || _iframeRef$current2.postMessage({
      rooms: filteredItems.filter(function () {
        let _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          soldOut = _ref5.soldOut;
        return !soldOut;
      }).map(function () {
        let _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          id = _ref6.id;
        return id;
      }),
      soldOutRooms: filteredItems.filter(function () {
        let _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          soldOut = _ref7.soldOut;
        return soldOut;
      }).map(function () {
        let _ref8 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          id = _ref8.id;
        return id;
      })
    }, process.env.TWIN_URL);
  };
  const handleSelect = id => {
    var _filteredItems$find;
    selectedByUserRef.current = true;
    _dataSources.Event.publish(_helpers3.EVENT.METRICS, {
      id: _helpers3.METRICS_EVENTS.THREE_D_INTERACTION,
      action: 'select'
    });
    onSelect((_filteredItems$find = filteredItems.find(item => item.id === id)) === null || _filteredItems$find === void 0 ? void 0 : _filteredItems$find.boards[0]);
    handleClose(false);
  };
  const handleSubmitFilter = () => {
    onFilter();
  };
  const debounceSelectId = (0, _helpers2.debounce)(roomId => {
    if (roomId && Number(roomId) !== selectedId) {
      setSelectedId(Number(roomId));
    }
  });
  const _ref9 = dataSource || {},
    _ref9$items = _ref9.items,
    items = _ref9$items === void 0 ? [] : _ref9$items;
  const filteredItems = ((_select = (0, _helpers4.select)(items, filters, {
    priceFactor
  })) === null || _select === void 0 ? void 0 : _select.map(item => (0, _helpers4.filterItem)(item, filters, priceFactor))) || [];
  const selectedIndex = selectedId ? filteredItems.findIndex(function () {
    let _ref0 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      id = _ref0.id;
    return id === selectedId;
  }) : undefined;
  const url = (0, _react.useMemo)(() => (0, _helpers.getUrl)({
    filteredItems,
    hotel,
    hotelId,
    isHotel,
    items,
    language
  }),
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [hotel, hotelId, isHotel, language]);
  (0, _react.useEffect)(() => {
    if (!selected) return;
    loadStartRef.current = performance.now();
    loadedTrackedRef.current = false;
    selectedByUserRef.current = false;
    _dataSources.Event.publish(_helpers3.EVENT.METRICS, {
      id: _helpers3.METRICS_EVENTS.THREE_D_INTERACTION,
      action: 'open'
    });
  }, [currency, dataSource, finder, language, locale, selected, urlParams]);
  return /*#__PURE__*/_react.default.createElement(_ui.Modal, _extends({}, others, {
    displayName: ModalTwin.displayName,
    fit: true,
    preventDefault: false,
    title: translate(_ModalTwin.L10N.LABEL_IMMERSIVE_BOOKING),
    visible: !!selected,
    onClose: handleClose,
    onOverflow: handleClose,
    className: style.modal
  }), /*#__PURE__*/_react.default.createElement(isMobile ? _react.default.Fragment : _ui.View, !isMobile ? {
    className: style.container,
    row: true
  } : undefined, /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, !isMobile && (loaded ? /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.panel
  }, /*#__PURE__*/_react.default.createElement(_ui.ScrollView, {
    horizontal: false,
    scrollIndicator: true,
    scrollTo: scrollTo,
    snap: false,
    className: style.scrollview
  }, filteredItems.map(function () {
    let item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    let index = arguments.length > 1 ? arguments[1] : undefined;
    return /*#__PURE__*/_react.default.createElement(_ui.View, {
      key: item.id,
      ref: el => itemsRef.current[item.id] = el
    }, selectedId === item.id ? /*#__PURE__*/_react.default.createElement(_components.CardExpanded, _extends({}, _objectSpread({
      item,
      priceFactor
    }, others), {
      onSelect: handleSelect,
      className: (0, _ui.styles)(style.card)
    })) : /*#__PURE__*/_react.default.createElement(_components.CardReduced, _extends({}, _objectSpread({
      item,
      priceFactor
    }, others), {
      onPress: () => handleChange(index)
    })));
  }))) : /*#__PURE__*/_react.default.createElement(_ModalTwin2.ModalTwinSkeleton, null)), /*#__PURE__*/_react.default.createElement(_ui.View, {
    tag: "iframe",
    ref: iframeRef,
    src: url,
    title: "modal",
    className: style.iframe
  }))), loaded && /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.filters
  }, /*#__PURE__*/_react.default.createElement(_Filters.Filters, _extends({}, dataSource, _objectSpread({
    values: filters,
    priceFactor
  }, others), {
    onSubmit: handleSubmitFilter
  }))), loaded && selectedId !== undefined && isMobile && /*#__PURE__*/_react.default.createElement(_components.Slider, {
    index: selectedIndex,
    onChange: handleChange,
    className: !expanded && style.reduced
  }, filteredItems.map(function () {
    let item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    let index = arguments.length > 1 ? arguments[1] : undefined;
    const last = index === filteredItems.length - 1;
    return /*#__PURE__*/_react.default.createElement(_ui.View, {
      key: item.id,
      className: style.item
    }, /*#__PURE__*/_react.default.createElement(_components.CardReduced, _extends({}, _objectSpread({
      item,
      last,
      priceFactor
    }, others), {
      visible: !expanded,
      onPress: () => !expanded && setExpanded(true)
    })), /*#__PURE__*/_react.default.createElement(_components.CardExpanded, _extends({}, _objectSpread({
      item,
      last,
      priceFactor
    }, others), {
      visible: expanded,
      onReduce: () => setExpanded(false),
      onSelect: handleSelect
    })));
  })));
};
exports.ModalTwin = ModalTwin;
ModalTwin.propTypes = {
  dataSource: _propTypes.default.object,
  filters: _propTypes.default.object,
  priceFactor: _propTypes.default.number,
  selected: _propTypes.default.number,
  onClose: _propTypes.default.func,
  onFilter: _propTypes.default.func,
  onSelect: _propTypes.default.func
};
ModalTwin.displayName = 'Mirai:Core:Rates:ModalTwin';
//# sourceMappingURL=ModalTwin.js.map