'use strict';

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var shallow = require('zustand/shallow');
var React = require('react');
var reactUtils = require('@bigbinary/neeto-commons-frontend/react-utils');
var useDisplayErrorPage = require('@bigbinary/neeto-commons-frontend/react-utils/useDisplayErrorPage');
var EditorContent = require('@bigbinary/neeto-editor/EditorContent');
var Button = require('@bigbinary/neetoui/Button');
var Tag = require('@bigbinary/neetoui/Tag');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var injectCss = require('./inject-css-B6qYtOJe.js');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var reactQuery = require('@tanstack/react-query');
var neetoCist = require('@bigbinary/neeto-cist');
var axios = require('axios');
var constants = require('@bigbinary/neeto-commons-frontend/constants');
var utils$1 = require('@bigbinary/neeto-commons-frontend/utils');
var utils = require('@bigbinary/neeto-editor/utils');
var jsxRuntime = require('react/jsx-runtime');

var QUERY_KEYS = {
  APP_STICKY_RIBBONS_LIST: "APP_STICKY_RIBBONS_LIST"
};
var STICKY_RIBBON_KIND_TO_STYLE = {
  info: "info",
  warning: "warning",
  error: "danger"
};
var STICKY_RIBBONS_LOCAL_STORAGE_KEY = "dismissedStickyRibbons";
var POLLING_INTERVAL = 5000;
var MAX_POLLING_TIME = 60000;
var DATE_TIME_FORMAT = "MMMM D h:mm A z";

var css = ".neeto-molecules-sticky-ribbon{border-radius:0}";
injectCss.n(css,{});

var fetchStickyRibbons = function fetchStickyRibbons() {
  return axios.get("".concat(constants.BASE_API_V1_URL, "/sticky_ribbons"), {
    includeMetadataInResponse: true
  });
};
var stickyRibbonsApi = {
  fetchStickyRibbons: fetchStickyRibbons
};

function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = false, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = true, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), true), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
var APP_STICKY_RIBBONS_LIST = QUERY_KEYS.APP_STICKY_RIBBONS_LIST;
var useFetchStickyRibbons = function useFetchStickyRibbons() {
  var _useState = React.useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isPolling = _useState2[0],
    setIsPolling = _useState2[1];
  React.useEffect(function () {
    if (!isPolling) return neetoCist.noop;
    var timer = setTimeout(function () {
      setIsPolling(false);
    }, MAX_POLLING_TIME);
    return function () {
      clearTimeout(timer);
    };
  }, [isPolling]);
  return reactQuery.useQuery({
    queryKey: [APP_STICKY_RIBBONS_LIST],
    queryFn: function () {
      var _queryFn = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
        var response;
        return _regenerator().w(function (_context) {
          while (1) switch (_context.n) {
            case 0:
              _context.n = 1;
              return stickyRibbonsApi.fetchStickyRibbons();
            case 1:
              response = _context.v;
              if (response.status === 202) {
                setIsPolling(true);
              } else if (response.status === 200) {
                setIsPolling(false);
              }
              return _context.a(2, response.data);
          }
        }, _callee);
      }));
      function queryFn() {
        return _queryFn.apply(this, arguments);
      }
      return queryFn;
    }(),
    refetchInterval: isPolling ? POLLING_INTERVAL : false
  });
};

var dayTimeFormatter = function dayTimeFormatter(timestamp) {
  return (
    // eslint-disable-next-line @bigbinary/neeto/use-standard-date-time-formats
    utils$1.dayjs.utc(timestamp).local().format(DATE_TIME_FORMAT)
  );
};
var formatMessageContent = function formatMessageContent(_ref) {
  var message = _ref.message,
    startsAt = _ref.startsAt,
    endsAt = _ref.endsAt;
  return utils.substituteVariables(message, [{
    label: "starts_at",
    key: "starts_at",
    value: dayTimeFormatter(startsAt)
  }, {
    label: "ends_at",
    key: "ends_at",
    value: dayTimeFormatter(endsAt)
  }]);
};

var StickyRibbonsContainer = function StickyRibbonsContainer() {
  var _useState = React.useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isRefreshRibbonDismissed = _useState2[0],
    setIsRefreshRibbonDismissed = _useState2[1];
  var _useLocalStorage = reactUtils.useLocalStorage(STICKY_RIBBONS_LOCAL_STORAGE_KEY, []),
    _useLocalStorage2 = _slicedToArray(_useLocalStorage, 2),
    dismissedRibbons = _useLocalStorage2[0],
    setDismissedRibbons = _useLocalStorage2[1];
  var _useErrorDisplayStore = useDisplayErrorPage.useErrorDisplayStore(function (store) {
      return {
        showRefreshRibbon: store["showRefreshRibbon"]
      };
    }, shallow.shallow),
    showRefreshRibbon = _useErrorDisplayStore.showRefreshRibbon;
  var _useFetchStickyRibbon = useFetchStickyRibbons(),
    _useFetchStickyRibbon2 = _useFetchStickyRibbon.data,
    _useFetchStickyRibbon3 = _useFetchStickyRibbon2 === void 0 ? {} : _useFetchStickyRibbon2,
    _useFetchStickyRibbon4 = _useFetchStickyRibbon3.stickyRibbons,
    stickyRibbons = _useFetchStickyRibbon4 === void 0 ? [] : _useFetchStickyRibbon4;
  var handleDismiss = function handleDismiss(ribbonId) {
    var validRibbonIds = ramda.pluck("id", stickyRibbons);
    var updatedDismissedRibbons = dismissedRibbons.filter(function (id) {
      return validRibbonIds.includes(id);
    });
    setDismissedRibbons([].concat(_toConsumableArray(updatedDismissedRibbons), [ribbonId]));
  };
  var visibleRibbons = stickyRibbons.filter(function (ribbon) {
    return !dismissedRibbons.includes(ribbon.id);
  });
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [showRefreshRibbon && !isRefreshRibbonDismissed && /*#__PURE__*/jsxRuntime.jsx(Tag, {
      className: "neeto-molecules-sticky-ribbon w-full p-2.5 text-center",
      "data-cy": "refresh-sticky-ribbon",
      size: "large",
      style: STICKY_RIBBON_KIND_TO_STYLE["error"],
      onClose: function onClose() {
        return setIsRefreshRibbonDismissed(true);
      },
      children: /*#__PURE__*/jsxRuntime.jsx("span", {
        className: "w-full",
        children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
          i18nKey: "neetoMolecules.stickyRibbonsContainer.refreshRibbon",
          components: {
            button: /*#__PURE__*/jsxRuntime.jsx(Button, {
              "data-cy": "refresh-button",
              style: "link",
              onClick: function onClick() {
                return window.location.reload();
              }
            })
          }
        })
      })
    }), visibleRibbons.map(function (_ref) {
      var id = _ref.id,
        kind = _ref.kind,
        message = _ref.message,
        startsAt = _ref.startsAt,
        endsAt = _ref.endsAt;
      return /*#__PURE__*/jsxRuntime.jsx(Tag, {
        className: "neeto-molecules-sticky-ribbon w-full p-2.5 text-center",
        "data-cy": "sticky-ribbon",
        size: "large",
        style: STICKY_RIBBON_KIND_TO_STYLE[kind],
        onClose: function onClose() {
          return handleDismiss(id);
        },
        children: /*#__PURE__*/jsxRuntime.jsx(EditorContent, {
          className: "w-full",
          content: formatMessageContent({
            message: message,
            startsAt: startsAt,
            endsAt: endsAt
          })
        })
      }, id);
    })]
  });
};

module.exports = StickyRibbonsContainer;
//# sourceMappingURL=StickyRibbonsContainer.js.map
