import type { Metadata } from "next";

import { Container } from "@/components/Container";
import { getCachedStudiesWithMeta } from "@/lib/studies/cache";

import { StudiesList } from "./StudiesList";

/**
 * /studies — live feed of recent orthopaedic studies from PubMed.
 *
 * This page is a server component. It pulls the cached `{ items, fetchedAt }`
 * entry from the PubMed adapter (6-hour revalidate, tagged `"studies"`) and
 * hands the list to a client component for filtering and rendering. If the
 * fetch fails the cache layer returns `[]` and we render a graceful empty
 * state so the page never hard-fails.
 */

export const metadata: Metadata = {
  title: "Studies",
  description:
    "Live feed of recent research from the top orthopaedic journals, auto-curated from PubMed and refreshed throughout the day.",
  openGraph: {
    title: "Studies | OrthoGlobe",
    description:
      "Live feed of recent research from the top orthopaedic journals, auto-curated from PubMed.",
  },
};

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);
}

export default async function StudiesIndexPage() {
  const { items: studies, fetchedAt } = await getCachedStudiesWithMeta();

  return (
    <>
      <section className="bg-gradient-to-b from-[var(--color-mist)]/60 to-white pt-10 pb-10 md:pt-14 md:pb-12">
        <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)]">
            Studies
          </h1>
          <p className="mt-6 max-w-3xl text-[18px] md:text-[20px] leading-relaxed text-[var(--color-slate)]">
            Recent research from the top orthopaedic journals — auto-curated from
            PubMed and refreshed throughout the day.
          </p>
          <div className="mt-6 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] font-semibold text-[var(--color-slate)]">
            <span>
              <span className="text-[var(--color-ink)]">{studies.length}</span>{" "}
              studies in the last 180 days
            </span>
            <span className="text-[var(--color-line)]">·</span>
            <span>12 journals tracked</span>
            <span className="text-[var(--color-line)]">·</span>
            <span>Source: PubMed (NCBI)</span>
            {fetchedAt && (
              <>
                <span className="text-[var(--color-line)]">·</span>
                <span className="inline-flex items-center gap-1.5">
                  <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>
                </span>
              </>
            )}
          </div>
        </Container>
      </section>

      <Container className="pb-24">
        {studies.length === 0 ? (
          <div className="mx-auto mt-12 max-w-2xl rounded-lg border border-dashed border-[var(--color-line)] bg-[var(--color-mist)]/40 p-10 text-center">
            <h2 className="font-display text-[22px] font-bold text-[var(--color-ink)]">
              The feed is catching up
            </h2>
            <p className="mt-3 text-[15px] leading-relaxed text-[var(--color-slate)]">
              We couldn&apos;t reach PubMed right now. Please refresh in a few
              minutes — new studies will appear here automatically once the
              upstream feed recovers.
            </p>
            <a
              href="https://pubmed.ncbi.nlm.nih.gov/?term=orthopaedics"
              target="_blank"
              rel="noopener noreferrer"
              className="mt-6 inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
            >
              Search PubMed directly →
            </a>
          </div>
        ) : (
          <div className="pt-10">
            <StudiesList studies={studies} />
          </div>
        )}
      </Container>
    </>
  );
}
