import type { ReactNode } from "react";
import "./globals.css";
import { readBuildInfoFromEnv } from "@/lib/build-info";

export const metadata = {
  title: "Jorge Cuadros & Asociados — Plataforma",
  description:
    "Plataforma interna unificada de clientes, servicios y seguros.",
};

// The browser talks to the API cross-origin, so it needs the API URL at
// runtime. NEXT_PUBLIC_* would bake it at build time (one URL per image); we
// want the URL to come from the deploy .env instead. So read it here on the
// server per request and inject it as window.__API_ORIGIN__ (see lib/api.ts).
// force-dynamic guarantees process.env is read at request time, never baked
// into a static prerender.
export const dynamic = "force-dynamic";

export default function RootLayout({ children }: { children: ReactNode }) {
  const apiOrigin =
    process.env.API_ORIGIN ??
    process.env.NEXT_PUBLIC_API_ORIGIN ??
    "http://localhost:3001";
  // Same reason as the API origin: read on the server per request so the built
  // image is not pinned to one build identity in its client bundle.
  const build = readBuildInfoFromEnv();

  return (
    <html lang="es">
      <head>
        {/* Must run before the app bundle so lib/api.ts sees it at import. */}
        <script
          dangerouslySetInnerHTML={{
            __html:
              `window.__API_ORIGIN__=${JSON.stringify(apiOrigin)};` +
              `window.__APP_BUILD__=${JSON.stringify(build)};`,
          }}
        />
        {/* Text-size preference, applied before first paint so the page never
            flashes at the default size. Mirrors lib/ui-scale.ts — keep the key
            and the clamp in sync with it. */}
        <script
          dangerouslySetInnerHTML={{
            __html:
              `try{var s=parseFloat(localStorage.getItem("jc.ui-scale"));` +
              `if(isFinite(s))document.documentElement.style.setProperty(` +
              `"--ui-scale",String(Math.min(1.5,Math.max(0.9,s))));}catch(e){}`,
          }}
        />
        {/* Google Fonts via <link> so an offline build still runs with the
            system fallback stacks defined in globals.css. */}
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link
          rel="preconnect"
          href="https://fonts.gstatic.com"
          crossOrigin="anonymous"
        />
        <link
          href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,400;9..144,500;9..144,560;9..144,600&family=Work+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap"
          rel="stylesheet"
        />
      </head>
      <body>{children}</body>
    </html>
  );
}
