"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Rates = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _services = require("@mirai/services");
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 _hooks = require("./hooks");
var _Rates = require("./Rates.constants");
var _Rates2 = require("./Rates.Content");
var _Rates3 = require("./Rates.Footer");
var _Rates4 = require("./Rates.Header");
var _Rates5 = require("./Rates.l10n");
var style = _interopRequireWildcard(require("./Rates.module.css"));
var _Rates6 = require("./Rates.RoomSelector");
var _Rates7 = _interopRequireDefault(require("./Rates.Skeleton"));
var _Rates8 = require("./Rates.Unavailability");
var _Core = require("../../Core.constants");
var _helpers2 = require("../../helpers");
var _shared__ = require("../__shared__");
var _Finder = require("../Finder");
var _Header = require("../Header");
var _helpers3 = require("../helpers");
const _excluded = ["testId"],
  _excluded2 = ["id"];
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 Rates = _ref => {
  var _dataSource$hotels, _responseError$tracki, _responseError$tracki2, _responseError$tracki3, _dataSource$items;
  let {
      testId
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    isDesktop,
    isMobile,
    width
  } = (0, _ui.useDevice)();
  const {
    actions,
    device,
    fetch,
    multiRoom,
    refRoomSelector,
    responseError,
    state
  } = (0, _hooks.useRates)();
  const {
    set,
    value: {
      club,
      currency,
      finder = {},
      forwarder,
      hotel = {},
      id,
      language,
      locale,
      session,
      skeleton = false,
      urlParams = {},
      variant
    }
  } = (0, _dataSources.useStore)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const refItems = (0, _react.useRef)({});
  const ratesMetricsSent = (0, _react.useRef)(false);
  const [busy, setBusy] = (0, _react.useState)(false);
  const [cancellationInfo, setCancellationInfo] = (0, _react.useState)();
  const [extras, setExtras] = (0, _react.useState)();
  const [filterBoard, setFilterBoard] = (0, _react.useState)();
  const [filters, setFilters] = (0, _react.useState)({});
  const [itemInfo, setItemInfo] = (0, _react.useState)();
  const [itemUrl, setItemUrl] = (0, _react.useState)();
  const [mapView, setMapView] = (0, _react.useState)();
  const [offerInfo, setOfferInfo] = (0, _react.useState)();
  const [twinSelected, setTwinSelected] = (0, _react.useState)();
  const {
    calendar = [],
    occupation = []
  } = finder;
  const {
    cart,
    clubDiscount,
    clubRate,
    dataSource,
    fetching,
    metaBoard,
    room,
    strictSearch
  } = state;
  const {
    setCart,
    setClubRate,
    setDataSource,
    setMetaBoard,
    setRoom,
    setStrictSearch
  } = actions;
  (0, _react.useEffect)(() => {
    if (skeleton || responseError || !dataSource || ratesMetricsSent.current) return;
    _dataSources.Event.publish(_helpers3.EVENT.METRICS, _objectSpread(_objectSpread({
      id: _helpers3.METRICS_EVENTS.RATES_READY,
      multiRoom,
      variant
    }, (0, _helpers2.getSearchProps)({
      store: {
        finder,
        currency,
        language,
        locale,
        urlParams
      },
      dataSource
    })), {}, {
      is_refundable: refundable
    }));
    ratesMetricsSent.current = true;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource]);
  (0, _react.useEffect)(() => {
    if (!filterBoard) return;
    setMetaBoard(filterBoard);
    scrollToRoom(filterBoard.roomId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterBoard]);

  // -- handlers -------------------------------------------------------------------------------------------------------
  const handleFilters = function () {
    let next = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      strictSearch: nextStrictSearch
    } = next;
    setCart([]);
    setRoom(undefined);
    setFilters(next);
    if (strictSearch !== nextStrictSearch) setStrictSearch(nextStrictSearch);
  };
  const handleFinder = function () {
    let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    setCart([]);
    setDataSource(undefined);
    setRoom();
    setMetaBoard();
    scrollTo(0);
    (0, _helpers3.replaceUrlParams)((0, _helpers.getFinderParams)(_objectSpread(_objectSpread({}, values), {}, {
      hotel
    })));
    const {
      calendar: nextCalendar,
      occupation: nextOccupation,
      place: nextPlace,
      promocode: nextPromocode
    } = values;
    fetch({
      nextCalendar,
      nextOccupation,
      nextPlace,
      nextPromocode
    });
  };
  const handleSelect = (board, others) => {
    const nextCart = [...cart];
    nextCart[room || 0] = board ? _objectSpread(_objectSpread({}, board), others) : undefined;
    if (board) {
      scrollToRoom(board.roomId);
      _dataSources.Event.publish(_helpers3.EVENT.RATES_ADD_TO_CART, {
        event: _helpers3.EVENT.RATES_ADD_TO_CART,
        response: _objectSpread({
          board,
          cart: nextCart
        }, dataSource)
      });
      _dataSources.Event.publish(_helpers3.EVENT.METRICS, {
        id: _helpers3.METRICS_EVENTS.RATES_INTERACTION,
        action: 'room_selected',
        result_position: itemsFiltered.findIndex(function () {
          let {
            id
          } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
          return id === board.roomId;
        }) + 1,
        loyalty_discount_active: !!session || clubDiscount
      });
    }
    setCart(nextCart);
    setExtras();
    setMetaBoard(undefined);
    setTwinSelected();
    clubRate && setClubRate(false);
    if (!multiRoom && !!board) handleSubmit(nextCart);
    if (multiRoom) {
      if (board && room < occupation.length - 1) return setRoom(room + 1);
      if (!board) set({
        rates: undefined
      });
    }
  };
  const handleSubmit = async function (cart) {
    let sessionProp = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : session;
    const isPestana = _services.ServiceFeatures.get(_Rates.FEATURES.PESTANA, id) || false;
    setClubRate(false);
    if ((0, _helpers.showClubRate)({
      cart,
      clubDiscount,
      dataSource,
      isPestana,
      session: sessionProp,
      variant
    })) return setClubRate(true);
    const {
      extras = []
    } = (await _services.ServiceRates.extras(_objectSpread(_objectSpread(_objectSpread({}, (0, _helpers.getCheckoutParams)({
      cart,
      clubDiscount,
      currency,
      dataSource,
      forwarder,
      urlParams: (0, _helpers2.fetchUrlParams)(location.search)
    })), (0, _helpers3.getOccupationTotals)({
      infantAge: dataSource.infantAge,
      occupation
    })), {}, {
      clubDiscount: !!session || clubDiscount,
      device,
      hotelCurrency: dataSource.currency,
      locale,
      session
    })).catch(() => {})) || {};
    const selectableExtras = extras.some(function () {
      let {
        included
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return !included;
    });
    if (selectableExtras) setExtras(extras);else handleCheckout(cart, extras, variant);
  };
  const handleCheckout = function () {
    let cart = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    let selectedExtras = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    let variant = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'A';
    setBusy(true);
    _dataSources.Event.publish(_helpers3.EVENT.METRICS, {
      id: _helpers3.METRICS_EVENTS.RATES_INTERACTION,
      action: 'rates_submit',
      has_extras: (extras === null || extras === void 0 ? void 0 : extras.length) > 0
    });
    setTimeout(() => {
      setBusy(false);
      document.location.href = (0, _helpers.getForwarderUrl)({
        cart,
        clubDiscount,
        currency,
        dataSource,
        extras: selectedExtras,
        forwarder,
        meta: !!urlParams.rates,
        refundable,
        session,
        urlParams: _objectSpread(_objectSpread({}, (0, _helpers2.fetchUrlParams)(location.search)), {}, {
          device
        }),
        variant,
        occupationTotals: JSON.stringify((0, _helpers3.getOccupationTotals)({
          infantAge: dataSource.infantAge,
          occupation
        }))
      });
    }, _helpers3.SUBMIT_DELAY);
  };
  const handleTwin = roomId => {
    setFilterBoard();
    setMetaBoard();
    setTwinSelected(roomId);
  };
  const scrollTo = function () {
    let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
    return window.scrollTo({
      top: value,
      behavior: 'smooth'
    });
  };
  const scrollToRoom = roomId => {
    var _refItems$current$roo;
    const {
      top
    } = (refItems === null || refItems === void 0 ? void 0 : (_refItems$current$roo = refItems.current[roomId]) === null || _refItems$current$roo === void 0 ? void 0 : _refItems$current$roo.getBoundingClientRect()) || {};
    if (top) scrollTo(top + window.scrollY - (isMobile ? 65 : 16 * 5));
  };
  const {
    contentBackground
  } = _ui.Theme.get();
  const cardImageHeight = (0, _helpers.getCardImageHeight)();
  const {
    days: nights
  } = (0, _locale.dateDiff)(calendar[0], calendar[1]);
  const response = dataSource !== undefined;
  const roomSelectorProps = {
    cart,
    occupation,
    room,
    onPress: setRoom
  };
  const features = (0, _helpers.getFeatures)(hotel.features, urlParams, {
    isDesktop
  });
  const priceFactor = features.showPricePerNight && nights > 1 ? nights : 1;
  const uniqueOption = ((dataSource === null || dataSource === void 0 ? void 0 : dataSource.items) || []).filter(function () {
    let {
      soldOut
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return !soldOut;
  }).every(_ref2 => {
    let {
      boards = [],
      cancellations = [],
      rates = []
    } = _ref2;
    return boards.length === 1 && cancellations.length === 1 && rates.length === 1;
  });
  const itemsFiltered = (0, _helpers.select)(dataSource === null || dataSource === void 0 ? void 0 : dataSource.items, filters, {
    priceFactor
  });
  const refundable = (0, _helpers2.getRefundableFromItems)(dataSource === null || dataSource === void 0 ? void 0 : dataSource.items);
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Header.Header, {
    currency: true,
    login: !!club,
    name: features.showNameInHeader,
    skeleton: skeleton
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    ref: refRoomSelector,
    className: (0, _ui.styles)(style.finder, style.blur, (!multiRoom || responseError) && style.sticky),
    style: !isMobile ? {
      backgroundColor: (0, _helpers3.opacity)(contentBackground, 0.66)
    } : undefined
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: isMobile,
    className: style.wrapper
  }, /*#__PURE__*/_react.default.createElement(_Finder.Finder, {
    compacted: !isDesktop,
    icon: true,
    onSubmit: handleFinder,
    testId: testId ? "".concat(testId, "-finder") : undefined
  }), !responseError && (dataSource === null || dataSource === void 0 ? void 0 : dataSource.items) && /*#__PURE__*/_react.default.createElement(_components.Filters, _extends({}, dataSource, {
    clubDiscount,
    values: filters,
    priceFactor,
    onSubmit: handleFilters
  })))), /*#__PURE__*/_react.default.createElement(_ui.Progress, {
    indeterminate: true,
    visible: fetching && !responseError,
    className: style.progress
  }), isMobile && !responseError && /*#__PURE__*/_react.default.createElement(_Rates6.RoomSelector, _extends({}, roomSelectorProps, {
    testId: testId ? "".concat(testId, "-multiroom") : undefined
  })), /*#__PURE__*/_react.default.createElement(_ui.View, {
    role: "rates",
    testId: testId,
    className: (0, _ui.styles)(style.container, others.className)
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: [style.wrapper, style.content]
  }, !responseError && /*#__PURE__*/_react.default.createElement(_Rates2.Content, _extends({}, dataSource, others, {
    skeleton: skeleton
  })), (response || multiRoom && !responseError) && /*#__PURE__*/_react.default.createElement(_Rates4.Header, {
    dataSource,
    filters,
    multiRoom,
    priceFactor,
    onMapView: setMapView,
    onSelect: handleSelect
  }, !isMobile ? /*#__PURE__*/_react.default.createElement(_Rates6.RoomSelector, _extends({}, roomSelectorProps, {
    testId: testId ? "".concat(testId, "-multiroom") : undefined
  })) : undefined), response ? /*#__PURE__*/_react.default.createElement(_shared__.Cards, null, itemsFiltered === null || itemsFiltered === void 0 ? void 0 : itemsFiltered.map((_ref3, index) => {
    let {
        id
      } = _ref3,
      item = _objectWithoutProperties(_ref3, _excluded2);
    return /*#__PURE__*/_react.default.createElement(_components.Item, _extends({}, _objectSpread(_objectSpread({}, (0, _helpers.filterItem)(item, filters, priceFactor)), {}, {
      cardImageHeight,
      cart,
      features,
      filters,
      metaBoard,
      id,
      resultPosition: index + 1,
      multiRoom,
      nights,
      priceFactor,
      room,
      taxesType: dataSource.taxesType,
      uniqueOption
    }), {
      key: "".concat(id || index, ":").concat(fetching, ":").concat(width),
      ref: el => refItems.current[id] = el,
      selected: cart[room || 0],
      onCancellationInfo: rate => setCancellationInfo(_objectSpread(_objectSpread({}, rate), {}, {
        name: item.name
      })),
      onMoreInfo: () => setItemInfo(item),
      onOfferInfo: rate => setOfferInfo(rate),
      onSelect: handleSelect,
      onTwin: handleTwin,
      onViewUrl: info => setItemUrl(info),
      testId: testId ? "".concat(testId, "-item-").concat(index) : undefined
    }));
  }), (_dataSource$hotels = dataSource.hotels) === null || _dataSource$hotels === void 0 ? void 0 : _dataSource$hotels.map(function () {
    let item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return /*#__PURE__*/_react.default.createElement(_components.CardHotel, _extends({
      key: item.id
    }, _objectSpread(_objectSpread({}, item), {}, {
      cardImageHeight,
      nights,
      priceFactor
    })));
  })) : responseError ? responseError.hotel || ((_responseError$tracki = responseError.tracking) === null || _responseError$tracki === void 0 ? void 0 : (_responseError$tracki2 = _responseError$tracki.hotelInfoBAR) === null || _responseError$tracki2 === void 0 ? void 0 : _responseError$tracki2.length) === 0 || (_responseError$tracki3 = responseError.tracking) !== null && _responseError$tracki3 !== void 0 && _responseError$tracki3.hotelInfoBAR[0].noAvailableReason ? /*#__PURE__*/_react.default.createElement(_Rates8.Unavailability, _extends({}, _objectSpread(_objectSpread({}, responseError), {}, {
    nights,
    priceFactor
  }), {
    onMapView: setMapView
  })) : /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: true,
    large: true,
    className: style.error
  }, translate(_Rates5.L10N.NOTIFICATION_ERROR[responseError.code || _Core.ERROR.UNKNOWN])) : /*#__PURE__*/_react.default.createElement(_Rates7.default, {
    multiRoom: multiRoom
  })), /*#__PURE__*/_react.default.createElement(_Rates3.Footer, {
    cart: multiRoom ? cart : [],
    clubRate,
    dataSource,
    extras,
    multiRoom,
    occupation,
    onSubmit: () => multiRoom ? handleSubmit(cart) : undefined,
    testId: testId ? "".concat(testId, "-footer") : undefined
  })), response && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_components.ModalItemInfo, _extends({}, _objectSpread(_objectSpread({}, itemInfo), {}, {
    features,
    room
  }), {
    visible: !!itemInfo,
    onClose: () => setItemInfo(),
    onViewUrl: info => setItemUrl(info)
  })), /*#__PURE__*/_react.default.createElement(_components.ModalCancellationInfo, _extends({}, cancellationInfo, {
    visible: !!cancellationInfo,
    onClose: () => setCancellationInfo()
  })), /*#__PURE__*/_react.default.createElement(_components.ModalItemUrl, _extends({}, itemUrl, {
    visible: !!itemUrl,
    onClose: () => setItemUrl()
  })), /*#__PURE__*/_react.default.createElement(_components.ModalOfferInfo, _extends({}, _objectSpread({}, offerInfo), {
    visible: !!offerInfo,
    onClose: () => setOfferInfo()
  })), /*#__PURE__*/_react.default.createElement(_components.ModalTwin, _extends({}, _objectSpread(_objectSpread({}, itemInfo), {}, {
    clubDiscount,
    dataSource,
    cart,
    features,
    filters,
    nights,
    priceFactor,
    room,
    selected: twinSelected
  }), {
    onBook: handleSelect,
    onClose: () => setTwinSelected(),
    onFilter: handleFilters,
    onSelect: setFilterBoard
  })), /*#__PURE__*/_react.default.createElement(_components.ModalExtras, _extends({}, _objectSpread(_objectSpread({}, dataSource), {}, {
    busy,
    cart,
    extras
  }), {
    visible: !!extras,
    onCancel: () => multiRoom ? setExtras() : handleSelect(),
    onSubmit: extras => handleCheckout(cart, extras, variant),
    testId: testId ? "".concat(testId, "-modalExtras") : undefined
  })), (club === null || club === void 0 ? void 0 : club.active) && ((_dataSource$items = dataSource.items) === null || _dataSource$items === void 0 ? void 0 : _dataSource$items.length) > 0 && /*#__PURE__*/_react.default.createElement(_components.ModalClubRate, {
    dataSource: dataSource,
    cart: cart,
    visible: clubRate,
    onSubmit: session => handleSubmit(cart, session)
  })), /*#__PURE__*/_react.default.createElement(_components.ModalMapView, {
    items: mapView,
    nights: nights,
    visible: !!mapView,
    onClose: () => setMapView()
  }), /*#__PURE__*/_react.default.createElement(_shared__.Footer, null));
};
exports.Rates = Rates;
Rates.displayName = 'Mirai:Core:Rates';
Rates.propTypes = {
  testId: _propTypes.default.string
};
//# sourceMappingURL=Rates.js.map