import Document, {
  Html, Head, Main, NextScript
} from 'next/document'

import createEmotionServer from '@emotion/server/create-instance'
import createEmotionCache from '../lib/create-emotion-cache'

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang='fr' prefix='website: https://ogp.me/ns/website#'>
        <Head>
          <link rel='manifest' href='/manifest.json' />
          <link rel='icon' type='image/x-icon' sizes='128x128' href='/favicon.ico' />
          <link rel='apple-touch-icon' href='/favicon.ico' />
          {this.props.emotionStyleTags}
          <meta name='application-name' content='#OKi | Organisation KA Internationale' />
          <meta name='theme-color' content='#303030' />
          <meta name='apple-mobile-web-app-status-bar' content='#303030' />
          <meta charSet='utf-8' />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

MyDocument.getInitialProps = async ctx => {
  const originalRenderPage = ctx.renderPage
  const cache = createEmotionCache()
  const {extractCriticalToChunks} = createEmotionServer(cache)

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: App =>
        function EnhanceApp(props) { // eslint-disable-line react/function-component-definition
          return <App emotionCache={cache} {...props} />
        },
    })

  const initialProps = await Document.getInitialProps(ctx)
  const emotionStyles = extractCriticalToChunks(initialProps.html)
  const emotionStyleTags = emotionStyles.styles.map(style => (
    <style
      key={style.key}
      data-emotion={`${style.key} ${style.ids.join(' ')}`}
      dangerouslySetInnerHTML={{__html: style.css}}
    />
  ))

  return {
    ...initialProps,
    emotionStyleTags
  }
}
