/** @jsxImportSource hono/jsx */
import type { Context } from "hono";
import { readFileSync } from "fs";
import { join } from "path";

import type { BlankEnv } from "hono/types";

export function clientEntry(c: Context<BlankEnv>) {
  let jsFile = "/src/client/main.tsx";
  let cssFiles: string[] | null = null;

  if (process.env.NODE_ENV === 'production') {
    try {
      // Read Vite manifest to get the correct file names
      const manifestPath = join(process.cwd(), 'dist', '.vite', 'manifest.json');
      const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
      const entry = manifest['index.html'];
      if (entry) {
        jsFile = `/${entry.file}`;
        if (entry.css) {
          cssFiles = entry.css.map((css: string) => `/${css}`);
        }
      }
    } catch (error) {
      console.warn('Could not read Vite manifest, using fallback:', error);
      // Fallback to a generic path
      jsFile = "/assets/index-Ccx6A0bN.js";
      cssFiles = ["/assets/index-RdX4PbOO.css"];
    }
  }

  return c.html(
    <html lang="de">
      <head>
        <meta charSet="utf-8" />
        <meta content="width=device-width, initial-scale=1" name="viewport" />
        <meta name="theme-color" content="#ec4899" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="default" />
        <meta name="apple-mobile-web-app-title" content="Stargirlnails" />
        <title>Stargirlnails Kiel</title>
        <link rel="icon" type="image/png" href="/favicon.png" />
        <link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
        <link rel="manifest" href="/manifest.json" />
        <script
          defer
          data-domain="stargirlnails.de"
          src="https://plausible.elpatron.me/js/script.js"
        />
        {cssFiles && cssFiles.map((css: string) => (
          <link key={css} rel="stylesheet" href={css} />
        ))}
        {process.env.NODE_ENV === 'production' ? (
          <script src={jsFile} type="module" />
        ) : (
          <>
            <script src="/@vite/client" type="module" />
            <script src={jsFile} type="module" />
          </>
        )}
      </head>
      <body>
        <div id="root" />
      </body>
    </html>,
  );
}
