import type { Metadata, Viewport } from "next";
import { readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { siteConfig } from "@/lib/site-config";
import { PreventBrowserBackspace } from "@/components/prevent-browser-backspace";
import { PwaServiceWorker } from "@/components/pwa-service-worker";
import "./globals.css";

export const metadata: Metadata = {
  title: siteConfig.brandName,
  description: `${siteConfig.brandName} is a modern webmail workspace for mail, contacts, and calendar`,
  appleWebApp: {
    capable: true,
    statusBarStyle: "default",
    title: "Zimphony"
  },
  icons: {
    icon: siteConfig.brandFaviconUrl || "/icon.png",
    apple: siteConfig.brandFaviconUrl || "/apple-icon.png"
  }
};

export const viewport: Viewport = {
  width: "device-width",
  initialScale: 1,
  viewportFit: "cover",
  themeColor: "#0f766e"
};

export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
  const shouldLoadLiveHelper = process.env.NODE_ENV !== "production";
  const distDir = process.env.NEXT_DIST_DIR || ".next";
  let buildId = "";
  let buildTime = "";
  try {
    const buildIdPath = join(process.cwd(), distDir, "BUILD_ID");
    buildId = readFileSync(buildIdPath, "utf8").trim();
    buildTime = statSync(buildIdPath).mtime.toISOString();
  } catch {
    buildId = "";
    buildTime = "";
  }

  return (
    <html lang="th" suppressHydrationWarning>
      <head>
        <meta name="apple-mobile-web-app-capable" content="yes" />
        {buildId ? <meta name="build-id" content={buildId} /> : null}
        {buildTime ? <meta name="build-time" content={buildTime} /> : null}
      </head>
      <body suppressHydrationWarning>
        <PreventBrowserBackspace />
        <PwaServiceWorker />
        {children}{shouldLoadLiveHelper ? (
        <>
          {/* impeccable-live-start */}
<script src="http://localhost:8400/live.js"></script>
{/* impeccable-live-end */}
        </>
      ) : null}</body>
    </html>
  );
}
