// eslint-disable filenames/match-exported
import React from "react"
import { render } from "react-dom"
import { BrowserRouter } from "react-router-dom"
import { ApolloProvider } from "react-apollo"
import { withAsyncComponents } from "react-async-component"

import ReactHotLoader from "./ReactHotLoader"
import AppContainer from "../app/AppContainer"
import { createApolloClient, createReduxStore } from "../common/Data"

// Get the DOM Element that will host our React application.
const container = document.querySelector("#app")

function renderApp(RenderContainer)
{
  console.log("Client: Initialize state from server:", window.APP_STATE)
  const apolloClient = createApolloClient({
    initialState: window.APP_STATE
  })

  const reduxStore = createReduxStore({
    reducers: RenderContainer.getReducers(),
    enhancers: RenderContainer.getEnhancers(),
    middlewares: RenderContainer.getMiddlewares(),
    initialState: window.APP_STATE
  })

  var fullApp = (
    <ReactHotLoader>
      <BrowserRouter>
        <ApolloProvider client={apolloClient} store={reduxStore}>
          <RenderContainer/>
        </ApolloProvider>
      </BrowserRouter>
    </ReactHotLoader>
  )

  withAsyncComponents(fullApp).then((result) => {
    // The result will include a version of your app that is
    // built to use async components and is automatically
    // rehydrated with the async component state returned by
    // the server.
    const { appWithAsyncComponents } = result
    render(appWithAsyncComponents, container)
  }).catch((error) => {
    console.error("Client: Error wrapping application for code splitting:", error)
  })
}

// The following is needed so that we can hot reload our App.
if (process.env.NODE_ENV === "development" && module.hot)
{
  // Accept changes to this file for hot reloading.
  module.hot.accept("./index.js")

  // Any changes to our App will cause a hotload re-render.
  // module.hot.accept("../app/AppContainer", () => renderApp(require("../app/AppContainer").default))
}

renderApp(AppContainer)

@@ -528,16 +528,50 @@
 #app%22)%0A%0A
+%0Alet apolloClient%0Alet reduxStore%0A%0A
 function
@@ -573,24 +573,28 @@
 ction render
+Data
 App(RenderCo
@@ -679,22 +679,16 @@
 TATE)%0A  
-const 
 apolloCl
@@ -758,22 +758,16 @@
   %7D)%0A%0A  
-const 
 reduxSto
@@ -974,16 +974,93 @@
 E%0A  %7D)%0A%0A
+  return renderApp(RenderContainer)%0A%7D%0A%0Afunction renderApp(RenderContainer)%0A%7B%0A
   var fu
@@ -2009,19 +2009,16 @@
 ender.%0A 
- //
  module.
@@ -2057,26 +2057,37 @@
 , () =%3E 
-renderApp(
+%7B%0A    let nextRoot = 
 require(
@@ -2116,17 +2116,101 @@
 .default
-)
+%0A    console.log(%22Reloaded root container: %22, nextRoot)%0A    renderApp(nextRoot)%0A%0A%0A  %7D
 )%0A%7D%0A%0Aren
@@ -2208,24 +2208,28 @@
 %7D)%0A%7D%0A%0Arender
+Data
 App(AppConta

Split data/component rendering