"use client";

import * as React from "react";
import Image from "next/image";
import { Trophy } from "lucide-react";
import { useTranslations } from "next-intl";
import { FadeIn } from "@/components/magicui/fade-in";
import { Lightbox } from "@/components/ui/lightbox";

type Award = {
  id: string;
  name: string;
  year: string;
  image: string;
};

/* ── Award Card ──────────────────────────────────────── */
function AwardCard({
  award,
  globalIndex,
  onClick,
}: {
  award: Award;
  globalIndex: number;
  onClick: (index: number) => void;
}) {
  return (
    <FadeIn delay={(globalIndex % 6) * 50}>
      <button
        onClick={() => onClick(globalIndex)}
        className="group relative w-full overflow-hidden rounded-2xl border border-black/5 bg-white text-left shadow-sm transition-all duration-300 hover:-translate-y-1 hover:border-gold/20 hover:shadow-lg"
        aria-label={`View: ${award.name}`}
      >
        {/* Year badge */}
        {award.year !== "—" && (
          <div className="absolute right-3 top-3 z-10">
            <span className="rounded-full bg-gold/90 px-2.5 py-0.5 text-[9px] font-bold tracking-widest text-white shadow-sm">
              {award.year}
            </span>
          </div>
        )}

        {/* Image */}
        <div className="relative aspect-[3/4] overflow-hidden bg-gold-bg">
          <Image
            src={award.image}
            alt={award.name}
            fill
            className="object-contain p-3 transition-transform duration-500 group-hover:scale-105"
            sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
          />
          {/* Zoom overlay */}
          <div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-all duration-300 group-hover:bg-black/12">
            <div className="flex h-10 w-10 scale-75 items-center justify-center rounded-full bg-white/0 opacity-0 shadow-lg transition-all duration-300 group-hover:scale-100 group-hover:bg-white/95 group-hover:opacity-100">
              <Trophy className="h-4 w-4 text-gold" />
            </div>
          </div>
        </div>

        {/* Label */}
        <div className="px-3 py-3">
          <p className="line-clamp-2 text-[11px] font-semibold leading-snug text-ink">
            {award.name}
          </p>
        </div>
      </button>
    </FadeIn>
  );
}

/* ── RecognitionGallery (client island) ──────────────── */
export function RecognitionGallery({
  awards,
  locale,
}: {
  awards: Award[];
  locale: string;
}) {
  const t = useTranslations("recognitionPage");

  const [lightboxIndex, setLightboxIndex] = React.useState<number | null>(null);

  const openLightbox = React.useCallback(
    (index: number) => setLightboxIndex(index),
    []
  );
  const closeLightbox = React.useCallback(
    () => setLightboxIndex(null),
    []
  );
  const prevLightbox = React.useCallback(
    () =>
      setLightboxIndex((i) => (i !== null && i > 0 ? i - 1 : i)),
    []
  );
  const nextLightbox = React.useCallback(
    () =>
      setLightboxIndex((i) =>
        i !== null && i < awards.length - 1 ? i + 1 : i
      ),
    [awards.length]
  );

  const years = React.useMemo(() => {
    return Array.from(new Set(awards.map((a) => a.year)))
      .filter((y) => y !== "—")
      .sort((a, b) => Number(a) - Number(b));
  }, [awards]);

  const ungrouped = React.useMemo(() => {
    return awards.filter((a) => a.year === "—");
  }, [awards]);

  return (
    <>
      {/* Lightbox */}
      {lightboxIndex !== null && (
        <Lightbox
          src={awards[lightboxIndex].image}
          alt={awards[lightboxIndex].name}
          year={awards[lightboxIndex].year}
          onClose={closeLightbox}
          onPrev={prevLightbox}
          onNext={nextLightbox}
          hasPrev={lightboxIndex > 0}
          hasNext={lightboxIndex < awards.length - 1}
        />
      )}

      {/* ── AWARD GALLERY — grouped by year ──────────────── */}
      <section className="bg-white py-14 sm:py-20">
        <div className="mx-auto max-w-[1400px] px-4 sm:px-6 lg:px-8">
          {years.map((year) => {
            const yearAwards = awards.filter((a) => a.year === year);
            const awardCountText =
              locale === "id"
                ? `· ${yearAwards.length} Penghargaan`
                : locale === "zh"
                  ? `· ${yearAwards.length} 项荣誉`
                  : `· ${yearAwards.length} award${yearAwards.length > 1 ? "s" : ""}`;

            return (
              <div key={year} className="mb-16 last:mb-0">
                {/* Year divider */}
                <FadeIn>
                  <div className="mb-8 flex items-center gap-4">
                    <div className="h-px flex-1 bg-black/6" />
                    <div className="flex items-center gap-2 rounded-full border border-gold/20 bg-gold-bg px-5 py-2">
                      <Trophy className="h-3.5 w-3.5 text-gold" />
                      <span className="font-serif text-xl font-bold text-gold">
                        {year}
                      </span>
                      <span className="text-[10px] font-bold text-muted">
                        {awardCountText}
                      </span>
                    </div>
                    <div className="h-px flex-1 bg-black/6" />
                  </div>
                </FadeIn>

                {/* Cards */}
                <div className="grid grid-cols-2 gap-5 sm:grid-cols-3 lg:grid-cols-4">
                  {yearAwards.map((award) => {
                    const globalIndex = awards.findIndex(
                      (a) => a.id === award.id
                    );
                    return (
                      <AwardCard
                        key={award.id}
                        award={award}
                        globalIndex={globalIndex}
                        onClick={openLightbox}
                      />
                    );
                  })}
                </div>
              </div>
            );
          })}

          {/* Ungrouped */}
          {ungrouped.length > 0 && (
            <div className="mb-0">
              <FadeIn>
                <div className="mb-8 flex items-center gap-4">
                  <div className="h-px flex-1 bg-black/6" />
                  <span className="rounded-full border border-gold/20 bg-gold-bg px-5 py-2 text-[11px] font-bold uppercase tracking-widest text-muted">
                    {t("other")}
                  </span>
                  <div className="h-px flex-1 bg-black/6" />
                </div>
              </FadeIn>
              <div className="grid grid-cols-2 gap-5 sm:grid-cols-3 lg:grid-cols-4">
                {ungrouped.map((award) => {
                  const globalIndex = awards.findIndex(
                    (a) => a.id === award.id
                  );
                  return (
                    <AwardCard
                      key={award.id}
                      award={award}
                      globalIndex={globalIndex}
                      onClick={openLightbox}
                    />
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </section>
    </>
  );
}
