"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 _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,
      filters,
      priceFactor,
      selected,
      onClose = () => {},
      onFilter = () => {},
      onSelect = () => {}
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    translate
  } = (0, _locale.useLocale)();
  const {
    isMobile
  } = (0, _ui.useDevice)();
  const {
    value: {
      currency,
      finder = {},
      finder: {
        place: {
          id: [hotelId] = [],
          isHotel
        } = {}
      } = {},
      hotel = {},
      language,
      locale,
      urlParams
    } = {}
  } = (0, _dataSources.useStore)();
  const iframeRef = (0, _react.useRef)();
  const itemsRef = (0, _react.useRef)([]);
  const [expanded, setExpanded] = (0, _react.useState)();
  const [loaded, setLoaded] = (0, _react.useState)();
  const [scrollTo, setScrollTo] = (0, _react.useState)();
  const [selectedId, setSelectedId] = (0, _react.useState)();
  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;
      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 {
        data: {
          isLoaded,
          roomId
        } = {}
      } = event;
      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 {
          id
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        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 {
        id
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      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];
    if (id !== selectedId) {
      var _iframeRef$current, _iframeRef$current$co;
      setSelectedId(id);
      iframeRef === null || iframeRef === void 0 ? void 0 : (_iframeRef$current = iframeRef.current) === null || _iframeRef$current === void 0 ? void 0 : (_iframeRef$current$co = _iframeRef$current.contentWindow) === null || _iframeRef$current$co === void 0 ? void 0 : _iframeRef$current$co.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, _iframeRef$current2$c;
    if (!filters || Object.keys(filters).length === 0) return;
    iframeRef === null || iframeRef === void 0 ? void 0 : (_iframeRef$current2 = iframeRef.current) === null || _iframeRef$current2 === void 0 ? void 0 : (_iframeRef$current2$c = _iframeRef$current2.contentWindow) === null || _iframeRef$current2$c === void 0 ? void 0 : _iframeRef$current2$c.postMessage({
      rooms: filteredItems.filter(function () {
        let {
          soldOut
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return !soldOut;
      }).map(function () {
        let {
          id
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return id;
      }),
      soldOutRooms: filteredItems.filter(function () {
        let {
          soldOut
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return soldOut;
      }).map(function () {
        let {
          id
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        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 {
    items = []
  } = dataSource || {};
  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 {
      id
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    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