import type { Metadata } from "next";
import { NextIntlClientProvider, hasLocale } from "next-intl";
import { getTranslations, setRequestLocale } from "next-intl/server";
import { notFound } from "next/navigation";
import { Geist, Geist_Mono } from "next/font/google";
import localFont from "next/font/local";
import Script from "next/script";
import { routing } from "@/i18n/routing";
import { getSettings } from "@/lib/settings";
import { getSiteUrl } from "@/lib/seo";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { LiveChat } from "@/components/LiveChat";
import { ScrollToTop } from "@/components/ScrollToTop";
import { MaintenancePage } from "@/components/MaintenancePage";
import { hasMaintenanceBypass } from "@/lib/maintenanceBypass";
import { SiteBanner } from "@/components/SiteBanner";
import { SiteHeader } from "@/components/SiteHeader";
import { SiteFooter } from "@/components/SiteFooter";
import { CopyProtection } from "@/components/CopyProtection";
import { AdminAwareLayout } from "@/components/AdminAwareLayout";
import { PageViewTracker } from "@/components/PageViewTracker";
import "../globals.css";

const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"] });
const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"] });

// Nur für Headlines/Wordmark gedacht (Rakku-Markenschrift) — nicht für Fließtext.
const quantify = localFont({
  src: "../fonts/Quantify.ttf",
  variable: "--font-quantify",
  display: "swap",
});

export function generateStaticParams() {
  return routing.locales.map((locale) => ({ locale }));
}

// Muss bei jedem Request neu geprüft werden (Wartungsmodus/Live-Chat-Schalter
// sollen sofort wirken, ohne Rebuild).
export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}): Promise<Metadata> {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: "common" });
  const settings = await getSettings();
  const seo = settings.seoSettings;

  return {
    metadataBase: new URL(getSiteUrl()),
    title: t("siteName"),
    description: (locale === "en" ? seo?.defaultMetaDescriptionEn || seo?.defaultMetaDescription : seo?.defaultMetaDescription) || t("tagline"),
    // Sicherer Standard: nur Seiten, die selbst explizit Metadaten setzen
    // (buildPageMetadata, siehe lib/seo.ts), werden indexierbar — Admin-/
    // Konto-Seiten ohne eigene generateMetadata bleiben so automatisch
    // aus der Suche heraus, ohne das an jeder einzelnen Stelle vergessen zu können.
    robots: { index: false, follow: false },
    verification: {
      google: seo?.googleSiteVerification || undefined,
      other: seo?.bingSiteVerification ? { "msvalidate.01": seo.bingSiteVerification } : undefined,
    },
    icons: {
      icon: [
        { url: "/favicon.ico", sizes: "any" },
        { url: "/icon-192.png", type: "image/png", sizes: "192x192" },
        { url: "/icon-512.png", type: "image/png", sizes: "512x512" },
      ],
      apple: [{ url: "/apple-touch-icon.png", sizes: "180x180" }],
    },
  };
}

export default async function LocaleLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  if (!hasLocale(routing.locales, locale)) notFound();
  setRequestLocale(locale);

  const settings = await getSettings();
  const maintenance = settings.maintenanceMode?.enabled;

  // Mitarbeiter dürfen nie ausgesperrt werden — weder durch den
  // Wartungsmodus (sonst kommt niemand mehr ran, um ihn abzuschalten) noch
  // durch den Kopierschutz (stört bei der eigentlichen Admin-Arbeit).
  const clientId = await getSessionClientId();
  const isStaff = clientId ? await isAdminSession() : false;
  // Zusätzlicher Bypass ohne echten Login — z. B. für ein privates
  // Browserfenster, in dem man die Seite wie ein normaler Besuch sehen will,
  // siehe Vorschau-Passwort in den Einstellungen.
  const previewPassword = settings.maintenanceMode?.previewPassword || "";
  const hasBypass = maintenance && !isStaff && previewPassword ? await hasMaintenanceBypass(previewPassword) : false;

  const bannerText = (locale === "en" ? settings.bannerSettings?.textEn || settings.bannerSettings?.text : settings.bannerSettings?.text) || "";
  const bannerEnabled = Boolean(settings.bannerSettings?.enabled && bannerText.trim());

  return (
    <html
      lang={locale}
      className={`${geistSans.variable} ${geistMono.variable} ${quantify.variable} h-full antialiased`}
    >
      <body className="min-h-full flex flex-col bg-[var(--rk-bg)] text-[var(--rk-ink)]">
        {settings.seoSettings?.googleAnalyticsId && (
          <>
            <Script
              src={`https://www.googletagmanager.com/gtag/js?id=${settings.seoSettings.googleAnalyticsId}`}
              strategy="afterInteractive"
            />
            <Script id="ga4-init" strategy="afterInteractive">
              {`window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${settings.seoSettings.googleAnalyticsId}');`}
            </Script>
          </>
        )}
        <NextIntlClientProvider>
          {maintenance && !isStaff && !hasBypass ? (
            <MaintenancePage customMessage={settings.maintenanceMode?.message} previewEnabled={Boolean(previewPassword)} />
          ) : (
            <>
              {/* AdminAwareLayout entscheidet reaktiv (usePathname, siehe
                  Kommentar dort) ob/wo Banner, Top-Padding, Footer und
                  ScrollToTop erscheinen — [locale]/layout.tsx selbst (Server
                  Component) wird bei einer client-seitigen Navigation
                  zwischen Geschwister-Routen nicht neu ausgeführt, ein hier
                  nur einmalig berechnetes isAdminRoute bliebe sonst nach dem
                  ersten Seitenaufruf stehen. */}
              <AdminAwareLayout
                bannerEnabled={bannerEnabled}
                banner={<SiteBanner text={bannerText} />}
                footer={<SiteFooter settings={settings} />}
                scrollToTop={<ScrollToTop />}
              >
                <SiteHeader isStaff={isStaff} bannerEnabled={bannerEnabled} />
                {children}
              </AdminAwareLayout>
              <CopyProtection options={isStaff ? undefined : settings.copyProtection} />
            </>
          )}
          {/* Bewusst außerhalb der Wartungsmodus-Verzweigung — der Chat soll
              als Kontaktmöglichkeit auch dann erreichbar bleiben, wenn die
              Seite sonst den Wartungshinweis zeigt. */}
          <LiveChat
            enabled={settings.liveChat?.enabled}
            tawkPropertyId={settings.liveChat?.tawkPropertyId}
            tawkWidgetId={settings.liveChat?.tawkWidgetId}
          />
          {/* Nicht für eingeloggte Mitarbeiter — sonst würde die eigene
              Navigation durchs Admin-Team die Besucherzahlen verfälschen. */}
          {!isStaff && !maintenance && <PageViewTracker />}
        </NextIntlClientProvider>
      </body>
    </html>
  );
}
