"use client";

import * as React from "react";
import Image from "next/image";
import { useLocale, useTranslations } from "next-intl";
import { X, ZoomIn } from "lucide-react";
import { FadeIn } from "@/components/magicui/fade-in";
import { GALLERY_IMAGES } from "@/data/site-data";

const galleryAltsMap: Record<string, Record<string, string>> = {
  id: {
    "Preparing Raw Materials": "Persiapan Bahan Baku",
    "Distribution & Traceability": "Distribusi & Ketertelusuran",
    "Processing Stage": "Tahap Pemrosesan",
    "Hand Cleaning": "Pembersihan Manual",
    "Drying Process": "Proses Pengeringan",
    "Moulding": "Pencetakan",
    "Quality Control": "Kontrol Kualitas",
    "Traceability System": "Sistem Ketertelusuran",
    "Packing": "Pengemasan",
    "Our Team": "Tim Kami",
  },
  zh: {
    "Preparing Raw Materials": "原料准备工作",
    "Distribution & Traceability": "条码追溯分发",
    "Processing Stage": "精细加工阶段",
    "Hand Cleaning": "纯手工清洗",
    "Drying Process": "控制环境烘干",
    "Moulding": "盏形重塑定型",
    "Quality Control": "严格质量控制",
    "Traceability System": "专有追溯系统",
    "Packing": "安全出口包装",
    "Our Team": "我们的团队",
  },
};

/* ── Lightbox ────────────────────────────────────────── */
function Lightbox({
  src,
  alt,
  onClose,
  onPrev,
  onNext,
  hasPrev,
  hasNext,
}: {
  src: string;
  alt: string;
  onClose: () => void;
  onPrev: () => void;
  onNext: () => void;
  hasPrev: boolean;
  hasNext: boolean;
}) {
  React.useEffect(() => {
    const h = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") onPrev();
      if (e.key === "ArrowRight") onNext();
    };
    document.addEventListener("keydown", h);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", h); document.body.style.overflow = ""; };
  }, [onClose, onPrev, onNext]);

  return (
    <div className="fixed inset-0 z-[999] flex items-center justify-center bg-black/85 p-4 backdrop-blur-sm" onClick={onClose}>
      <button onClick={onClose} className="absolute right-4 top-4 flex h-10 w-10 items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/25">
        <X className="h-5 w-5" />
      </button>
      {hasPrev && (
        <button onClick={(e) => { e.stopPropagation(); onPrev(); }} className="absolute left-4 top-1/2 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-xl text-white hover:bg-white/25">‹</button>
      )}
      {hasNext && (
        <button onClick={(e) => { e.stopPropagation(); onNext(); }} className="absolute right-4 top-1/2 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-xl text-white hover:bg-white/25">›</button>
      )}
      <div className="relative max-h-[88vh] w-full max-w-3xl overflow-hidden rounded-2xl bg-white shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <div className="relative aspect-video w-full">
          <Image src={src} alt={alt} fill className="object-contain p-3" sizes="(max-width: 768px) 100vw, 900px" priority />
        </div>
        <div className="border-t border-black/5 bg-gold-bg px-5 py-3 text-center">
          <p className="text-xs font-bold text-ink">{alt}</p>
        </div>
      </div>
    </div>
  );
}

function Gallery() {
  const [lightboxIndex, setLightboxIndex] = React.useState<number | null>(null);
  const locale = useLocale();
  const t = useTranslations("gallery");

  const getLocalizedAlt = (alt: string) => {
    return galleryAltsMap[locale]?.[alt] ?? alt;
  };

  const photoCountText = locale === "id" ? `${GALLERY_IMAGES.length} foto` : locale === "zh" ? `${GALLERY_IMAGES.length} 张照片` : `${GALLERY_IMAGES.length} photos`;

  return (
    <section id="gallery" className="bg-gold-bg py-20 sm:py-28">
      {lightboxIndex !== null && (
        <Lightbox
          src={GALLERY_IMAGES[lightboxIndex].src}
          alt={getLocalizedAlt(GALLERY_IMAGES[lightboxIndex].alt)}
          onClose={() => setLightboxIndex(null)}
          onPrev={() => setLightboxIndex((i) => (i !== null && i > 0 ? i - 1 : i))}
          onNext={() => setLightboxIndex((i) => (i !== null && i < GALLERY_IMAGES.length - 1 ? i + 1 : i))}
          hasPrev={lightboxIndex > 0}
          hasNext={lightboxIndex < GALLERY_IMAGES.length - 1}
        />
      )}

      <div className="mx-auto max-w-[1400px] px-4 sm:px-6 lg:px-8">
        <FadeIn>
          <div className="mb-14">
            <p className="mb-2 text-xs font-bold uppercase tracking-[0.25em] text-gold">
              {t("label")}
            </p>
            <h2 className="font-serif text-3xl font-bold text-ink sm:text-4xl">
              {t("title")}
            </h2>
          </div>
        </FadeIn>

        {/* Featured large + grid layout */}
        <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">

          {/* Featured left — tall */}
          <FadeIn direction="left" className="lg:row-span-2">
            <button
              onClick={() => setLightboxIndex(0)}
              className="group relative h-64 w-full overflow-hidden rounded-2xl shadow-md lg:h-full"
            >
              <Image
                src={GALLERY_IMAGES[0].src}
                alt={getLocalizedAlt(GALLERY_IMAGES[0].alt)}
                fill
                className="object-cover transition-transform duration-700 group-hover:scale-105"
                sizes="(max-width: 1024px) 100vw, 33vw"
              />
              <div className="absolute inset-0 bg-black/0 transition-all duration-300 group-hover:bg-black/15" />
              <div className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                <div className="flex h-11 w-11 items-center justify-center rounded-full bg-white/90 text-gold shadow">
                  <ZoomIn className="h-5 w-5" />
                </div>
              </div>
              <div className="absolute bottom-4 left-4 rounded-lg bg-white/90 px-3 py-1.5 backdrop-blur-sm">
                <p className="text-xs font-bold text-ink">{getLocalizedAlt(GALLERY_IMAGES[0].alt)}</p>
              </div>
            </button>
          </FadeIn>

          {/* Right grid — 2 columns × 2 rows */}
          <div className="col-span-1 grid grid-cols-2 gap-4 lg:col-span-2">
            {GALLERY_IMAGES.slice(1, 5).map((img, i) => (
              <FadeIn key={img.alt} delay={i * 60}>
                <button
                  onClick={() => setLightboxIndex(i + 1)}
                  className="group relative aspect-video w-full overflow-hidden rounded-2xl shadow-sm"
                >
                  <Image
                    src={img.src}
                    alt={getLocalizedAlt(img.alt)}
                    fill
                    className="object-cover transition-transform duration-500 group-hover:scale-105"
                    sizes="(max-width: 640px) 50vw, 25vw"
                  />
                  <div className="absolute inset-0 bg-black/0 transition-all duration-300 group-hover:bg-black/15" />
                  <div className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                    <div className="flex h-9 w-9 items-center justify-center rounded-full bg-white/90 text-gold shadow">
                      <ZoomIn className="h-4 w-4" />
                    </div>
                  </div>
                  <div className="absolute bottom-2 left-2 rounded-md bg-white/85 px-2 py-1 backdrop-blur-sm">
                    <p className="text-[10px] font-bold text-ink">{getLocalizedAlt(img.alt)}</p>
                  </div>
                </button>
              </FadeIn>
            ))}
          </div>

        </div>

        {/* Bottom strip — remaining images */}
        <div className="mt-4 grid grid-cols-3 gap-4 sm:grid-cols-6">
          {GALLERY_IMAGES.slice(5).map((img, i) => (
            <FadeIn key={img.alt} delay={i * 50}>
              <button
                onClick={() => setLightboxIndex(i + 5)}
                className="group relative aspect-square w-full overflow-hidden rounded-xl shadow-sm"
              >
                <Image
                  src={img.src}
                  alt={getLocalizedAlt(img.alt)}
                  fill
                  className="object-cover transition-transform duration-500 group-hover:scale-105"
                  sizes="(max-width: 640px) 33vw, 16vw"
                />
                <div className="absolute inset-0 bg-black/0 transition-all duration-300 group-hover:bg-black/20" />
                <div className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                  <ZoomIn className="h-4 w-4 text-white drop-shadow" />
                </div>
                <div className="absolute bottom-1.5 left-1.5 rounded bg-white/85 px-1.5 py-0.5 backdrop-blur-sm">
                  <p className="text-[8px] font-bold text-ink sm:text-[9px]">{getLocalizedAlt(img.alt)}</p>
                </div>
              </button>
            </FadeIn>
          ))}
        </div>

        <FadeIn>
          <p className="mt-6 text-center text-xs text-muted">
            {t("clickHint")} · {photoCountText}
          </p>
        </FadeIn>
      </div>
    </section>
  );
}

export { Gallery };
