import React from 'react';
import { PersistGate } from 'redux-persist/integration/react'
import App, { Container } from 'next/app';
import theme from '../components/atoms/theme';
import { ThemeProvider } from '@material-ui/styles';
import { StylesProvider } from '@material-ui/styles';
import Router from 'next/router'
import { Provider } from 'react-redux'
import withRedux from 'next-redux-wrapper'
import withReduxSaga from 'next-redux-saga'
import setAuthorizationHeader from "../data/setAuthorizationHeader";
import { fetchCurrentUserRequest } from "../actions/user";
import createStore from '../store'
import WebPush from '../components/atoms/Webpush';
import * as gtag from '../src/gtag'

class MyApp extends App {
  constructor(props) {
    super(props);
  }

  componentDidMount() {

    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles && jssStyles.parentNode) {
      jssStyles.parentNode.removeChild(jssStyles);
    }

    // if (process.env.DEV !== 1) {
    //   //google tag manager tracking
    //   Router.router.events.on('routeChangeComplete', url => gtag.pageview(url))
    // }

    if (!!localStorage.ttJWT) {
      setAuthorizationHeader(localStorage.ttJWT)
      this.props.store.dispatch(fetchCurrentUserRequest());
    }

    window.$crisp = [];
    window.CRISP_WEBSITE_ID = process.env.CRISP_WEBSITE_ID;
    
    (function () {
      var d = document;
      var s = d.createElement("script");

      s.src = "https://client.crisp.chat/l.js";
      s.async = 1;

      d.getElementsByTagName("head")[0].appendChild(s);
    })();
  }

  render() {
    const { Component, pageProps, store } = this.props;
    return (
      <StylesProvider injectFirst>
        {/* Wrap every page in Jss and Theme providers */}
        {/* MuiThemeProvider makes the theme available down the React
              tree thanks to React context. */}
        <ThemeProvider theme={theme}
        >
          {/* Pass pageContext to the _document though the renderPage enhancer
                to render collected styles on server side. */}
          <Provider store={store}>
            <WebPush>
              {/* <PersistGate loading={null} persistor={store.__persistor}> */}
              <Component pageContext={this.pageContext} {...pageProps} />

            </WebPush>
            {/* </PersistGate> */}
          </Provider>
        </ThemeProvider>
      </StylesProvider>
    );
  }
}

export default withRedux(createStore)(withReduxSaga(MyApp))
