import { renderToString } from '@vue/server-renderer'
import { createMemoryHistory } from 'vue-router'
import { renderHeadToString } from '@vueuse/head'
import { escapeInject, dangerouslySkipEscape } from 'vike/server'
import { createApp } from '@/app'

export { onRenderHtml }

async function onRenderHtml(pageContext) {
  const { app, router, head } = createApp({
    history: createMemoryHistory()
  })

  await router.push(pageContext.urlOriginal)
  await router.isReady()

  const appHtml = await renderToString(app)
  const { headTags, htmlAttrs, bodyAttrs } = await renderHeadToString(head)
  const assetsHtml = pageContext.renderAssets ? pageContext.renderAssets() : ''

  return escapeInject`<!DOCTYPE html>
    <html${dangerouslySkipEscape(htmlAttrs)}>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="icon" type="image/svg+xml" href="/favicon.svg">
        ${dangerouslySkipEscape(headTags)}
        ${dangerouslySkipEscape(assetsHtml)}
      </head>
      <body${dangerouslySkipEscape(bodyAttrs)}>
        <div id="app">${dangerouslySkipEscape(appHtml)}</div>
      </body>
    </html>`
}
