import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import { ArrowUpRight } from "lucide-react";
import { Header } from "@/components/landing/Header";
import { Footer } from "@/components/landing/Footer";
import { RelatedReading } from "@/components/landing/RelatedReading";
import { siteUrl } from "@/lib/seo/site";
import { publicPath, publicUrl, type SeoSlugKey } from "@/lib/seo/slugs";

type Locale = "de" | "en";

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

const meta = {
  de: {
    title: "Blog: Belege scannen & OCR für Selbstständige | ScanReceipts",
    description:
      "Praktische Guides zu Beleg-OCR und Belege digitalisieren für Selbstständige, Freelancer und Privatpersonen.",
    keywords: ["belege blog", "kassenbon scannen guide", "beleg ocr guide"],
  },
  en: {
    title: "Blog: Receipt Scanning & OCR for Freelancers | ScanReceipts",
    description:
      "Practical guides on receipt OCR and digitizing receipts for freelancers, the self-employed, and anyone tired of typing.",
    keywords: ["receipt scanning blog", "receipt ocr guide", "digitize receipts guide"],
  },
} as const;

const posts = [
  {
    key: "blog/how-receipt-ocr-works" as const satisfies SeoSlugKey,
    eyebrow: { de: "TECHNIK ERKLÄRT", en: "TECHNICAL EXPLAINER" },
    title: {
      de: "So funktioniert Beleg-OCR wirklich (und warum viele Scanner-Apps Fehler machen)",
      en: "How Receipt OCR Actually Works (And Why Most Scanners Get It Wrong)",
    },
    description: {
      de: "Wie KI Kassenbons wirklich ausliest, warum Thermopapier eine Herausforderung ist und warum ein Rechen-Check nach der KI unverzichtbar ist.",
      en: "A plain-language technical explainer on receipt OCR and AI extraction — why thermal receipts are hard to read and why arithmetic verification matters.",
    },
  },
  {
    key: "blog/receipt-scanning-vs-manual-bookkeeping" as const satisfies SeoSlugKey,
    eyebrow: { de: "BELEGE ERFASSEN", en: "RECEIPT CAPTURE" },
    title: {
      de: "Kassenbon scannen statt abtippen: Was Selbstständige wirklich sparen",
      en: "Receipt Scanning vs. Manual Data Entry: What Freelancers Actually Save",
    },
    description: {
      de: "Ein ehrlicher Vergleich: Was das manuelle Abtippen von Belegen einen Freelancer wirklich an Zeit kostet – und wie ein Foto-Workflow Tippfehler abfängt.",
      en: "An honest breakdown of what manual receipt entry actually costs a freelancer in time, and how a photo-first workflow catches transcription errors early.",
    },
  },
  {
    key: "blog/receipt-to-excel-guide" as const satisfies SeoSlugKey,
    eyebrow: { de: "PRAKTISCHER RATGEBER", en: "PRACTICAL GUIDE" },
    title: {
      de: "Kassenbon in Excel umwandeln: Vom Foto zur fertigen Tabelle",
      en: "Receipt to Excel: The Fastest Way From Photo to Spreadsheet",
    },
    description: {
      de: "So wird aus einem Foto eines Kassenbons eine strukturierte Excel-Tabelle – ohne Zahlen abzutippen. Warum Vorlagen dabei nur begrenzt helfen.",
      en: "How to turn a photo of a receipt into a structured Excel spreadsheet without retyping numbers, and why a receipt excel template is a weaker starting point.",
    },
  },
  {
    key: "blog/organize-digital-receipts" as const satisfies SeoSlugKey,
    eyebrow: { de: "ORGANISATION", en: "GETTING ORGANIZED" },
    title: {
      de: "Belege digitalisieren und organisieren: So findest du sie später wieder",
      en: "How to Digitize and Organize Receipts So You Can Actually Find Them Later",
    },
    description: {
      de: "Warum Papierbelege auf Dauer unzuverlässig sind und wie du Kassenbons direkt beim Einkauf digitalisierst, damit du sie später in Sekunden wiederfindest.",
      en: "Why paper receipts fade and get lost, and how to digitize receipts the moment you get them so they stay searchable instead of buried in a drawer.",
    },
  },
  {
    key: "blog/simple-expense-tracking" as const satisfies SeoSlugKey,
    eyebrow: { de: "AUSGABEN & GEWOHNHEITEN", en: "SPENDING & HABITS" },
    title: {
      de: "Einfache Ausgabenverfolgung für Freelancer und Privatpersonen",
      en: "Simple Expense Tracking for Freelancers and Private Individuals",
    },
    description: {
      de: "Warum die meisten Ausgaben-Apps nach zwei Wochen wieder verschwinden – und wie eine Foto-first-Methode Ausgabenverfolgung endlich zur Gewohnheit macht.",
      en: "Why most expense tracker apps get abandoned after two weeks, and how a photo-first approach turns expense tracking into a habit that actually sticks.",
    },
  },
] as const;

const PUBLISHED = "2026-08-19";

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

  return {
    title: copy.title,
    description: copy.description,
    keywords: [...copy.keywords],
    alternates: {
      canonical,
      languages: {
        de: `${siteUrl}/de/blog`,
        en: `${siteUrl}/en/blog`,
        "x-default": `${siteUrl}/en/blog`,
      },
    },
    openGraph: {
      type: "website",
      url: canonical,
      siteName: "ScanReceipts",
      title: copy.title,
      description: copy.description,
      locale: lang === "de" ? "de_DE" : "en_US",
      alternateLocale: lang === "de" ? "en_US" : "de_DE",
      images: [{ url: `${siteUrl}/receipt-texture-hero.png`, width: 1672, height: 941 }],
    },
    twitter: { card: "summary_large_image", title: copy.title, description: copy.description },
    robots: {
      index: true,
      follow: true,
      googleBot: { index: true, follow: true, "max-image-preview": "large" },
    },
  };
}

export default async function BlogIndexPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const lang: Locale = isLocale(locale) ? locale : "en";
  if (!isLocale(locale)) notFound();
  const isDe = lang === "de";
  const canonical = `${siteUrl}/${lang}/blog`;

  const jsonLd = {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "BreadcrumbList",
        itemListElement: [
          { "@type": "ListItem", position: 1, name: isDe ? "Start" : "Home", item: `${siteUrl}/${lang}` },
          { "@type": "ListItem", position: 2, name: "Blog", item: canonical },
        ],
      },
      {
        "@type": "Blog",
        "@id": canonical,
        url: canonical,
        name: meta[lang].title,
        description: meta[lang].description,
        inLanguage: lang,
        blogPost: posts.map((post) => ({
          "@type": "BlogPosting",
          headline: post.title[lang],
          url: publicUrl(lang, post.key),
          datePublished: PUBLISHED,
        })),
      },
    ],
  };

  return (
    <div className="flex min-h-screen flex-col bg-[#F6F9FF] text-[#161C22] font-sans">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
      />
      <Header />
      <main className="flex-1 w-full">
        <section className="w-full py-20">
          <div className="max-w-[1440px] mx-auto px-4 sm:px-8 border-x border-[#E2E8F0]">
            <div className="mb-14 pb-6 border-b border-[#E2E8F0]">
              <div className="flex items-center gap-2 mb-3">
                <span className="w-2.5 h-2.5 bg-black" />
                <span className="font-mono text-xs uppercase tracking-caps font-semibold text-[#475569]">
                  {isDe ? "BLOG" : "BLOG"}
                </span>
              </div>
              <h1 className="font-display text-4xl sm:text-5xl lg:text-6xl font-bold tracking-tightest text-black leading-[1.05] max-w-3xl">
                {isDe
                  ? "Belege scannen und OCR – praktisch erklärt."
                  : "Receipt scanning and OCR — explained practically."}
              </h1>
              <p className="mt-5 text-base sm:text-lg text-[#475569] max-w-2xl leading-relaxed">
                {isDe
                  ? "Keine Marketing-Floskeln – konkrete Guides für Selbstständige, Freelancer und alle, die Belege digitalisieren wollen."
                  : "No marketing fluff — concrete guides for freelancers, the self-employed, and anyone digitizing receipts."}
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {posts.map((post) => (
                <Link
                  key={post.key}
                  href={publicPath(lang, post.key)}
                  className="group flex flex-col justify-between bg-white border border-[#E2E8F0] p-7 sm:p-8 hover:border-black transition-colors"
                >
                  <div>
                    <div className="flex items-center gap-2 mb-4">
                      <span className="w-1.5 h-1.5 bg-black" />
                      <span className="font-mono text-[11px] uppercase tracking-caps font-semibold text-[#475569]">
                        {post.eyebrow[lang]}
                      </span>
                    </div>
                    <h2 className="font-display text-xl sm:text-2xl font-bold tracking-tight text-black leading-snug mb-3">
                      {post.title[lang]}
                    </h2>
                    <p className="text-sm text-[#475569] leading-relaxed">{post.description[lang]}</p>
                  </div>
                  <div className="mt-6 flex items-center gap-1.5 font-mono text-xs uppercase tracking-caps font-semibold text-black">
                    <span>{isDe ? "Artikel lesen" : "Read article"}</span>
                    <ArrowUpRight className="w-3.5 h-3.5 transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />
                  </div>
                </Link>
              ))}
            </div>

            <RelatedReading
              lang={lang}
              heading={
                isDe
                  ? "Keyword-Seiten und Vergleiche"
                  : "Keyword pages and comparisons"
              }
              keys={["ocr", "freelancer", "expensify", "lexoffice"]}
            />
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
}
