/**
 * _document is only rendered on the server
 * https://github.com/zeit/next.js/#custom-document
 *
 * We're using styled-components, so here is the right place
 * to place the styles.
 * https://www.styled-components.com/docs/advanced#server-side-rendering
 *
 * Configure babel for server-side rendering with styled-components
 * https://dev.to/aprietof/nextjs--styled-components-the-really-simple-guide----101c
*/

import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

class MyDocument extends Document {
  static async getInitialProps (ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () => originalRenderPage({
        enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
      })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      }
    } finally {
      sheet.seal()
    }
  }
}

export default MyDocument