"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.OTAPrices = 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 _OTAPrices = require("./OTAPrices.l10n");
var style = _interopRequireWildcard(require("./OTAPrices.module.css"));
var _Core = require("../../../../Core.constants");
var _shared__ = require("../../../__shared__");
var _helpers = require("../../../helpers");
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 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 _objectDestructuringEmpty(t) { if (null == t) throw new TypeError("Cannot destructure " + t); }
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); }
const MIN_VIEW_TIME_MS = 1200;
const SESSION_STORAGE_KEY = 'MIRAI:PRICE_COMP:VIEWED';
const getSessionViewed = () => {
  try {
    return sessionStorage.getItem(SESSION_STORAGE_KEY) === 'true';
  } catch (_unused) {
    return false;
  }
};
const setSessionViewed = () => {
  try {
    sessionStorage.setItem(SESSION_STORAGE_KEY, 'true');
  } catch (_unused2) {
    return undefined;
  }
};
const OTAPrices = _ref => {
  let others = _extends({}, (_objectDestructuringEmpty(_ref), _ref));
  const {
    isMobile
  } = (0, _ui.useDevice)();
  const {
    currency,
    locale,
    translate
  } = (0, _locale.useLocale)();
  const ref = (0, _react.useRef)(null);
  const {
    value: {
      finder: {
        calendar,
        occupation,
        place,
        promocode
      } = {},
      variant
    } = {}
  } = (0, _dataSources.useStore)();
  const [dataSource, setDataSource] = (0, _react.useState)();
  const [fetching, setFetching] = (0, _react.useState)(true);
  const [otas, setOtas] = (0, _react.useState)([]);
  const loadStartRef = (0, _react.useRef)(performance.now());
  const loadedTrackedRef = (0, _react.useRef)(false);
  const viewTrackedRef = (0, _react.useRef)(false);
  const viewTimerRef = (0, _react.useRef)();
  (0, _react.useEffect)(() => {
    if (process.env.NODE_ENV === 'development') {
      localStorage.setItem('cmprm_screens_override', '[{ "type": "StartsWith", "path": "http://local.mirai.com:8080", "id_screen": 1233 }]');
    }
    const handleHeaderReady = event => {
      const {
        detail: {
          currency,
          is_hide: disabled = false,
          price
        } = {}
      } = event;
      if (disabled) {
        window.removeEventListener('cmprm_event_rc_header_ready', handleHeaderReady);
        window.removeEventListener('cmprm_event_rc_ota_ready', handleOTAReady);
      }
      setDataSource({
        currency,
        disabled,
        price
      });
      !disabled && _dataSources.Event.publish(_helpers.EVENT.OTA_PRICES_READY);
      if (!disabled && !loadedTrackedRef.current) {
        loadedTrackedRef.current = true;
        _dataSources.Event.publish(_helpers.EVENT.METRICS, {
          id: _helpers.METRICS_EVENTS.PRICE_COMP_INTERACTION,
          action: 'loaded',
          load_time_ms: Math.round(performance.now() - loadStartRef.current)
        });
      }
    };
    const handleOTAReady = event => {
      const {
        detail: {
          currency,
          id_ota: id,
          ota_name: name,
          price
        } = {}
      } = event;
      setOtas(prevOtas => [...prevOtas, {
        currency,
        id,
        name,
        price
      }]);
    };
    window.addEventListener('cmprm_event_rc_header_ready', handleHeaderReady);
    window.addEventListener('cmprm_event_rc_ota_ready', handleOTAReady);
    return () => {
      window.removeEventListener('cmprm_event_rc_header_ready', handleHeaderReady);
      window.removeEventListener('cmprm_event_rc_ota_ready', handleOTAReady);
    };
  }, []);
  (0, _react.useEffect)(() => {
    setFetching(true);
    const timeout = setTimeout(() => setFetching(false), 5000);
    return () => clearTimeout(timeout);
  }, [otas]);
  (0, _react.useEffect)(() => {
    const initialize = () => {
      setDataSource();
      setOtas([]);
      loadStartRef.current = performance.now();
      loadedTrackedRef.current = false;
      viewTrackedRef.current = false;
    };
    _dataSources.Event.subscribe(_helpers.EVENT.RATES_FILTER_CLUB, initialize);
    initialize();
    return () => _dataSources.Event.unsubscribe(_helpers.EVENT.RATES_FILTER_CLUB, initialize);
  }, [calendar, currency, occupation, place, promocode]);
  (0, _react.useEffect)(() => {
    const currentRef = ref.current;
    if (!currentRef || viewTrackedRef.current) return;
    if (getSessionViewed()) {
      viewTrackedRef.current = true;
      return;
    }
    const observer = new IntersectionObserver(_ref2 => {
      let [entry] = _ref2;
      if (!entry.isIntersecting) {
        if (viewTimerRef.current) clearTimeout(viewTimerRef.current);
        return;
      }
      if (viewTrackedRef.current) return;
      viewTimerRef.current = setTimeout(() => {
        if (viewTrackedRef.current) return;
        viewTrackedRef.current = true;
        setSessionViewed();
        _dataSources.Event.publish(_helpers.EVENT.METRICS, {
          id: _helpers.METRICS_EVENTS.PRICE_COMP_INTERACTION,
          action: variant === _Core.VARIANT.B ? 'ghost_view' : 'view'
        });
      }, MIN_VIEW_TIME_MS);
    }, {
      threshold: 0.6
    });
    observer.observe(currentRef);
    return () => {
      observer.disconnect();
      if (viewTimerRef.current) clearTimeout(viewTimerRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource === null || dataSource === void 0 ? void 0 : dataSource.disabled, ref === null || ref === void 0 ? void 0 : ref.current]);
  const currencyFormatProps = {
    currency,
    locale,
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  };
  const {
    disabled = false
  } = dataSource || {};
  if (dataSource && !disabled && variant === _Core.VARIANT.B) {
    return /*#__PURE__*/_react.default.createElement(_ui.View, _extends({}, others, {
      ref: ref,
      "aria-hidden": true,
      className: style.ghost
    }));
  }
  return dataSource && !disabled ? /*#__PURE__*/_react.default.createElement(_ui.View, _extends({}, others, {
    ref: ref,
    row: !isMobile,
    className: style.container
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.title
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, null, translate(_OTAPrices.L10N.LABEL_OUR_BEST_ONLINE_RATE)), /*#__PURE__*/_react.default.createElement(_ui.Text, {
    accent: true,
    bold: true,
    headline: true
  }, (0, _locale.currencyFormat)(_objectSpread(_objectSpread({}, currencyFormatProps), {}, {
    value: dataSource.price
  })))), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.items
  }, [...otas].sort((a, b) => a.price - b.price).map(_ref3 => {
    let {
      id,
      name,
      price
    } = _ref3;
    return /*#__PURE__*/_react.default.createElement(_ui.View, {
      key: id,
      className: style.item
    }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
      small: true
    }, name), /*#__PURE__*/_react.default.createElement(_ui.Text, {
      action: isMobile
    }, (0, _locale.currencyFormat)(_objectSpread(_objectSpread({}, currencyFormatProps), {}, {
      value: price
    }))));
  }), fetching && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, Array.from({
    length: 4 - otas.length
  }, (_, index) => /*#__PURE__*/_react.default.createElement(_ui.View, {
    key: "skeleton:".concat(index),
    className: style.item
  }, /*#__PURE__*/_react.default.createElement(_shared__.Skeleton, {
    small: true
  }, "OTA Name"), /*#__PURE__*/_react.default.createElement(_shared__.Skeleton, {
    action: isMobile,
    bold: true
  }, "???$")))))) : null;
};
exports.OTAPrices = OTAPrices;
OTAPrices.displayName = 'Mirai:Core:OTAPrices';
OTAPrices.propTypes = {
  children: _propTypes.default.node,
  className: _propTypes.default.any,
  columnMode: _propTypes.default.bool,
  disabled: _propTypes.default.bool,
  focus: _propTypes.default.bool,
  rowMode: _propTypes.default.bool
};
//# sourceMappingURL=OTAPrices.js.map