"use client";

import Image from "next/image";
import { useTranslation } from "react-i18next";
import { ExternalLink } from "lucide-react";
import { useLanguageStore } from "@/store/languageStore";
import { type CertificateItem } from "./commonProfileTypes";

/** The certificates a volunteer has earned. */
export default function CertificatesGrid({ certificates }: { certificates: CertificateItem[] }) {
  const { t } = useTranslation();
  const language = useLanguageStore((state) => state.language);

  if (!certificates.length) {
    return (
      <p className="py-8 text-center text-lg text-secondary-102">
        {t("COMMON.NO_CERTIFICATES_AVAILABLE")}
      </p>
    );
  }

  return (
    <div className="listing-card-grid grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3">
      {/* Fixed box + object-contain: every tile is the same height whatever
          the certificate's aspect ratio, without cropping. */}
      {certificates.map((certificate) => {
        const title =
          certificate[
            language === "ar" ? "opportunity__title_ar" : "opportunity__title_en"
          ] || t("COMMON.CERTIFICATE-");
        return (
          <a
            key={certificate.registration_id}
            href={certificate.certificate_image}
            target="_blank"
            rel="noopener noreferrer"
            className="group relative flex h-[260px] items-center justify-center overflow-hidden rounded-lg bg-[#29246D]/[0.03] shadow-md"
          >
            {/\.html?(?:$|[?#])/i.test(certificate.certificate_image) ? (
              <iframe
                src={certificate.certificate_image}
                title={title}
                tabIndex={-1}
                className="pointer-events-none h-full w-full border-0 bg-white transition-transform group-hover:scale-[1.02]"
              />
            ) : (
              <Image
                src={certificate.certificate_image}
                alt={title}
                width={600}
                height={420}
                className="h-full w-full object-contain transition-transform group-hover:scale-[1.02]"
                unoptimized
              />
            )}
            <span className="absolute end-3 top-3 rounded-full bg-white p-2 text-primary-5 shadow">
              <ExternalLink className="h-4 w-4" />
            </span>
          </a>
        );
      })}
    </div>
  );
}
