import Image from "next/image";
import Link from "next/link";

import { urlFor } from "@/sanity/image";
import type { StudyListItem } from "@/sanity/queries";

/**
 * Research study card. Similar layout to PostCard but surfaces
 * institutions and a multi-author byline since studies almost always
 * involve several authors across institutions.
 */
export function StudyCard({ study }: { study: StudyListItem }) {
  const coverUrl = study.coverImage
    ? urlFor(study.coverImage).width(800).height(800).fit("crop").url()
    : "";
  const date = study.publishedAt
    ? new Date(study.publishedAt).toLocaleDateString("en-GB", {
        year: "numeric",
        month: "short",
        day: "numeric",
      })
    : "";
  const authorLine = (study.authors ?? []).map((a) => a.name).join(", ");
  const institutionLine = (study.institutions ?? []).join(" · ");

  return (
    <Link
      href={`/studies/${study.slug}`}
      className="group flex flex-col rounded-lg border border-[var(--color-line)] bg-white transition-all hover:border-[var(--color-blue)] hover:shadow-md"
    >
      <div className="relative aspect-square w-full overflow-hidden rounded-t-lg bg-[var(--color-mist)]">
        {coverUrl ? (
          <Image
            src={coverUrl}
            alt=""
            fill
            sizes="(max-width: 768px) 100vw, 33vw"
            className="object-cover transition-transform group-hover:scale-[1.02]"
          />
        ) : null}
      </div>
      <div className="flex flex-1 flex-col p-5">
        {date && (
          <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
            {date}
          </div>
        )}
        <h3 className="mt-2 font-display text-[19px] font-bold leading-tight tracking-tight text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
          {study.title}
        </h3>
        {study.summary && (
          <p className="mt-2 line-clamp-3 text-[14px] leading-relaxed text-[var(--color-slate)]">
            {study.summary}
          </p>
        )}
        {authorLine && (
          <div className="mt-4 text-[12px] text-[var(--color-slate)]">{authorLine}</div>
        )}
        {institutionLine && (
          <div className="mt-1 text-[12px] text-[var(--color-slate)]/80">{institutionLine}</div>
        )}
      </div>
    </Link>
  );
}
