"use client";

import Image from "next/image";
import { useCallback, useEffect, useState } from "react";

import { Reveal } from "@/components/Reveal";

function ChevronIcon({ direction, className }: { direction: "next" | "prev"; className?: string }) {
  const d = direction === "next" ? "M19 12H5m0 0 6-6m-6 6 6 6" : "M5 12h14m0 0-6-6m6 6-6 6";
  return (
    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" className={className}>
      <path d={d} stroke="currentColor" strokeWidth="1.6" />
    </svg>
  );
}

/**
 * The grid stays exactly as before; clicking a thumbnail opens it full-size
 * with prev/next controls — a lightbox/slideshow over the same image list.
 */
export function ProjectGalleryLightbox({ images, alt }: { images: string[]; alt: string }) {
  const [openIndex, setOpenIndex] = useState<number | null>(null);

  const close = useCallback(() => setOpenIndex(null), []);
  const showNext = useCallback(
    () => setOpenIndex((i) => (i === null ? null : (i + 1) % images.length)),
    [images.length],
  );
  const showPrev = useCallback(
    () => setOpenIndex((i) => (i === null ? null : (i - 1 + images.length) % images.length)),
    [images.length],
  );

  useEffect(() => {
    if (openIndex === null) return;

    document.body.style.overflow = "hidden";
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") close();
      if (e.key === "ArrowRight") showPrev(); // RTL: right arrow moves to the previous item
      if (e.key === "ArrowLeft") showNext();
    };
    window.addEventListener("keydown", onKey);

    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [openIndex, close, showNext, showPrev]);

  return (
    <>
      <ul className="grid gap-6 sm:grid-cols-2 lg:gap-8">
        {images.map((url, i) => (
          <Reveal as="li" key={url} delay={(i % 4) * 80}>
            <button
              type="button"
              onClick={() => setOpenIndex(i)}
              aria-label={`مشاهده بزرگ‌تر تصویر ${i + 1}`}
              className="group relative block aspect-[4/3] w-full overflow-hidden bg-ink"
            >
              <Image
                src={url}
                alt={`${alt} ${i + 1}`}
                fill
                quality={82}
                sizes="(max-width: 1024px) 100vw, 50vw"
                loading={i < 2 ? "eager" : "lazy"}
                className="object-cover transition-transform duration-[1100ms] ease-out-soft group-hover:scale-[1.04]"
              />
              <div className="absolute inset-0 flex items-center justify-center bg-ink/0 opacity-0 transition-all duration-300 group-hover:bg-ink/30 group-hover:opacity-100">
                <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" className="h-9 w-9 text-white">
                  <path
                    d="M9 3H4v5m11-5h5v5M9 21H4v-5m11 5h5v-5"
                    stroke="currentColor"
                    strokeWidth="1.6"
                    strokeLinecap="round"
                  />
                </svg>
              </div>
            </button>
          </Reveal>
        ))}
      </ul>

      {openIndex !== null && (
        <div
          role="dialog"
          aria-modal="true"
          aria-label="نمایش بزرگ‌شده‌ی تصویر"
          className="fixed inset-0 z-[100] flex items-center justify-center bg-black/95 p-4"
          onClick={close}
        >
          <button
            type="button"
            onClick={close}
            aria-label="بستن"
            className="absolute top-5 left-5 flex h-11 w-11 items-center justify-center rounded-full text-white/80 transition-colors hover:bg-white/10 hover:text-white"
          >
            <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" className="h-6 w-6">
              <path d="M6 6l12 12M18 6 6 18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
            </svg>
          </button>

          <span className="latin absolute top-6 right-6 text-sm text-white/60">
            {openIndex + 1} / {images.length}
          </span>

          {images.length > 1 && (
            <>
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  showPrev();
                }}
                aria-label="تصویر قبلی"
                className="absolute end-3 top-1/2 flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full text-white/80 transition-colors hover:bg-white/10 hover:text-white sm:end-6"
              >
                <ChevronIcon direction="prev" className="h-6 w-6" />
              </button>
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  showNext();
                }}
                aria-label="تصویر بعدی"
                className="absolute start-3 top-1/2 flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full text-white/80 transition-colors hover:bg-white/10 hover:text-white sm:start-6"
              >
                <ChevronIcon direction="next" className="h-6 w-6" />
              </button>
            </>
          )}

          <div
            className="relative h-full max-h-[80vh] w-full max-w-5xl"
            onClick={(e) => e.stopPropagation()}
          >
            <Image
              src={images[openIndex]}
              alt={`${alt} ${openIndex + 1}`}
              fill
              priority
              quality={90}
              sizes="(max-width: 1024px) 100vw, 1024px"
              className="object-contain"
            />
          </div>
        </div>
      )}
    </>
  );
}
