import React from 'react';
import { render } from 'react-dom';

import { App } from './containers/App';
import { Home, SinglePost, Login, NotFound } from './containers';
import { Router, Route } from './components/router';
import { history } from './history';
import { firebase } from './backend';

import './styles/styles.scss';

// Function that wraps ReactDOM.render and renders the app w/ current location
const renderApp = (state) => {
  render(
    <Router {...state}>
      <Route path="/" index={Home} component={App}>
        <Route path="posts/:post" component={SinglePost} />
        <Route path="login" component={Login} />
        <Route path="*" component={NotFound} />
      </Route>
    </Router>,
    document.getElementById('app'),
  );
};

const initialState = {
  location: window.location.pathname,
};

// When there's a history change, re-render the app
function activateHistoryListener() {
  history.listen((location) => {
    const user = firebase.auth().currentUser;
    const newState = Object.assign(initialState, {
      location: user
                ? location.pathname
                : '/login',
    });

    renderApp(newState);
  });
}

function activateAuthListener() {
  firebase.auth().onAuthStateChanged((user) => {
    const currentLocation = window.location.pathname;
    if (currentLocation === '/') {
      history.push(user
                ? window.location.pathname
                : '/login');
    }

        // Ensure user gets redirected after they log in
    if (user && currentLocation === '/login') {
      history.push('/');
    }
  });
}


// Render the app initially
renderApp(initialState);
activateHistoryListener();
activateAuthListener();

@@ -752,16 +752,56 @@
  );%0A%7D;%0A%0A
+// Create an intial state object to use%0A
 const in
@@ -1204,16 +1204,44 @@
  %7D);%0A%7D%0A%0A
+// Set up the auth listener%0A
 function
@@ -1304,16 +1304,17 @@
 hanged((
+(
 user) =%3E
@@ -1324,31 +1324,19 @@
     
-const currentLocation =
+if (user &&
  win
@@ -1360,40 +1360,20 @@
 name
-;%0A    if (currentLocation
  === '/
+login
 ') %7B
@@ -1371,32 +1371,39 @@
 login') %7B%0A      
+return 
 history.push(use
@@ -1403,231 +1403,93 @@
 ush(
-user%0A                ? window.location.pathname%0A                : '/login');%0A    %7D%0A%0A        // Ensure user gets redirected after they log in%0A    if (user && currentLocation === '/login') %7B%0A      history.push('/
+'/');%0A    %7D%0A    return history.push(user ? window.location.pathname : '/login
 ');%0A  
- 
- %7D%0A  
 %7D
+)
 );%0A%7D

simplify auth stuff in backend