#!/usr/bin/env -S node -r esbin
import fs from "fs"
import React from "react"
import { renderToStaticMarkup } from "react-dom/server"

const __DEV__ = process.env.NODE_ENV !== "production"

const Head: FC<{
  children: React.ReactNode
}> = ({ children }) => (
  <head>
    <meta charSet="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    {children}
  </head>
)

const files: {
  [path: string]: React.ReactElement
} = {
  "./dist/background.html": (
    <html>
      <Head>
        <script type="module" src="app/background/index.js" />
      </Head>
    </html>
  ),
  "./dist/devtools.html": (
    <html>
      <Head>
        <script type="module" src="app/devtools/index.js" />
      </Head>
    </html>
  ),
  "./dist/options.html": (
    <html data-theme="github-dark">
      <Head>
        <link rel="stylesheet" href="app/options/index.css" />
        <link rel="stylesheet" href="/vendor/primer/github-dark.css" />
      </Head>
      <body>
        {__DEV__ && (
          // React DevTools
          // curl -s http://localhost:8097 | openssl dgst -sha384 -binary | openssl base64 -A
          <script src="http://localhost:8097" crossOrigin="anonymous" />
        )}
        <div id="not-loaded" />
        <div id="root" />
        <script type="module" src="app/options/index.js" />
      </body>
    </html>
  ),
  "./dist/playground.html": (
    <html>
      <Head>
        <link rel="stylesheet" href="app/playground/index.css" />
      </Head>
      <body>
        <div id="root" />
        <script type="module" src="app/playground/index.js" />
      </body>
    </html>
  ),
  "./dist/popup.html": (
    <html>
      <Head>
        <link rel="stylesheet" href="app/popup/index.css" />
      </Head>
      <body>
        <div id="root" />
        <script type="module" src="app/popup/index.js" />
      </body>
    </html>
  ),
  "./dist/reference.html": (
    <html>
      <Head>
        <link rel="stylesheet" href="app/reference/index.css" />
      </Head>
      <body>
        <div id="root" />
        <script src="app/reference/index.js" />
      </body>
    </html>
  ),
}

for (const [path, content] of Object.entries(files)) {
  const html = "<!DOCTYPE html>" + renderToStaticMarkup(content)
  fs.writeFileSync(path, html)
}
