import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";

/* eslint-disable @typescript-eslint/camelcase */
import React, { useEffect } from 'react';
import Router from 'next/router';
import { ThemeProvider } from 'styled-components';
import { ReactQueryCacheProvider, QueryCache } from 'react-query';
import { Hydrate, dehydrate } from 'react-query/hydration';
import { ReactQueryDevtools } from 'react-query-devtools';
import { ToastProvider } from 'react-toast-notifications';
import { Views, Toast } from '../Common';
import dynamic from 'next/dynamic';
import { Config } from '../../config/index';
import Cookies from 'js-cookie'; // THIS HAS TO BE MOVED OUT OF HERE ITS TEMP FIX SO WE CAN RELEASE!!!!!

import { productsApi, LabelsContextProvider, ConfigProvider, UIProvider, GlobalLabelsProvider, CookieProvider, SentecaProvider, GoogleOneTap, GlobalSEO, prefetchPredicate, prefetchCategories, prefetchCmsContent, prefetchCmsContentList, prefetchListing, protectRoute, enablePreview, AggregationTypeEnum, ComponentTypeEnum, prefetchMenu, InjectedContentProvider, prefetchCookies, RelevaProvider, PixelScript, pixelChangeRoute } from '@sentecacommerce-theme/lib';
import { GlobalStyles } from '../GlobalStyles'; //https://react-query.tanstack.com/docs/guides/ssr

export var queryCache = new QueryCache();
var injectedContentComponents = {
  Banner: dynamic(() => import('../Banner').then(mod => mod.Banner)),
  BannerCarousel: dynamic(() => import('../BannerCarousel').then(mod => mod.BannerCarousel)),
  Caption: dynamic(() => import('../Caption').then(mod => mod.Caption)),
  Carousel: dynamic(() => import('../Carousel').then(mod => mod.Carousel)),
  Element: dynamic(() => import('../Element').then(mod => mod.Element)),
  Header: dynamic(() => import('../Header').then(mod => mod.Header)),
  Html: dynamic(() => import('../Html').then(mod => mod.Html)),
  ListingBanner: dynamic(() => import('../ListingBanner').then(mod => mod.ListingBanner)),
  MerchMenu: dynamic(() => import('../MerchMenu').then(mod => mod.MerchMenu)),
  SlidingCTA: dynamic(() => import('../SlidingCTA').then(mod => mod.SlidingCTA)),
  SubscribeToNewsletter: dynamic(() => import('../SubscribeToNewsletter').then(mod => mod.SubscribeToNewsletter))
};

var 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,
    pageProps
  } = _ref;
  useEffect(() => {
    // Init Pixel
    if (typeof window !== 'undefined' && window.document && window.document.createElement) {
      var initPixel = function initPixel(retryCount) {
        if (retryCount === void 0) {
          retryCount = 0;
        }

        if (Cookies.get('token') || Cookies.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 = PixelScript();
            document.head.appendChild(pixelMain);
          }
        } else if (retryCount < 10) {
          setTimeout(() => initPixel(retryCount + 1), 300);
        }
      };

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


    Router.events.on('routeChangeComplete', () => {
      window.scrollTo(0, 0);
      pixelChangeRoute();
    });
  }, []);
  return /*#__PURE__*/React.createElement(ReactQueryCacheProvider, {
    queryCache: queryCache
  }, /*#__PURE__*/React.createElement(SentecaProvider, {
    defaultConfig: {
      basePath: '/api'
    }
  }, /*#__PURE__*/React.createElement(Hydrate, {
    state: pageProps.dehydratedState
  }, /*#__PURE__*/React.createElement(ConfigProvider, {
    config: Config
  }, /*#__PURE__*/React.createElement(GlobalSEO, null), /*#__PURE__*/React.createElement(GoogleOneTap, null), /*#__PURE__*/React.createElement(ReactQueryDevtools, {
    initialIsOpen: true
  }), /*#__PURE__*/React.createElement(GlobalStyles, null), /*#__PURE__*/React.createElement(ThemeProvider, {
    theme: Config.theme
  }, /*#__PURE__*/React.createElement(LabelsContextProvider, null, /*#__PURE__*/React.createElement(GlobalLabelsProvider, {
    labels: Config.globalLabels
  }, /*#__PURE__*/React.createElement(ToastProvider, {
    components: {
      Toast
    }
  }, /*#__PURE__*/React.createElement(CookieProvider, null, /*#__PURE__*/React.createElement(RelevaProvider, null, /*#__PURE__*/React.createElement(UIProvider, {
    displayNavbar: true,
    displaySidebar: true
  }, /*#__PURE__*/React.createElement(Views, null), /*#__PURE__*/React.createElement(InjectedContentProvider, {
    components: injectedContentComponents,
    fullWidthContentClass: "InjectedContent--full-width",
    containerClass: "InjectedContent--container"
  }, /*#__PURE__*/React.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 = _asyncToGenerator(function* (context) {
    var pageProps = {};
    var {
      router,
      ctx
    } = context;

    if (typeof window === 'undefined') {
      enablePreview(router, ctx);
      yield prefetchMenu(queryCache);
      yield prefetchCookies(queryCache, Config.interfaceKey);

      if (router.route === '/[slug]/p') {
        yield productsApi.usePrefetchProduct(queryCache, router.query.slug, {
          expand: 'brands'
        });

        var _dehydratedState = dehydrate(queryCache);

        pageProps.dehydratedState = _dehydratedState;
      }

      var listing = listingSet.has(router.route);

      if (listing) {
        var predicate = yield prefetchPredicate(queryCache, router);

        if (!predicate || predicate.statusCode || predicate.stack) {
          ctx.res.statusCode = 404;
          pageProps.errorCode = 404;
          return {
            pageProps
          };
        }

        yield prefetchListing(queryCache, router, predicate);
        yield prefetchCategories(queryCache, router, predicate, [{
          label: 'Categories',
          aggregationType: AggregationTypeEnum.Terms,
          aggregationDefinition: 'categories',
          filterDefinition: 'category',
          component: ComponentTypeEnum.TextWithLink,
          order: 0
        }]);
      }

      if (router.route === '/search') {
        yield prefetchListing(queryCache, router);
      }

      if (router.route === '/blog') {
        var _router$query;

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

        var _dehydratedState2 = dehydrate(queryCache);

        pageProps.dehydratedState = _dehydratedState2;
      }

      if (router.route === '/blog/[slug]') {
        var isContentFound = yield prefetchCmsContent({
          queryCache,
          key: router.query.slug
        });

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

        var _dehydratedState3 = dehydrate(queryCache);

        pageProps.dehydratedState = _dehydratedState3;
      }

      var dehydratedState = dehydrate(queryCache);
      pageProps.dehydratedState = dehydratedState;
    } // If user is not logged in redirect to /


    protectRoute(ctx, 'profile', '/');
    return {
      pageProps
    };
  });

  return function (_x) {
    return _ref2.apply(this, arguments);
  };
}();

export { App };
//# sourceMappingURL=app.component.js.map