"use client"

import { useState, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { useInView } from "react-intersection-observer"
import { useTranslations } from "next-intl"
import Image from "next/image"
import { X, ArrowLeft, ArrowRight, Download } from "lucide-react"
import SectionLabel from "@/components/section-label"

interface Certification {
  logo: string
  titleKey: string
  subtitleKey: string
  descriptionKey: string
  pdf: string
}

export default function CertificationsSection() {
  const t = useTranslations("certifications")
  const [ref, inView] = useInView({ triggerOnce: true, threshold: 0.1 })
  const [modalIndex, setModalIndex] = useState<number | null>(null)

  const certifications: Certification[] = [
    {
      logo: "/9001.png",
      titleKey: "iso9001.title",
      subtitleKey: "iso9001.subtitle",
      descriptionKey: "iso9001.description",
      pdf: "ISO-9001-C630407-0-fr-FR-20230727-20230802030053.pdf",
    },
    {
      logo: "/14001.png",
      titleKey: "iso14001.title",
      subtitleKey: "iso14001.subtitle",
      descriptionKey: "iso14001.description",
      pdf: "ISO-14001-C630405-0-fr-FR-20230802-20230802025608.pdf",
    },
    {
      logo: "/45001.png",
      titleKey: "iso45001.title",
      subtitleKey: "iso45001.subtitle",
      descriptionKey: "iso45001.description",
      pdf: "ISO-45001-C630406-0-fr-FR-20230802-20230802025835.pdf",
    },
    {
      logo: "/17025.png",
      titleKey: "iso17025.title",
      subtitleKey: "iso17025.subtitle",
      descriptionKey: "iso17025.description",
      pdf: "DIPLOME-DACCREDITATION-ISO-17025-LABO-JUIL-25.pdf",
    },
  ]

  const current = modalIndex !== null ? certifications[modalIndex] : null

  const prev = () => setModalIndex((i) => i !== null ? (i - 1 + certifications.length) % certifications.length : null)
  const next = () => setModalIndex((i) => i !== null ? (i + 1) % certifications.length : null)

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setModalIndex(null)
      if (e.key === "ArrowLeft" && modalIndex !== null) prev()
      if (e.key === "ArrowRight" && modalIndex !== null) next()
    }
    document.addEventListener("keydown", onKey)
    return () => document.removeEventListener("keydown", onKey)
  }, [modalIndex])

  useEffect(() => {
    const open = modalIndex !== null
    document.body.style.overflow = open ? "hidden" : ""
    document.body.classList.toggle("modal-open", open)
    return () => { document.body.style.overflow = ""; document.body.classList.remove("modal-open") }
  }, [modalIndex])

  return (
    <section id="certifications" ref={ref} className="pt-8 sm:pt-10 md:pt-12 pb-24 bg-slate-100">
      <div className="px-2 sm:px-4 lg:px-6">
        <div className="max-w-[98%] mx-auto">
          <SectionLabel title={t("title")} size="small" variant="overline" />
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-6 sm:gap-8">
          {certifications.map((cert, index) => (
            <motion.button
              key={index}
              type="button"
              onClick={() => setModalIndex(index)}
              initial={{ opacity: 0, y: 30 }}
              animate={inView ? { opacity: 1, y: 0 } : {}}
              transition={{ duration: 0.6, delay: index * 0.1 }}
              className="group w-full text-left border-2 border-gray-200 transition-all duration-300 hover:shadow-xl hover:-translate-y-1 hover:scale-[1.02] bg-white shadow-sm cursor-pointer"
            >
              <div className="p-6 text-center flex flex-col items-center">
                <div className="rounded-full border-4 border-gray-300 p-4 mb-4">
                  <Image
                    src={cert.logo}
                    alt={t(cert.titleKey)}
                    width={80}
                    height={80}
                    className="object-contain w-16 h-16 sm:w-20 sm:h-20"
                  />
                </div>
                <h3 className="text-lg sm:text-xl md:text-2xl font-bold mb-1 text-gray-900">{t(cert.titleKey)}</h3>
                <p className="text-xs sm:text-sm font-semibold mb-3" style={{ color: "#d40924" }}>{t(cert.subtitleKey)}</p>
                <p className="text-xs sm:text-sm text-gray-700 leading-relaxed">{t(cert.descriptionKey)}</p>
              </div>
            </motion.button>
          ))}
        </div>
      </div>

      {/* ── Modal split-screen ── */}
      <AnimatePresence>
        {modalIndex !== null && current && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.25 }}
            className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-end lg:items-center justify-center lg:p-8"
            onClick={() => setModalIndex(null)}
          >
            <motion.div
              initial={{ opacity: 0, y: 40 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 40 }}
              transition={{ duration: 0.28, ease: "easeOut" }}
              className="relative w-full lg:max-w-5xl flex flex-col lg:flex-row overflow-hidden shadow-2xl h-[100dvh] lg:h-[min(90vh,720px)]"
              onClick={(e) => e.stopPropagation()}
            >

              {/* ── MOBILE : barre de tête ── */}
              <div className="lg:hidden flex items-center gap-3 bg-white border-b border-neutral-100 px-4 py-3 flex-shrink-0">
                <button
                  type="button"
                  onClick={() => setModalIndex(null)}
                  className="flex-shrink-0 w-8 h-8 flex items-center justify-center bg-neutral-100 hover:bg-neutral-200 transition-colors rounded-full"
                >
                  <X className="w-4 h-4 text-gray-700" />
                </button>
                <div className="flex-1 min-w-0">
                  <p className="text-[9px] font-semibold uppercase tracking-widest text-primary/60 leading-none mb-0.5">Certification</p>
                  <p className="text-xs font-bold text-gray-900 truncate">{t(current.titleKey)}</p>
                </div>
                <a
                  href={`/${current.pdf}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-2 bg-primary text-white text-[10px] font-semibold uppercase tracking-widest hover:bg-primary/90 transition-colors"
                >
                  <Download className="w-3 h-3" />
                  PDF
                </a>
              </div>

              {/* ── DESKTOP : bouton fermer absolu ── */}
              <button
                type="button"
                onClick={() => setModalIndex(null)}
                className="hidden lg:flex absolute top-3 right-3 z-20 w-8 h-8 items-center justify-center bg-black/60 hover:bg-black/90 text-white transition-colors rounded-full"
              >
                <X className="w-4 h-4" />
              </button>

              {/* ── DESKTOP : panneau gauche ── */}
              <div className="hidden lg:flex lg:w-80 flex-shrink-0 bg-white flex-col overflow-hidden">
                <div className="flex items-center justify-center px-8 pt-8 pb-6 flex-shrink-0">
                  <div className="rounded-full border-4 border-gray-200 p-5">
                    <Image
                      src={current.logo}
                      alt={t(current.titleKey)}
                      width={96}
                      height={96}
                      className="object-contain w-20 h-20"
                    />
                  </div>
                </div>
                <div className="flex flex-col flex-1 px-6 pb-6 min-h-0">
                  <p className="text-[9px] font-semibold uppercase tracking-widest text-primary mb-1">
                    Certification
                  </p>
                  <div className="h-0.5 w-8 bg-primary/70 mb-3" />
                  <h3 className="text-2xl font-bold text-gray-900 leading-none mb-1">
                    {t(current.titleKey)}
                  </h3>
                  <p className="text-xs font-semibold uppercase tracking-widest mb-4" style={{ color: "#d40924" }}>
                    {t(current.subtitleKey)}
                  </p>
                  <p className="text-xs text-neutral-600 leading-relaxed flex-1">
                    {t(current.descriptionKey)}
                  </p>
                  <a
                    href={`/${current.pdf}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-5 inline-flex items-center gap-2 px-4 py-2.5 bg-primary text-white text-[10px] font-semibold uppercase tracking-widest hover:bg-primary/90 transition-colors w-full justify-center"
                  >
                    <Download className="w-3 h-3" />
                    Télécharger le certificat
                  </a>
                  <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
                    <button
                      type="button"
                      onClick={prev}
                      className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-widest text-primary hover:text-primary/70 transition-colors"
                    >
                      <ArrowLeft className="w-3.5 h-3.5" />
                      Préc.
                    </button>
                    <span className="text-[10px] font-mono text-primary font-bold">
                      {modalIndex + 1} / {certifications.length}
                    </span>
                    <button
                      type="button"
                      onClick={next}
                      className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-widest text-primary hover:text-primary/70 transition-colors"
                    >
                      Suiv.
                      <ArrowRight className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
              </div>

              {/* ── PDF (mobile : flex-1, desktop : panneau droit) ── */}
              <div
                className="flex-1 min-h-0 bg-white overflow-y-auto [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-track]:bg-gray-100 [&::-webkit-scrollbar-thumb]:bg-primary [&::-webkit-scrollbar-thumb]:rounded-full"
                style={{ scrollbarColor: "#d40924 #f3f4f6", scrollbarWidth: "thin" }}
              >
                <iframe
                  key={current.pdf}
                  src={`/${current.pdf}#navpanes=0&toolbar=0`}
                  className="w-full border-0 block"
                  style={{ minHeight: "520px", height: "100%" }}
                  title={t(current.titleKey)}
                />
              </div>

              {/* ── MOBILE : barre de navigation prev/next ── */}
              <div className="lg:hidden flex items-center justify-between bg-white border-t border-neutral-200 px-5 py-3 flex-shrink-0">
                <button
                  type="button"
                  onClick={prev}
                  className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-widest text-primary hover:text-primary/70 transition-colors"
                >
                  <ArrowLeft className="w-4 h-4" />
                  Précédent
                </button>
                <span className="text-[11px] font-mono text-gray-400 font-bold">
                  {modalIndex + 1} / {certifications.length}
                </span>
                <button
                  type="button"
                  onClick={next}
                  className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-widest text-primary hover:text-primary/70 transition-colors"
                >
                  Suivant
                  <ArrowRight className="w-4 h-4" />
                </button>
              </div>

            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </section>
  )
}
