import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";

import { Container } from "@/components/Container";
import { getCachedNews } from "@/lib/news/cache";
import { formatLongDate } from "@/lib/news/format";
import { getSourceById } from "@/lib/news/sources";
import type { NewsItem } from "@/lib/news/types";

import { CopyLinkButton } from "./CopyLinkButton";

/**
 * Attribution landing page for an aggregated news item.
 *
 * We deliberately do NOT rehost the article body: aggregating full
 * publisher content would raise ToS and copyright issues. Instead, this
 * page acts as a neutral staging point that shows the title, source,
 * author, date, and excerpt, then funnels the reader straight out to
 * the original article with a prominent primary CTA.
 *
 * Why have this page at all? Three reasons:
 *   1. Stable internal URL that can be shared on socials.
 *   2. A place to show "Related from {source}" as a discovery aid.
 *   3. Clear attribution and outbound consent before sending traffic
 *      off-site — better UX than a surprise new-tab jump from a list.
 *
 * `generateStaticParams` prerenders the top 50 items so the most common
 * deep-links are served statically. Any id past the top 50 falls back
 * to on-demand rendering at the same cached data source.
 */

type Params = { id: string };

export async function generateStaticParams(): Promise<Params[]> {
  try {
    const items = await getCachedNews();
    return items.slice(0, 50).map((item) => ({ id: item.id }));
  } catch {
    // Never let a broken feed crash the build.
    return [];
  }
}

async function findById(id: string): Promise<NewsItem | undefined> {
  const items = await getCachedNews();
  return items.find((item) => item.id === id);
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { id } = await params;
  const item = await findById(id);
  if (!item) return { title: "News item not found" };
  return {
    title: `${item.title} — ${item.sourceName}`,
    description: item.excerpt,
    openGraph: {
      title: item.title,
      description: item.excerpt,
      type: "article",
      url: item.link,
      images: item.imageUrl ? [item.imageUrl] : undefined,
    },
  };
}

export default async function NewsDetailPage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { id } = await params;
  const item = await findById(id);
  if (!item) notFound();

  const source = getSourceById(item.sourceId);
  const allItems = await getCachedNews();
  const related = allItems
    .filter((other) => other.sourceId === item.sourceId && other.id !== item.id)
    .slice(0, 6);

  return (
    <>
      <section className="relative overflow-hidden bg-white pt-10 pb-10 md:pt-14 md:pb-14">
        <div
          aria-hidden
          className="pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(ellipse_at_top,_var(--color-mist)_0%,_transparent_60%)]"
        />
        <Container>
          <div className="text-[12px] font-semibold">
            <Link
              href="/news"
              className="text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
            >
              ← All news
            </Link>
          </div>
          <div className="mt-6 flex flex-wrap items-center gap-3 text-[11px] font-bold uppercase tracking-wider">
            <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-blue)]/20 bg-[var(--color-blue)]/10 px-3 py-1 text-[var(--color-blue-deep)]">
              <span
                aria-hidden
                className="inline-block h-1.5 w-1.5 rounded-full bg-[var(--color-blue)]"
              />
              {item.sourceName}
            </span>
            <span className="text-[var(--color-slate)]">
              {formatLongDate(item.pubDate)}
            </span>
            {item.author && (
              <span className="text-[var(--color-slate)]">
                by {item.author}
              </span>
            )}
          </div>
          <h1 className="mt-4 max-w-4xl font-display text-[34px] md:text-[48px] font-extrabold leading-[1.08] tracking-[-0.02em] text-[var(--color-ink)]">
            {item.title}
          </h1>
          {item.excerpt && (
            <p className="mt-6 max-w-3xl text-[18px] md:text-[20px] leading-relaxed text-[var(--color-slate)]">
              {item.excerpt}
            </p>
          )}
          <div className="mt-8 flex flex-wrap items-center gap-3">
            <a
              href={item.link}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-blue)] px-6 py-3 text-[15px] font-semibold text-white shadow-sm transition-all duration-200 hover:scale-[1.02] hover:bg-[var(--color-blue-deep)] hover:shadow-md motion-reduce:transform-none"
            >
              Read original at {item.sourceName} ↗
            </a>
          </div>
          {item.imageUrl && (
            <div className="mt-10 overflow-hidden rounded-xl border border-[var(--color-line)] bg-[var(--color-mist)]">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={item.imageUrl}
                alt={item.title}
                loading="lazy"
                decoding="async"
                referrerPolicy="no-referrer"
                className="aspect-[16/9] w-full object-cover"
              />
            </div>
          )}
        </Container>
      </section>

      <Container className="pb-24">
        <div className="max-w-3xl rounded-xl border border-[var(--color-line)] bg-[var(--color-mist)] p-8 md:p-10">
          <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
            Attribution
          </div>
          <h2 className="mt-2 font-display text-[22px] font-extrabold leading-tight tracking-[-0.01em] text-[var(--color-ink)]">
            This article lives on {item.sourceName}.
          </h2>
          <p className="mt-3 text-[15px] leading-relaxed text-[var(--color-slate)]">
            OrthoGlobe aggregates titles and excerpts from curated
            orthopaedic publishers — we don&apos;t rehost article text.
            Follow the link below to read the full story at{" "}
            {item.sourceName}.
          </p>
          <div className="mt-6 flex flex-wrap items-center gap-3">
            <a
              href={item.link}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-blue)] px-6 py-3 text-[15px] font-semibold text-white shadow-sm transition-all duration-200 hover:scale-[1.02] hover:bg-[var(--color-blue-deep)] hover:shadow-md motion-reduce:transform-none"
            >
              Read at {item.sourceName} ↗
            </a>
            <CopyLinkButton url={item.link} />
          </div>
          {source && (
            <div className="mt-4 text-[12px] text-[var(--color-slate)]">
              Publisher homepage:{" "}
              <a
                href={source.homepageUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="underline hover:text-[var(--color-blue)]"
              >
                {source.homepageUrl}
              </a>
            </div>
          )}
        </div>

        {related.length > 0 && (
          <div className="mt-16 max-w-5xl">
            <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              More from {item.sourceName}
            </div>
            <h2 className="mt-3 font-display text-[28px] md:text-[32px] font-extrabold leading-tight tracking-[-0.015em] text-[var(--color-ink)]">
              Related stories
            </h2>
            <ul className="mt-8 divide-y divide-[var(--color-line)] border-y border-[var(--color-line)]">
              {related.map((r) => (
                <li key={r.id} className="py-5">
                  <Link
                    href={`/news/${r.id}`}
                    className="group flex flex-col gap-1 md:flex-row md:items-baseline md:justify-between md:gap-6"
                  >
                    <span className="font-display text-[17px] font-bold leading-snug text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                      {r.title}
                    </span>
                    <span className="shrink-0 text-[12px] uppercase tracking-wider text-[var(--color-slate)]">
                      {formatLongDate(r.pubDate)}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        )}
      </Container>
    </>
  );
}
