import { type FC } from 'hono/jsx'

const isDev = process.env.NODE_ENV !== 'production'

const Layout: FC = ({ children, title, props }) =>
  <html lang="en">
    <head>
      <title>{title ?? 'hype'}</title>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <meta name="color-scheme" content="light dark" />

      {props.reset && <link href="/css/reset.css" rel="stylesheet" />}
      {props.pico && <link href="/css/pico.css" rel="stylesheet" />}
      <link href="/css/main.css" rel="stylesheet" />
      <script src="/client/main.ts" type="module"></script>
    </head>
    <body>
      <main>
        {children}
      </main>
      {isDev && <ReloadScript />}
    </body>
  </html>

const RELOAD_SCRIPT = '{let c=false;const e=new EventSource("/__hype/reload");e.onopen=()=>{if(c)location.reload();c=true};e.onerror=()=>{e.close();let d=50;setTimeout(function r(){fetch("/__hype/ping").then(()=>location.reload()).catch(()=>{d=Math.min(d*1.5,2000);setTimeout(r,d)})},d)}}'

export const ReloadScript: FC = () =>
  isDev ? <script dangerouslySetInnerHTML={{ __html: RELOAD_SCRIPT }} /> : null

export default Layout
