import type { Metadata } from "next";

import { Button } from "@/components/Button";
import { Container } from "@/components/Container";
import { getCachedNewsWithMeta } from "@/lib/news/cache";
import { NEWS_SOURCES } from "@/lib/news/sources";
import { uniqueYears } from "@/lib/news/format";

import { NewsFilters } from "./NewsFilters";

const REFRESHED_FMT = new Intl.DateTimeFormat("en-GB", {
  year: "numeric",
  month: "short",
  day: "numeric",
  hour: "2-digit",
  minute: "2-digit",
  timeZone: "UTC",
  timeZoneName: "short",
});

function formatRefreshedAt(iso: string): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "";
  return REFRESHED_FMT.format(d);
}

/**
 * Live orthopaedic news aggregator.
 *
 * Server component — all work happens at request time against a cache
 * that revalidates every 6 hours (and on-demand via
 * POST /api/refresh/news). We do NOT rehost publisher content: each card
 * shows title + source + date + excerpt, with a prominent outbound link
 * to the original article. The internal /news/[id] page exists as a
 * neutral attribution landing zone.
 *
 * The list is sorted newest-first and deduped by canonical link. If
 * every source fails we render an empty state rather than a server
 * error — news is non-critical content and the rest of the site should
 * keep working.
 */

export const metadata: Metadata = {
  title: "Orthopaedic News",
  description:
    "Live aggregated news from Healio, Orthopedics This Week, Becker's Spine Review, BoneZone, and Orthopedic Design & Technology — curated by the OrthoGlobe collaborative.",
  openGraph: {
    title: "Orthopaedic News — OrthoGlobe",
    description:
      "Live aggregated news from curated orthopaedic publishers, refreshed every 6 hours.",
  },
};

// Allow ISR; the unstable_cache inside fetchAllNews owns refresh timing.
export const revalidate = 21600;

export default async function NewsIndexPage() {
  const { items, fetchedAt } = await getCachedNewsWithMeta();

  const sources = NEWS_SOURCES.map((s) => ({ id: s.id, name: s.name }));
  const years = uniqueYears(items);

  return (
    <>
      {/* Gradient hero matching /blog's visual language. */}
      <section className="relative overflow-hidden bg-white pt-10 pb-10 md:pt-14 md:pb-12">
        <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-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
            Live Feed
          </div>
          <h1 className="mt-3 font-display text-[40px] md:text-[56px] font-extrabold leading-[1.05] tracking-[-0.025em] text-[var(--color-ink)]">
            Orthopaedic news, in one place.
          </h1>
          <p className="mt-6 max-w-3xl text-[18px] md:text-[20px] leading-relaxed text-[var(--color-slate)]">
            A live aggregator of curated orthopaedic publishers — spine,
            joints, trauma, sports medicine, devices, and research. Updated
            every six hours. All links go directly back to the original
            source.
          </p>
          <div className="mt-8 flex flex-wrap items-center gap-3 text-[12px] text-[var(--color-slate)]">
            <span className="font-bold uppercase tracking-wider">
              Sources
            </span>
            {NEWS_SOURCES.map((s) => (
              <a
                key={s.id}
                href={s.homepageUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="rounded-full border border-[var(--color-line)] px-3 py-1 transition-colors hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
              >
                {s.name}
              </a>
            ))}
          </div>
          {fetchedAt && (
            <div className="mt-5 inline-flex items-center gap-1.5 text-[12px] font-semibold text-[var(--color-slate)]">
              <span
                aria-hidden
                className="inline-block h-1.5 w-1.5 rounded-full bg-[var(--color-blue)]"
              />
              <span>
                Last refreshed{" "}
                <time dateTime={fetchedAt} className="text-[var(--color-ink)]">
                  {formatRefreshedAt(fetchedAt)}
                </time>
              </span>
            </div>
          )}
        </Container>
      </section>

      <Container className="pb-24 pt-6">
        {items.length === 0 ? (
          <div className="mx-auto flex max-w-xl flex-col items-center py-20 text-center">
            <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              Standby
            </div>
            <h2 className="mt-3 font-display text-[28px] font-extrabold leading-tight tracking-[-0.015em] text-[var(--color-ink)]">
              The feed is catching its breath.
            </h2>
            <p className="mt-4 text-[16px] leading-relaxed text-[var(--color-slate)]">
              We couldn&apos;t reach any of our curated sources right now.
              This usually resolves itself within a few minutes — please
              check back shortly.
            </p>
            <div className="mt-6">
              <Button href="/" variant="ghost">
                Back to home
              </Button>
            </div>
          </div>
        ) : (
          <NewsFilters items={items} sources={sources} years={years} />
        )}
      </Container>
    </>
  );
}
