import Image from "next/image";
import Link from "next/link";
import { ArrowRight } from "lucide-react";
import { Container } from "@/components/Container";
import type { StudiesCacheEntry } from "@/lib/studies/cache";
import type { NewsCacheEntry } from "@/lib/news/cache";
import { formatAgo } from "./format-ago";

type Props = {
  studies: StudiesCacheEntry;
  news: NewsCacheEntry;
};

function formatDate(iso: string): string {
  if (!iso) return "";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "";
  return d.toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}

/**
 * Two-column live feeds band showing the 4 latest studies and the 4 latest
 * news items. Stacks on mobile. Relative-time indicator is computed once per
 * render from each cache entry's `fetchedAt` so readers can see how fresh
 * the data is.
 */
export function LiveFeedsSection({ studies, news }: Props) {
  const topStudies = studies.items.slice(0, 4);
  const topNews = news.items.slice(0, 4);
  const studiesAgo = formatAgo(studies.fetchedAt);
  const newsAgo = formatAgo(news.fetchedAt);

  return (
    <section className="border-y border-[var(--color-line)] bg-[#fafbff] py-12 md:py-16">
      <Container>
        <div className="grid items-center gap-10 md:grid-cols-[minmax(0,1fr)_minmax(0,0.55fr)] md:gap-12">
          <div className="max-w-2xl">
            <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-[var(--color-blue)]">
              Live feeds
            </div>
            <h2 className="mt-4 font-display text-[36px] md:text-[46px] font-extrabold leading-[1.05] tracking-[-0.02em] text-[var(--color-ink)]">
              Evidence, delivered daily.
            </h2>
            <p className="mt-5 text-[17px] leading-relaxed text-[var(--color-slate)]">
              Fresh orthopaedic research from PubMed and curated headlines from
              the journals and societies that matter.
            </p>
          </div>
          <div className="relative hidden md:block">
            <div className="relative overflow-hidden rounded-2xl border border-[var(--color-line)] bg-white shadow-[0_20px_48px_rgba(10,14,40,0.08)]">
              <div className="relative aspect-[16/9] w-full">
                <Image
                  src="/photos/exam-prep/library-reading.jpg"
                  alt="Open medical journal and study materials on a library desk"
                  fill
                  sizes="(min-width: 768px) 35vw, 100vw"
                  className="object-cover"
                />
                <div className="absolute inset-0 bg-[linear-gradient(to_top,rgba(10,14,40,0.35),transparent_55%)]" />
                <div className="absolute inset-0 bg-[linear-gradient(120deg,rgba(30,64,255,0.18),transparent_55%)]" />
              </div>
            </div>
          </div>
        </div>

        <div className="mt-16 grid gap-10 lg:grid-cols-2 lg:gap-12">
          {/* Studies column */}
          <div className="rounded-2xl border border-[var(--color-line)] bg-white p-8 md:p-10">
            <div className="flex items-baseline justify-between gap-4">
              <div>
                <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-[var(--color-blue)]">
                  Studies
                </div>
                <h3 className="mt-2 font-display text-[24px] font-extrabold tracking-[-0.015em] text-[var(--color-ink)]">
                  Latest from PubMed
                </h3>
              </div>
              {studiesAgo ? (
                <div className="shrink-0 text-[12px] font-medium text-[var(--color-slate)]">
                  Updated {studiesAgo}
                </div>
              ) : null}
            </div>

            <ul className="mt-6 divide-y divide-[var(--color-line)]">
              {topStudies.length === 0 ? (
                <li className="py-6 text-[14px] text-[var(--color-slate)]">
                  No studies available right now.
                </li>
              ) : (
                topStudies.map((s) => (
                  <li key={s.pmid} className="py-5 first:pt-0 last:pb-0">
                    <Link
                      href={`/studies/${s.pmid}`}
                      className="group block"
                    >
                      <div className="flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-wider">
                        <span className="rounded-full bg-[var(--color-mist)] px-2 py-0.5 text-[var(--color-blue)]">
                          {s.journal || "PubMed"}
                        </span>
                        <span className="text-[var(--color-slate)]">
                          {formatDate(s.pubDate)}
                        </span>
                      </div>
                      <div className="mt-2 text-[15px] font-semibold leading-snug text-[var(--color-ink)] transition-colors group-hover:text-[var(--color-blue)]">
                        {s.title}
                      </div>
                    </Link>
                  </li>
                ))
              )}
            </ul>

            <div className="mt-8">
              <Link
                href="/studies"
                className="inline-flex items-center gap-1.5 text-[14px] font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
              >
                Browse all studies
                <ArrowRight size={16} strokeWidth={1.75} aria-hidden />
              </Link>
            </div>
          </div>

          {/* News column */}
          <div className="rounded-2xl border border-[var(--color-line)] bg-white p-8 md:p-10">
            <div className="flex items-baseline justify-between gap-4">
              <div>
                <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-[var(--color-blue)]">
                  News
                </div>
                <h3 className="mt-2 font-display text-[24px] font-extrabold tracking-[-0.015em] text-[var(--color-ink)]">
                  From the field
                </h3>
              </div>
              {newsAgo ? (
                <div className="shrink-0 text-[12px] font-medium text-[var(--color-slate)]">
                  Updated {newsAgo}
                </div>
              ) : null}
            </div>

            <ul className="mt-6 divide-y divide-[var(--color-line)]">
              {topNews.length === 0 ? (
                <li className="py-6 text-[14px] text-[var(--color-slate)]">
                  No news available right now.
                </li>
              ) : (
                topNews.map((n) => (
                  <li key={n.id} className="py-5 first:pt-0 last:pb-0">
                    <a
                      href={n.link}
                      target="_blank"
                      rel="noopener noreferrer"
                      aria-label={`Read "${n.title}" at ${n.sourceName}`}
                      className="group block"
                    >
                      <div className="flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-wider">
                        <span className="rounded-full bg-[var(--color-mist)] px-2 py-0.5 text-[var(--color-blue)]">
                          {n.sourceName}
                        </span>
                        <span className="text-[var(--color-slate)]">
                          {formatDate(n.pubDate)}
                        </span>
                      </div>
                      <div className="mt-2 text-[15px] font-semibold leading-snug text-[var(--color-ink)] transition-colors group-hover:text-[var(--color-blue)]">
                        {n.title}
                      </div>
                    </a>
                  </li>
                ))
              )}
            </ul>

            <div className="mt-8">
              <Link
                href="/news"
                className="inline-flex items-center gap-1.5 text-[14px] font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
              >
                Browse all news
                <ArrowRight size={16} strokeWidth={1.75} aria-hidden />
              </Link>
            </div>
          </div>
        </div>
      </Container>
    </section>
  );
}
