"use client";

import Image from "next/image";
import { useEffect, useState } from "react";
import type { DocumentItem } from "@/data/documents";

export function DocumentsGallery({ items }: { items: DocumentItem[] }) {
  const [active, setActive] = useState<DocumentItem | null>(null);

  useEffect(() => {
    if (!active) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setActive(null);
    };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [active]);

  return (
    <>
      <div className="grid gap-6 sm:grid-cols-2">
        {items.map((item) => (
          <button
            key={item.id}
            type="button"
            onClick={() => setActive(item)}
            className="group overflow-hidden bg-white text-center shadow-[0_0_10px_rgba(0,0,0,0.05)] transition hover:shadow-[0_8px_24px_rgba(0,0,0,0.08)]"
          >
            <div className="relative aspect-[3/4] w-full bg-[#fafafa]">
              <Image
                src={item.image}
                alt={item.title}
                fill
                className="object-contain p-3 transition duration-300 group-hover:scale-[1.02]"
                sizes="(max-width: 640px) 100vw, 50vw"
              />
            </div>
            <p className="border-t border-[#eee] px-3 py-3 text-sm font-medium text-[#333]">
              {item.title}
            </p>
          </button>
        ))}
      </div>

      {active ? (
        <div
          className="fixed inset-0 z-[100] flex items-center justify-center bg-black/70 p-4"
          role="dialog"
          aria-modal="true"
          aria-label={active.title}
          onClick={() => setActive(null)}
        >
          <button
            type="button"
            className="absolute top-4 left-4 rounded bg-white/90 px-3 py-1.5 text-sm text-[#232323]"
            onClick={() => setActive(null)}
          >
            بستن
          </button>
          <div
            className="relative max-h-[90vh] w-full max-w-3xl"
            onClick={(e) => e.stopPropagation()}
          >
            <Image
              src={active.image}
              alt={active.title}
              width={900}
              height={1200}
              className="mx-auto h-auto max-h-[90vh] w-auto object-contain"
              sizes="90vw"
              priority
            />
            <p className="mt-3 text-center text-sm text-white">{active.title}</p>
          </div>
        </div>
      ) : null}
    </>
  );
}
