"use client";

import { useEffect, useRef, useState } from "react";

// Minimal lightbox for gallery photo viewing. Click thumbnail to open,
// arrow keys to navigate, ESC to close, click backdrop to close, and
// (D.3) swipe left/right on touch devices to cycle photos.
export function PhotoLightbox({
  photos,
  alt,
}: {
  photos: { id: number; src: string }[];
  alt: string;
}) {
  const [index, setIndex] = useState<number | null>(null);
  const touchStartX = useRef<number | null>(null);

  useEffect(() => {
    if (index === null) return;
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") setIndex(null);
      else if (e.key === "ArrowLeft") setIndex((i) => (i === null ? null : Math.max(0, i - 1)));
      else if (e.key === "ArrowRight") setIndex((i) => (i === null ? null : Math.min(photos.length - 1, i + 1)));
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [index, photos.length]);

  function handleTouchStart(e: React.TouchEvent) {
    touchStartX.current = e.touches[0]?.clientX ?? null;
  }
  function handleTouchEnd(e: React.TouchEvent) {
    const start = touchStartX.current;
    touchStartX.current = null;
    if (start === null) return;
    const end = e.changedTouches[0]?.clientX ?? start;
    const dx = end - start;
    // 50 px swipe threshold — anything shorter is treated as a tap.
    if (Math.abs(dx) < 50) return;
    if (dx > 0) {
      setIndex((i) => (i === null ? null : Math.max(0, i - 1)));
    } else {
      setIndex((i) => (i === null ? null : Math.min(photos.length - 1, i + 1)));
    }
  }

  return (
    <>
      <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
        {photos.map((photo, i) => (
          <button
            key={photo.id}
            type="button"
            onClick={() => setIndex(i)}
            className="rounded-lg overflow-hidden bg-surface text-left"
            aria-label={`Open photo ${i + 1} of ${photos.length}`}
          >
            <img
              src={photo.src}
              alt={alt}
              className="w-full h-64 object-cover hover:opacity-90 transition-opacity cursor-zoom-in"
            />
          </button>
        ))}
      </div>

      {index !== null && (
        <div
          className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center"
          onClick={() => setIndex(null)}
          onTouchStart={handleTouchStart}
          onTouchEnd={handleTouchEnd}
        >
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); setIndex(null); }}
            className="absolute top-4 right-4 text-white text-2xl"
            aria-label="Close lightbox"
          >
            ✕
          </button>
          {index > 0 && (
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); setIndex(index - 1); }}
              className="absolute left-4 top-1/2 -translate-y-1/2 text-white text-3xl px-3 py-1 bg-black/40 rounded-full"
              aria-label="Previous photo"
            >
              ‹
            </button>
          )}
          {index < photos.length - 1 && (
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); setIndex(index + 1); }}
              className="absolute right-4 top-1/2 -translate-y-1/2 text-white text-3xl px-3 py-1 bg-black/40 rounded-full"
              aria-label="Next photo"
            >
              ›
            </button>
          )}
          <img
            src={photos[index].src}
            alt={alt}
            className="max-h-[90vh] max-w-[90vw] object-contain"
            onClick={(e) => e.stopPropagation()}
          />
          <div className="absolute bottom-4 left-1/2 -translate-x-1/2 text-white/70 text-sm">
            {index + 1} / {photos.length}
          </div>
        </div>
      )}
    </>
  );
}
