import type { Metadata } from "next";
import { Noto_Serif_Display, Be_Vietnam_Pro, Cormorant_Garamond } from "next/font/google";
import "./globals.css";
import { SiteShell } from "@/components/site-shell";
import { buildOrganization, buildWebsite, jsonLdScript } from "@/lib/seo";
import { getSetting } from "@/lib/settings";

// Read site.url from DB on every request so admins can change the public
// domain via /admin/site without a rebuild. JSON-LD + metadataBase + OG
// tags below all depend on it. getSetting() caches 30s in-process so the
// DB hit rate stays low.
export const dynamic = "force-dynamic";

// Self-hosted via next/font (Phase 1.3 will switch to local files for full control)
const display = Noto_Serif_Display({
  subsets: ["latin", "vietnamese"],
  weight: ["400", "500", "600", "700"],
  style: ["normal", "italic"],
  variable: "--font-display",
  display: "swap",
});

const body = Be_Vietnam_Pro({
  subsets: ["latin", "vietnamese"],
  weight: ["300", "400", "500", "600", "700"],
  variable: "--font-body",
  display: "swap",
});

const numeral = Cormorant_Garamond({
  subsets: ["latin", "vietnamese"],
  weight: ["400", "500", "600", "700"],
  variable: "--font-numeral",
  display: "swap",
});

export async function generateMetadata(): Promise<Metadata> {
  const siteUrl = await getSetting("site.url");
  return {
    title: {
      default: "Tử Vi Số · Khám phá vận mệnh của bạn",
      template: "%s · Tử Vi Số",
    },
    description:
      "Xem tử vi trọn đời, vận mệnh AI luận giải, ngày tốt và phong thủy nhà — dựa trên Tử vi Đẩu số cổ học.",
    metadataBase: new URL(siteUrl),
    openGraph: {
      type: "website",
      locale: "vi_VN",
      siteName: "Tử Vi Số",
    },
    robots: {
      index: true,
      follow: true,
    },
  };
}

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const siteUrl = await getSetting("site.url");
  return (
    <html
      lang="vi"
      className={`${display.variable} ${body.variable} ${numeral.variable} h-full antialiased`}
    >
      <body className="bg-bg-base text-ink-primary flex min-h-full flex-col">
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: jsonLdScript(buildOrganization(siteUrl)) }}
        />
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: jsonLdScript(buildWebsite(siteUrl)) }}
        />
        <SiteShell>{children}</SiteShell>
      </body>
    </html>
  );
}
