import Image from "next/image";
import Link from "next/link";
import type { GalleryItem } from "@/lib/gallery";

function cellClass(span?: GalleryItem["span"]) {
  if (span === "wide") return "md:col-span-2";
  if (span === "tall") return "md:row-span-2";
  return "";
}

function aspectClass(span?: GalleryItem["span"]) {
  if (span === "tall") return "aspect-[3/4] md:aspect-auto md:min-h-full md:h-full";
  if (span === "wide") return "aspect-[16/10] md:aspect-[21/9]";
  return "aspect-[4/3]";
}

export function GalleryGrid({
  images,
  showLabels = true,
}: {
  images?: GalleryItem[];
  showLabels?: boolean;
}) {
  if (!images || images.length === 0) {
    return (
      <div className="flex items-center justify-center border border-[var(--color-border)] py-20 text-[var(--color-text-muted)]">
        <p className="text-sm uppercase tracking-[2px]">Gallery coming soon</p>
      </div>
    );
  }

  return (
    <div className="grid auto-rows-fr grid-cols-1 gap-3 md:grid-cols-2 md:gap-4 lg:grid-cols-3">
      {images.map((img, i) => {
        const inner = (
          <>
            <Image
              src={img.url}
              alt={img.alt || `Gallery image ${i + 1}`}
              fill
              sizes={
                img.span === "wide"
                  ? "(max-width: 768px) 100vw, 66vw"
                  : "(max-width: 768px) 100vw, 33vw"
              }
              className="object-cover transition-transform duration-700 ease-out group-hover:scale-105"
            />
            <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/60 via-black/5 to-transparent opacity-80 transition-opacity duration-300 group-hover:opacity-100" />
            {showLabels && img.label && (
              <div className="absolute inset-x-0 bottom-0 p-4 md:p-5">
                <span className="text-xs font-medium uppercase tracking-[2px] text-white/90">
                  {img.label}
                </span>
              </div>
            )}
          </>
        );

        const classes = `group relative block overflow-hidden bg-[var(--color-surface)] ${aspectClass(img.span)} ${cellClass(img.span)}`;

        if (img.href) {
          return (
            <Link
              key={`${img.url}-${i}`}
              href={img.href}
              className={`${classes} focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-heading)]`}
            >
              {inner}
            </Link>
          );
        }

        return (
          <div key={`${img.url}-${i}`} className={classes}>
            {inner}
          </div>
        );
      })}
    </div>
  );
}
