"use strict";

var _interopRequireWildcard3 = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.App = App;
exports.queryCache = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _interopRequireWildcard2 = _interopRequireDefault(require("@babel/runtime/helpers/interopRequireWildcard"));

var _react = _interopRequireWildcard3(require("react"));

var _router = _interopRequireDefault(require("next/router"));

var _styledComponents = require("styled-components");

var _reactQuery = require("react-query");

var _hydration = require("react-query/hydration");

var _reactQueryDevtools = require("react-query-devtools");

var _reactToastNotifications = require("react-toast-notifications");

var _Common = require("../Common");

var _dynamic = _interopRequireDefault(require("next/dynamic"));

var _index = require("../../config/index");

var _jsCookie = _interopRequireDefault(require("js-cookie"));

var _lib = require("@sentecacommerce-theme/lib");

var _GlobalStyles = require("../GlobalStyles");

/* eslint-disable @typescript-eslint/camelcase */
// THIS HAS TO BE MOVED OUT OF HERE ITS TEMP FIX SO WE CAN RELEASE!!!!!
//https://react-query.tanstack.com/docs/guides/ssr
var queryCache = new _reactQuery.QueryCache();
exports.queryCache = queryCache;
var injectedContentComponents = {
  Banner: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../Banner'));
    }).then(function (mod) {
      return mod.Banner;
    });
  }),
  BannerCarousel: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../BannerCarousel'));
    }).then(function (mod) {
      return mod.BannerCarousel;
    });
  }),
  Caption: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../Caption'));
    }).then(function (mod) {
      return mod.Caption;
    });
  }),
  Carousel: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../Carousel'));
    }).then(function (mod) {
      return mod.Carousel;
    });
  }),
  Element: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../Element'));
    }).then(function (mod) {
      return mod.Element;
    });
  }),
  Header: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../Header'));
    }).then(function (mod) {
      return mod.Header;
    });
  }),
  Html: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../Html'));
    }).then(function (mod) {
      return mod.Html;
    });
  }),
  ListingBanner: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../ListingBanner'));
    }).then(function (mod) {
      return mod.ListingBanner;
    });
  }),
  MerchMenu: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../MerchMenu'));
    }).then(function (mod) {
      return mod.MerchMenu;
    });
  }),
  SlidingCTA: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../SlidingCTA'));
    }).then(function (mod) {
      return mod.SlidingCTA;
    });
  }),
  SubscribeToNewsletter: (0, _dynamic["default"])(function () {
    return Promise.resolve().then(function () {
      return (0, _interopRequireWildcard2["default"])(require('../SubscribeToNewsletter'));
    }).then(function (mod) {
      return mod.SubscribeToNewsletter;
    });
  })
};

var PixelConfig = function PixelConfig() {
  return "const token = document.cookie\n  .split('; ')\n  .map(el => el.split('='))\n  .find(el => el[0] === 'token' || el[0] === 'anonymousToken')[1];\n  const cfg = {\n  source: 'district-web-client',\n  appName: 'District Shoes',\n  debug: false,\n  initialUserId: JSON.parse(atob(token.split('.')[1])).sub, //get cookies\n  };\n  window.pixel_cfg = cfg;\n  ";
};

function App(_ref) {
  var Component = _ref.Component,
      pageProps = _ref.pageProps;
  (0, _react.useEffect)(function () {
    // Init Pixel
    if (typeof window !== 'undefined' && window.document && window.document.createElement) {
      var initPixel = function initPixel(retryCount) {
        if (retryCount === void 0) {
          retryCount = 0;
        }

        if (_jsCookie["default"].get('token') || _jsCookie["default"].get('anonymousToken')) {
          var pixelConfigScript = document.getElementById('pixelConfig');

          if (pixelConfigScript === null) {
            var pixelConfig = document.createElement('script');
            pixelConfig.type = 'application/javascript';
            pixelConfig.id = 'pixelConfig';
            pixelConfig.text = PixelConfig();
            document.head.appendChild(pixelConfig);
            var pixelMain = document.createElement('script');
            pixelMain.type = 'application/javascript';
            pixelMain.id = 'pixelMain';
            pixelMain.text = (0, _lib.PixelScript)();
            document.head.appendChild(pixelMain);
          }
        } else if (retryCount < 10) {
          setTimeout(function () {
            return initPixel(retryCount + 1);
          }, 300);
        }
      };

      initPixel();
    } // Scroll top on route change


    _router["default"].events.on('routeChangeComplete', function () {
      window.scrollTo(0, 0);
      (0, _lib.pixelChangeRoute)();
    });
  }, []);
  return /*#__PURE__*/_react["default"].createElement(_reactQuery.ReactQueryCacheProvider, {
    queryCache: queryCache
  }, /*#__PURE__*/_react["default"].createElement(_lib.SentecaProvider, {
    defaultConfig: {
      basePath: '/api'
    }
  }, /*#__PURE__*/_react["default"].createElement(_hydration.Hydrate, {
    state: pageProps.dehydratedState
  }, /*#__PURE__*/_react["default"].createElement(_lib.ConfigProvider, {
    config: _index.Config
  }, /*#__PURE__*/_react["default"].createElement(_lib.GlobalSEO, null), ' ', /*#__PURE__*/_react["default"].createElement(_reactQueryDevtools.ReactQueryDevtools, {
    initialIsOpen: true
  }), /*#__PURE__*/_react["default"].createElement(_GlobalStyles.GlobalStyles, null), /*#__PURE__*/_react["default"].createElement(_styledComponents.ThemeProvider, {
    theme: _index.Config.theme
  }, /*#__PURE__*/_react["default"].createElement(_lib.LabelsContextProvider, null, /*#__PURE__*/_react["default"].createElement(_lib.GlobalLabelsProvider, {
    labels: _index.Config.globalLabels
  }, /*#__PURE__*/_react["default"].createElement(_reactToastNotifications.ToastProvider, {
    components: {
      Toast: _Common.Toast
    }
  }, /*#__PURE__*/_react["default"].createElement(_lib.CookieProvider, null, /*#__PURE__*/_react["default"].createElement(_lib.RelevaProvider, null, /*#__PURE__*/_react["default"].createElement(_lib.UIProvider, {
    displayNavbar: true,
    displaySidebar: true
  }, /*#__PURE__*/_react["default"].createElement(_Common.Views, null), /*#__PURE__*/_react["default"].createElement(_lib.InjectedContentProvider, {
    components: injectedContentComponents,
    fullWidthContentClass: "InjectedContent--full-width",
    containerClass: "InjectedContent--container"
  }, /*#__PURE__*/_react["default"].createElement(Component, pageProps)))))))))))));
}

var listingSet = new Set(['/[slug]/c', '/[slug]/b', '/[slug]/v', '/[slug]/ct', '/[slug]/[cat]/c', '/[slug]/[cat]/b']);

App.getInitialProps = /*#__PURE__*/function () {
  var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(context) {
    var pageProps, router, ctx, _dehydratedState, listing, predicate, _router$query, _dehydratedState2, isContentFound, _dehydratedState3, dehydratedState;

    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            pageProps = {};
            router = context.router, ctx = context.ctx;

            if (!(typeof window === 'undefined')) {
              _context.next = 43;
              break;
            }

            (0, _lib.enablePreview)(router, ctx);
            _context.next = 6;
            return (0, _lib.prefetchMenu)(queryCache);

          case 6:
            _context.next = 8;
            return (0, _lib.prefetchCookies)(queryCache, _index.Config.interfaceKey);

          case 8:
            if (!(router.route === '/[slug]/p')) {
              _context.next = 13;
              break;
            }

            _context.next = 11;
            return _lib.productsApi.usePrefetchProduct(queryCache, router.query.slug, {
              expand: 'brands'
            });

          case 11:
            _dehydratedState = (0, _hydration.dehydrate)(queryCache);
            pageProps.dehydratedState = _dehydratedState;

          case 13:
            listing = listingSet.has(router.route);

            if (!listing) {
              _context.next = 26;
              break;
            }

            _context.next = 17;
            return (0, _lib.prefetchPredicate)(queryCache, router);

          case 17:
            predicate = _context.sent;

            if (!(!predicate || predicate.statusCode || predicate.stack)) {
              _context.next = 22;
              break;
            }

            ctx.res.statusCode = 404;
            pageProps.errorCode = 404;
            return _context.abrupt("return", {
              pageProps: pageProps
            });

          case 22:
            _context.next = 24;
            return (0, _lib.prefetchListing)({
              queryCache: queryCache,
              router: router,
              predicate: predicate,
              defaultLimit: _index.Config.listing.limit,
              defaultSortKey: _index.Config.listing.defaultSortKey
            });

          case 24:
            _context.next = 26;
            return (0, _lib.prefetchCategories)(queryCache, router, predicate, [{
              label: 'Categories',
              aggregationType: _lib.AggregationTypeEnum.Terms,
              aggregationDefinition: 'categories',
              filterDefinition: 'category',
              component: _lib.ComponentTypeEnum.TextWithLink,
              order: 0
            }]);

          case 26:
            if (!(router.route === '/search')) {
              _context.next = 29;
              break;
            }

            _context.next = 29;
            return (0, _lib.prefetchListing)({
              queryCache: queryCache,
              router: router,
              defaultLimit: _index.Config.listing.limit,
              defaultSortKey: _index.Config.listing.defaultSortKey
            });

          case 29:
            if (!(router.route === '/blog')) {
              _context.next = 34;
              break;
            }

            _context.next = 32;
            return (0, _lib.prefetchCmsContentList)(queryCache, {
              type: _index.Config.blogConfig.key,
              limit: _index.Config.blogConfig.limit
            }, +((router == null ? void 0 : (_router$query = router.query) == null ? void 0 : _router$query.page) || '1'));

          case 32:
            _dehydratedState2 = (0, _hydration.dehydrate)(queryCache);
            pageProps.dehydratedState = _dehydratedState2;

          case 34:
            if (!(router.route === '/blog/[slug]')) {
              _context.next = 41;
              break;
            }

            _context.next = 37;
            return (0, _lib.prefetchCmsContent)({
              queryCache: queryCache,
              key: router.query.slug
            });

          case 37:
            isContentFound = _context.sent;

            if (!isContentFound) {
              ctx.res.statusCode = 404;
            }

            _dehydratedState3 = (0, _hydration.dehydrate)(queryCache);
            pageProps.dehydratedState = _dehydratedState3;

          case 41:
            dehydratedState = (0, _hydration.dehydrate)(queryCache);
            pageProps.dehydratedState = dehydratedState;

          case 43:
            // If user is not logged in redirect to /
            (0, _lib.protectRoute)(ctx, 'profile', '/');
            return _context.abrupt("return", {
              pageProps: pageProps
            });

          case 45:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function (_x) {
    return _ref2.apply(this, arguments);
  };
}();
//# sourceMappingURL=app.component.js.map