import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { draftMode } from "next/headers";
import { Reveal } from "../../components/Reveal";
import { Footer } from "../../components/Footer";
import { RichText } from "../../components/RichText";
import { LivePostContent } from "./components/LivePostContent";
import { getBlogPosts, getPostBySlug, getCompanySettings } from "../../lib/payload";
import { formatDate } from "../../lib/format";
import { buildArticleSchema } from "../../lib/structuredData";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPostBySlug(slug);
  if (!post) return { title: "Beitrag nicht gefunden" };

  // Each falls back to the normal field when its SEO override (Posts.ts's
  // "SEO" collapsible group) is empty — filling those in is optional, a
  // post already has sensible metadata without them.
  const title = post.seoTitle || post.title;
  const description = post.seoDescription || post.excerpt;
  const image = post.seoImage || post.thumbnail;

  return {
    title,
    description,
    alternates: { canonical: `/blog/${post.slug}` },
    openGraph: {
      title: `${title} | einfach produktiv.`,
      description,
      url: `/blog/${post.slug}`,
      type: "article",
      images: image ? [{ url: image }] : undefined,
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: image ? [image] : undefined,
    },
  };
}

export default async function BlogDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const { isEnabled: isPreview } = await draftMode();
  const post = await getPostBySlug(slug, { draft: isPreview });
  if (!post) notFound();

  // "Weiterlesen" — the chronologically next-older post, wrapping around
  // to the newest post from the oldest one. Not getBlogPosts()'s own
  // -featured,-publishedAt order: picking "the first of the top 4 that
  // isn't this one" made nearly every post's Weiterlesen converge on the
  // same one or two most-recent posts (reported 2026-08-29). Sorting
  // purely by publishedAt here instead makes every post point somewhere
  // different, cycling through the whole archive one post at a time.
  const allPosts = await getBlogPosts(100);
  const byDate = [...allPosts].sort((a, b) => new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime());
  const currentIndex = byDate.findIndex((p) => p.slug === post.slug);
  const nextPost = currentIndex === -1 || byDate.length < 2 ? null : byDate[(currentIndex + 1) % byDate.length];
  const seller = await getCompanySettings();
  const articleSchema = buildArticleSchema(post, seller);

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(articleSchema) }} />
      <main className="flex flex-col flex-1 bg-bg-base">
        {isPreview ? (
          <LivePostContent initialPost={post} />
        ) : (
          <>
            <Reveal className="flex flex-col gap-4 items-start pt-10 pb-8 px-[var(--layout-padding-x)] w-full max-w-[48rem] mx-auto">
              <div className="flex items-center gap-2 font-semibold text-text-muted text-body-sm uppercase tracking-wide">
                <span>{post.categories.join(", ")}</span>
                <span>•</span>
                <span>{post.readTime} Min</span>
              </div>
              {/* Playfair (not Lora), matching the actual Figma title's font —
                  same "hero headline" family as Hero.tsx/TodoKartenHero.tsx/
                  WeeklyImpulsesHero.tsx use, not the Lora section-heading style
                  the legal pages use. Sized down from text-display (Figma's
                  literal 44px), but text-h-feature (max 40px) read too small —
                  no named token sits between the two, so this is a one-off
                  fluid(36, 48) clamp using the project's own fluid.ts formula
                  (768px Tablet floor → 1440px Desktop cap), landing between
                  them instead of jumping all the way back to text-display. */}
              <p
                className="font-semibold text-[clamp(2.25rem,1.393rem+1.786vw,3rem)] text-text-primary leading-[1.15]"
                style={{ fontFamily: "var(--font-playfair)" }}
              >
                {post.title}
              </p>
              <p className="text-body text-text-muted">{post.excerpt}</p>
              <div className="flex items-center gap-3 pt-1">
                <div className="relative size-9 shrink-0 rounded-full overflow-hidden">
                  <Image alt="Björn" src="/about-author.jpg" fill sizes="36px" className="object-cover" />
                </div>
                <p className="text-body-sm text-text-primary">
                  Björn <span className="text-text-muted">• {formatDate(post.publishedAt)}</span>
                </p>
              </div>
            </Reveal>

            {post.thumbnail && (
              // max-w-[70rem] (1120px) — exact Figma value (node 4667:379):
              // 1120px hero vs. 700px body = 1.6x, not full-bleed to the page
              // edge (an earlier version guessed that, which came out far too
              // wide) and not capped to the body column either.
              <Reveal delay={0.1} className="w-full max-w-[70rem] mx-auto px-[var(--layout-padding-x)] pb-10">
                <div className="relative w-full aspect-[1120/460] rounded-md overflow-hidden bg-bg-muted">
                  <Image alt="" src={post.thumbnail} fill sizes="(min-width: 1120px) 70rem, 100vw" className="object-cover" />
                </div>
              </Reveal>
            )}

            <Reveal delay={0.15} className="w-full max-w-[48rem] mx-auto px-[var(--layout-padding-x)] pb-10">
              <RichText content={post.content} quoteLabel={post.quoteLabel} />
            </Reveal>
          </>
        )}

        <Reveal delay={0.15} className="flex flex-col gap-6 w-full max-w-[48rem] mx-auto px-[var(--layout-padding-x)] pb-10">
          {/* "Passend dazu" — per-post CMS content now (Posts.relatedProduct),
              not a hardcoded flagship-product link. If the post has no
              related product (or that product has no detail page to send
              "Entdecken" to), falls back to a "Nicht verpassen" newsletter
              card instead of leaving this slot empty — /newsletter had no
              incoming link anywhere in the site despite being a fully
              built page (WERKZEUGE_ROUTES and TestimonialsPage already
              treated it as a first-class destination), and blog readers
              are exactly its target audience. Matches the actual built
              Figma frame exactly (node 4674:349, fetched via
              get_design_context) — 1px border-border, rounded-md,
              px-9/py-7 padding; an earlier version guessed a plain
              borderless row instead, which get_metadata's structural dump
              didn't reveal (frame-level stroke/padding/radius aren't
              visible there, only get_design_context shows those). */}
          {post.relatedProduct?.href ? (
            <Link
              href={post.relatedProduct.href}
              className="group flex items-center gap-4 sm:gap-6 border border-border rounded-md px-5 py-5 sm:px-9 sm:py-7 hover:border-brand transition-colors"
            >
              <div className="relative w-16 h-[4.6875rem] shrink-0 rounded-sm overflow-hidden">
                <Image alt="" src={post.relatedProduct.image} fill sizes="64px" className="object-cover" />
              </div>
              <div className="flex-1 min-w-0 flex flex-col gap-2.5">
                <p className="font-bold text-[0.8125rem] text-brand">Passend dazu:</p>
                {/* Stacked below sm: — the fixed w-[19rem] title column plus
                    "Entdecken" on the same row overflowed a mobile-width
                    card (fixed 2026-07-24). "Entdecken" wraps to its own
                    line with a little space above it; back to the
                    side-by-side row (matching Figma) from sm: up, where
                    there's room for both. */}
                <div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 w-full">
                  {/* w-[19rem] (305px) only from sm: — matches Figma's
                      title-col exactly there, so the description wraps at
                      the same point instead of stretching out to fill the
                      space before "Entdecken"; full width below sm:. */}
                  <div className="flex flex-col gap-2 items-start w-full sm:w-[19rem] sm:shrink-0">
                    <p
                      className="font-semibold text-[1.375rem] text-text-primary sm:whitespace-nowrap"
                      style={{ fontFamily: "var(--font-lora)" }}
                    >
                      {post.relatedProduct.name}
                    </p>
                    <p className="text-[0.9375rem] text-text-muted leading-[1.45]">{post.relatedProduct.descriptionText}</p>
                  </div>
                  <span className="flex items-center gap-1.5 font-bold text-[0.875rem] text-text-primary whitespace-nowrap mt-1 sm:mt-0">
                    Entdecken
                    <svg
                      viewBox="0 0 20 20"
                      className="size-3.5 transition-transform duration-200 group-hover:translate-x-1"
                      fill="none"
                      aria-hidden="true"
                    >
                      <path d="M4 10h12m0 0-5-5m5 5-5 5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </span>
                </div>
              </div>
            </Link>
          ) : (
            <Link
              href="/newsletter"
              className="group flex items-center gap-4 sm:gap-6 border border-border rounded-md px-5 py-5 sm:px-9 sm:py-7 hover:border-brand transition-colors"
            >
              <div className="relative w-16 h-[4.6875rem] shrink-0 rounded-sm overflow-hidden">
                <Image alt="" src="/weekly-photo.png" fill sizes="64px" className="object-cover" />
              </div>
              <div className="flex-1 min-w-0 flex flex-col gap-2.5">
                <p className="font-bold text-[0.8125rem] text-brand">Nicht verpassen:</p>
                <div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 w-full">
                  <div className="flex flex-col gap-2 items-start w-full sm:w-[19rem] sm:shrink-0">
                    <p
                      className="font-semibold text-[1.375rem] text-text-primary sm:whitespace-nowrap"
                      style={{ fontFamily: "var(--font-lora)" }}
                    >
                      Wöchentliche Impulse
                    </p>
                    <p className="text-[0.9375rem] text-text-muted leading-[1.45]">
                      Jeden Mittwoch neue Denkanstöße direkt ins Postfach – kostenlos, jederzeit abbestellbar.
                    </p>
                  </div>
                  <span className="flex items-center gap-1.5 font-bold text-[0.875rem] text-text-primary whitespace-nowrap mt-1 sm:mt-0">
                    Abonnieren
                    <svg
                      viewBox="0 0 20 20"
                      className="size-3.5 transition-transform duration-200 group-hover:translate-x-1"
                      fill="none"
                      aria-hidden="true"
                    >
                      <path d="M4 10h12m0 0-5-5m5 5-5 5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </span>
                </div>
              </div>
            </Link>
          )}
        </Reveal>

        {/* Author bio — same hardcoded-brand-chrome reasoning as above;
            this is a single-author blog, there's no author field on the
            Posts collection to read from. */}
        <Reveal delay={0.2} className="w-full max-w-[48rem] mx-auto px-[var(--layout-padding-x)] pb-14">
          <div className="flex items-center gap-4 bg-bg-muted rounded-md p-6">
            <div className="relative size-14 shrink-0 rounded-full overflow-hidden">
              <Image alt="Björn" src="/about-author.jpg" fill sizes="56px" className="object-cover" />
            </div>
            <div className="flex flex-col gap-0.5">
              <p className="font-semibold text-body text-text-primary">Geschrieben von Björn.</p>
              <p className="text-body-sm text-text-muted">Führungskraft. Familienmensch.</p>
              <p className="text-body-sm text-text-muted">Gründer von einfach produktiv.</p>
            </div>
          </div>
        </Reveal>

        {nextPost && (
          // max-w-[58.75rem] (940px) — exact Figma value (node 4667:382),
          // deliberately wider than the 48rem body column (widened past
          // the 43.75rem/700px Figma value per user preference), matching
          // the original build's "Weiterlesen" card being wider than the
          // text column rather than symmetric to it.
          <Reveal delay={0.25} className="w-full max-w-[58.75rem] mx-auto px-[var(--layout-padding-x)] pb-16">
            <p
              className="font-semibold text-h-small text-text-primary mb-4"
              style={{ fontFamily: "var(--font-lora)" }}
            >
              Weiterlesen
            </p>
            <Link
              href={`/blog/${nextPost.slug}`}
              className="group flex flex-col sm:flex-row items-stretch border border-border rounded-md overflow-hidden transition-transform duration-300 hover:-translate-y-1"
            >
              <div className="relative w-full sm:w-64 aspect-video sm:aspect-auto shrink-0 bg-bg-muted">
                {nextPost.thumbnail && (
                  <Image alt="" src={nextPost.thumbnail} fill sizes="(min-width: 640px) 16rem, 100vw" className="object-cover" />
                )}
              </div>
              <div className="flex flex-col justify-center gap-2 p-6 min-w-0">
                <div className="flex items-center gap-2 font-semibold text-text-muted text-body-sm uppercase tracking-wide">
                  <span>{nextPost.categories.join(", ")}</span>
                  <span>•</span>
                  <span>{nextPost.readTime} Min</span>
                </div>
                <p
                  className="font-semibold text-h-small text-text-primary"
                  style={{ fontFamily: "var(--font-lora)" }}
                >
                  {nextPost.title}
                </p>
                <p className="flex items-center gap-1.5 text-body-sm text-text-muted line-clamp-1">
                  {nextPost.excerpt}
                  <svg
                    viewBox="0 0 20 20"
                    className="size-3.5 shrink-0 text-text-primary transition-transform duration-200 group-hover:translate-x-1"
                    fill="none"
                    aria-hidden="true"
                  >
                    <path d="M4 10h12m0 0-5-5m5 5-5 5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </p>
              </div>
            </Link>
          </Reveal>
        )}
      </main>
      <Footer />
    </>
  );
}
