import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Script from "next/script";
import "../../../styles/globals.css";
import { I18nProvider } from "@/lib/i18n/context";
import { siteUrl } from "@/lib/seo/site";

type Locale = "de" | "en";

const locales: Locale[] = ["de", "en"];

function isLocale(value: string): value is Locale {
  return value === "de" || value === "en";
}

// Keyword-Auswahl basiert auf realen Google-Keyword-Planner-Daten aus
// receipt_scanner_to_excel_blueprint.md (DE/US-Suchvolumen & CPC), nicht auf
// Schätzungen — Reihenfolge nach Suchvolumen/Relevanz für diese Landingpage.
const meta: Record<Locale, { title: string; description: string; keywords: string[] }> = {
  de: {
    title: "Kassenbon scannen & als Excel exportieren | ScanReceipts",
    description:
      "Ein Foto, fertige Excel in Sekunden: KI liest Kassenbons & Rechnungen, rechnet jede Summe nach und exportiert als Dual-Sheet Excel oder CSV.",
    keywords: [
      "kassenbon scanner",
      "belege scannen",
      "belege scanner",
      "belege digitalisieren",
      "kassenbon scannen excel",
      "kassenbon in excel umwandeln",
      "belegscanner",
      "scanner für belege",
      "scanner für rechnungen",
      "digitale belegerfassung",
      "quittungen scannen app",
      "spesen erfassen",
      "bewirtungsbelege excel",
    ],
  },
  en: {
    title: "Scan Receipts, Export to Excel Instantly | ScanReceipts",
    description:
      "One photo, finished Excel in seconds: AI reads receipts & invoices, verifies every total, and exports clean Dual-Sheet Excel or CSV.",
    keywords: [
      "receipt scanner",
      "receipt scanner app",
      "receipt tracker",
      "ocr receipt scanner",
      "ai receipt scanner",
      "scan receipt to excel",
      "receipt scanning software",
      "invoice scanner",
      "receipt scanner that categorizes",
      "receipts to excel",
      "expense receipt scanner",
      "best receipt scanner app",
    ],
  },
};

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

// Bewusst KEIN `dynamicParams = false`: unbekannte Locales (z. B. /fr) würden
// sonst intern einen NoFallbackError werfen, der im Produktiv-Log als
// "Error: Internal: NoFallbackError" erscheint, obwohl der Client korrekt 404
// bekommt. Stattdessen wird die Locale unten in der Layout-Komponente
// validiert und per notFound() sauber als 404 ausgeliefert (kein Duplicate
// Content, kein Error-Log). generateStaticParams prerendert weiterhin de/en.

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}): Promise<Metadata> {
  const { locale } = await params;
  const lang = isLocale(locale) ? locale : "en";
  const { title, description, keywords } = meta[lang];
  const canonical = `${siteUrl}/${lang}`;

  return {
    metadataBase: new URL(siteUrl),
    title,
    description,
    keywords,
    icons: {
      icon: "/icon.png",
      apple: "/apple-icon.png",
    },
    alternates: {
      canonical,
      languages: {
        de: `${siteUrl}/de`,
        en: `${siteUrl}/en`,
        "x-default": `${siteUrl}/en`,
      },
    },
    openGraph: {
      type: "website",
      url: canonical,
      siteName: "ScanReceipts",
      title,
      description,
      locale: lang === "de" ? "de_DE" : "en_US",
      alternateLocale: lang === "de" ? "en_US" : "de_DE",
      // No explicit `images` here on purpose: the `opengraph-image.tsx` file
      // in this route segment generates a proper 1200x630 social card and
      // Next.js auto-wires it into both openGraph and twitter metadata.
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
    },
    robots: {
      index: true,
      follow: true,
      googleBot: { index: true, follow: true, "max-image-preview": "large" },
    },
  };
}

export default async function LocaleLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const lang = isLocale(locale) ? locale : "en";

  if (!isLocale(locale)) {
    // Unbekannte Locale → sauber 404 (not-found.tsx des Segments), statt
    // dynamisch mit Fallback-Sprache zu rendern oder einen internen
    // NoFallbackError ins Log zu werfen.
    notFound();
  }

  const { description } = meta[lang];
  const currency = lang === "de" ? "EUR" : "USD";

  // Organization + SoftwareApplication structured data. Deliberately no
  // aggregateRating/review markup — fabricating those trips Google's
  // structured-data spam policy, and there are no real reviews yet.
  const jsonLd = {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "Organization",
        "@id": `${siteUrl}/#organization`,
        name: "ScanReceipts",
        url: siteUrl,
        logo: `${siteUrl}/icon.png`,
      },
      {
        "@type": "SoftwareApplication",
        "@id": `${siteUrl}/${lang}/#software`,
        name: "ScanReceipts",
        applicationCategory: "BusinessApplication",
        operatingSystem: "Web",
        url: `${siteUrl}/${lang}`,
        description,
        offers: {
          "@type": "Offer",
          price: "0",
          priceCurrency: currency,
          description:
            lang === "de"
              ? "Kostenloser Einstieg mit 15 Gratis-Scans pro Monat"
              : "Free to start with 15 free scans per month",
        },
      },
    ],
  };

  return (
    <html lang={lang} className="scroll-smooth">
      <body className="min-h-screen bg-[#F6F9FF] text-[#161C22] font-sans antialiased selection:bg-[#161C22] selection:text-white">
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
        />
        <I18nProvider>{children}</I18nProvider>
        {process.env.NEXT_PUBLIC_UMAMI_SRC && process.env.NEXT_PUBLIC_UMAMI_ID && (
          <Script
            defer
            src={process.env.NEXT_PUBLIC_UMAMI_SRC}
            data-website-id={process.env.NEXT_PUBLIC_UMAMI_ID}
            strategy="afterInteractive"
          />
        )}
      </body>
    </html>
  );
}
