import type { Metadata } from "next";
import { Raleway } from "next/font/google";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { MobileTabs } from "@/components/MobileTabs";
import { RegisterSW } from "@/components/RegisterSW";
import { InteractiveShell } from "@/components/motion/InteractiveShell";
import { getBranding, getSettings } from "@/lib/session";
import "./globals.css";

export const dynamic = "force-dynamic";

const raleway = Raleway({
  subsets: ["latin"],
  weight: ["300", "400", "500", "600", "700"],
  style: ["normal", "italic"],
  variable: "--font-raleway",
  display: "swap",
});

function followUnlessLegacy(
  value: string | null | undefined,
  accent: string,
  legacy: string
) {
  if (!value) return accent;
  if (
    value.toLowerCase() === legacy.toLowerCase() &&
    accent.toLowerCase() !== legacy.toLowerCase()
  ) {
    return accent;
  }
  return value;
}

export async function generateMetadata(): Promise<Metadata> {
  const branding = await getBranding();
  return {
    title: branding.documentTitle,
    description: "Servicios, clasificados y empleos verificados en Puerto Rico",
    manifest: "/manifest.webmanifest",
    appleWebApp: {
      capable: true,
      statusBarStyle: "black-translucent",
      title: branding.brandName || "Servicios PR",
    },
    other: {
      "mobile-web-app-capable": "yes",
    },
  };
}

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

export default async function RootLayout({
  children,
}: Readonly<{ children: React.ReactNode }>) {
  const [settings, branding] = await Promise.all([
    getSettings(),
    getBranding(),
  ]);

  const accent = branding.accent || "#C5FF00";
  const bg = branding.bg || "#0A0A0A";
  const surface = branding.surface || "#141814";
  // Si effect/border/orb siguen el default lime/olive pero accent cambió,
  // el hero glow sigue el accent (evita verde “pegado” tras cambiar CTA).
  const effect = followUnlessLegacy(branding.effect, accent, "#C5FF00");
  const border = followUnlessLegacy(branding.border, accent, "#C5FF00");
  const orb = followUnlessLegacy(branding.orb, accent, "#2A3B00");

  return (
    <html
      lang="es"
      data-theme="lime-black"
      className={`${raleway.variable} ${raleway.className}`}
      suppressHydrationWarning
      style={
        {
          ["--lime"]: accent,
          ["--lime-dim"]: accent,
          ["--bg"]: bg,
          ["--bg-elevated"]: bg,
          ["--surface"]: surface,
          ["--surface-2"]: orb,
          ["--ink"]: bg,
          ["--effect"]: effect,
          ["--border-color"]: border,
          ["--orb"]: orb,
          ["--olive"]: orb,
          ["--olive-mid"]: orb,
          ["--border"]: `color-mix(in srgb, ${border} 14%, transparent)`,
          ["--border-strong"]: `color-mix(in srgb, ${border} 32%, transparent)`,
          backgroundColor: bg,
          color: "#F5F5F5",
        } as React.CSSProperties
      }
    >
      <body
        className={`${raleway.className} font-sans antialiased interactive-root`}
        suppressHydrationWarning
        style={
          {
            backgroundColor: bg,
            color: "#F5F5F5",
            fontFamily: "var(--font-raleway), Raleway, sans-serif",
            ["--mx"]: "50vw",
            ["--my"]: "40vh",
          } as React.CSSProperties
        }
      >
        {settings.maintenanceMode && (
          <div className="bg-amber-500/20 px-4 py-2 text-center text-sm text-amber-100">
            Modo mantenimiento activo — algunas funciones pueden estar limitadas.
          </div>
        )}
        <InteractiveShell>
          <div className="app-shell">
            <Navbar />
            <main className="app-main mx-auto w-full max-w-7xl px-4 pb-8 pt-3 sm:px-6 sm:pt-4 lg:px-8">
              {children}
            </main>
            <Footer />
            <MobileTabs
              modules={{
                services: settings.moduleServices,
                classifieds: settings.moduleClassifieds,
                jobs: settings.moduleJobs,
              }}
            />
          </div>
        </InteractiveShell>
        <RegisterSW />
      </body>
    </html>
  );
}
