"use client"

import { useEffect, useState } from "react"
import { motion } from "framer-motion"
import { useTranslations } from "next-intl"
import { useLoading } from "@/components/loading-context"

// show: breakpoint minimum pour afficher le lien
// xs(<640): 1 lien · sm(640): 2 · md(768): 3 · lg(1024): 4+

const DEFAULT_IMAGES = [
  "/media/hero/DJI_0592.jpg",
  "/media/hero/DSC04848.jpg",
  "/media/hero/DJI_0642.jpg",
  "/media/hero/DJI_0654.jpg",
  "/media/hero/DJI_0594.jpg",
  "/media/hero/DJI_0555.jpg",
  "/media/hero/DJI_0601.jpg",
  "/media/hero/DJI_0613.jpg",
  "/media/hero/DJI_0628.jpg",
  "/media/hero/DJI_0664.jpg",
  "/media/hero/DJI_0681.jpg",
  "/media/hero/DJI_0687.jpg",
  "/media/hero/DJI_0705.jpg",
  "/media/hero/DJI_0589.jpg",
]

interface ParticleConfig {
  width: number
  height: number
  initialX: number
  initialY: number
  animateY: number
  animateX: number
  scale: number
  duration: number
  background: string
}

export default function Hero(_props: { latestNews: { title: string }[]; loadingNews: boolean }) {
  const t = useTranslations("hero")
  const { isLoaded } = useLoading()
  const [particles, setParticles] = useState<ParticleConfig[]>([])
  const [currentImageIndex, setCurrentImageIndex] = useState(0)
  const [, setIsTransitioning] = useState(false)
  // Hero alimenté uniquement par la banque d'images (15 vues drone du site SAR)
  const [backgroundImages] = useState<string[]>(DEFAULT_IMAGES)

  // Carousel automatique avec transition tranche par tranche
  useEffect(() => {
    const total = backgroundImages.length
    const interval = setInterval(() => {
      setIsTransitioning(true)
      setTimeout(() => {
        setCurrentImageIndex((prev) => (prev + 1) % total)
        setIsTransitioning(false)
      }, 100)
    }, 7000) // Change d'image toutes les 7 secondes

    return () => clearInterval(interval)
  }, [backgroundImages.length])

  useEffect(() => {
    // Générer les valeurs aléatoires uniquement côté client
    const width = typeof window !== "undefined" ? window.innerWidth : 1000
    const height = typeof window !== "undefined" ? window.innerHeight : 1000

    const newParticles: ParticleConfig[] = Array.from({ length: 30 }, (_, i) => ({
      width: Math.random() * 4 + 2,
      height: Math.random() * 4 + 2,
      initialX: Math.random() * width,
      initialY: Math.random() * height,
      animateY: Math.random() * height,
      animateX: Math.random() * width,
      scale: Math.random() + 0.5,
      duration: Math.random() * 10 + 10,
      background: i % 3 === 0 ? "rgba(229, 38, 33, 0.3)" : "rgba(255, 255, 255, 0.2)",
    }))

    setParticles(newParticles)
  }, [])

  return (
    <section className={`relative min-h-[65vh] sm:min-h-[50vh] md:min-h-[55vh] lg:min-h-[calc(60vh+80px)] flex items-center justify-start overflow-hidden bg-white`}>
      {/* Background carousel avec transition tranche par tranche */}
      {isLoaded && (
      <div className="absolute inset-0 z-0">
        {/* Image précédente qui reste visible jusqu'à ce que les tranches la remplacent */}
        {backgroundImages.map((image, index) => {
          const prevIndex = currentImageIndex === 0 
            ? backgroundImages.length - 1 
            : currentImageIndex - 1
          if (index !== prevIndex) return null
          
          return (
            <div
              key={`prev-${image}-${prevIndex}`}
              className="absolute inset-0"
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={image}
                alt="Raffinerie SAR"
                loading="eager"
                style={{
                  position: 'absolute',
                  inset: 0,
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                  objectPosition: 'center 50%',
                }}
              />
            </div>
          )
        })}
        
        {/* Nouvelle image qui se révèle tranche par tranche (puzzle progressif) */}
        {backgroundImages.map((image, index) => {
          if (index !== currentImageIndex) return null
          
          // Créer 5 bandes verticales collées pour former le puzzle de l'image
          const numberOfStrips = 5
          
          return (
            <div
              key={`${image}-${currentImageIndex}`}
              className="absolute inset-0"
            >
              {/* Tranches de l'image qui se révèlent progressivement de gauche à droite */}
              <div className="absolute inset-0">
                {Array.from({ length: numberOfStrips }).map((_, stripIndex) => {
                  // Chaque tranche fait exactement 20% de la largeur (100% / 5) + 1px
                  const stripWidthPercent = 100 / numberOfStrips // 20%
                  const stripLeftPercent = stripIndex * stripWidthPercent // 0%, 20%, 40%, 60%, 80%
                  // Délai progressif : la première tranche (gauche) commence en premier, puis les suivantes
                  const delay = stripIndex * 0.15 // Ralenti pour une transition plus douce
                  
                  return (
                    <motion.div
                      key={stripIndex}
                      className="absolute top-0 bottom-0 overflow-hidden"
                      style={{
                        left: `${stripLeftPercent}%`,
                        width: `calc(${stripWidthPercent}% + 1px)`,
                      }}
                      initial={{
                        clipPath: "polygon(0 0, 0 0, 0 100%, 0 100%)", // Caché à gauche
                      }}
                      animate={{
                        clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)", // Révélé complètement
                      }}
                      transition={{
                        duration: 0.8, // Durée plus longue pour ralentir
                        delay: delay, // Délai progressif de gauche à droite
                        ease: [0.25, 0.46, 0.45, 0.94],
                      }}
                    >
                      <div
                        className="absolute inset-0"
                        style={{
                          width: `${100 * numberOfStrips}%`, // Largeur totale = 500% pour 5 tranches
                          left: `-${stripLeftPercent * numberOfStrips}%`, // Décaler pour afficher la bonne portion
                        }}
                      >
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={image}
                          alt={`Raffinerie SAR - Image ${index + 1}`}
                          loading="eager"
                          style={{
                            position: 'absolute',
                            inset: 0,
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover',
                            objectPosition: 'center 50%',
                          }}
                        />
                      </div>
                    </motion.div>
                  )
                })}
              </div>
            </div>
          )
        })}
        
        {/* Overlay for text readability - très léger */}
        <div className="absolute inset-0 bg-gradient-to-br from-primary/20 via-primary/10 to-primary/20" />
      </div>
      )}

      {/* Card certificat supprimée à la demande */}

      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        {particles.map((particle, i) => (
          <motion.div
            key={i}
            className="absolute rounded-full"
            style={{
              width: particle.width,
              height: particle.height,
              background: particle.background,
            }}
            initial={{
              x: particle.initialX,
              y: particle.initialY,
            }}
            animate={{
              y: [null, particle.animateY],
              x: [null, particle.animateX],
              scale: [1, particle.scale, 1],
              opacity: [0.3, 0.8, 0.3],
            }}
            transition={{
              duration: particle.duration,
              repeat: Number.POSITIVE_INFINITY,
              repeatType: "reverse",
              ease: "easeInOut",
            }}
          />
        ))}
      </div>

      {/* ── Signature : la baseline de la SAR ──────────────────────────────
          Un dégradé plutôt qu'un aplat : le bas de l'image reste lisible et
          le texte garde son contraste quelle que soit la photo affichée. */}
      {isLoaded && (
        <motion.div
          className="absolute bottom-0 left-0 right-0 z-10 pointer-events-none"
          initial={{ opacity: 0, y: 14 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, delay: 0.45, ease: [0.22, 1, 0.36, 1] }}
        >
          <div className="bg-gradient-to-t from-white via-white/85 to-transparent pt-12 pb-4 sm:pb-5">
            <div className="flex flex-col items-center px-5">
              {/* Le filet rouge se déploie : il signe la marque avant le texte */}
              <motion.span
                className="block h-0.5 w-10 bg-primary"
                initial={{ scaleX: 0 }}
                animate={{ scaleX: 1 }}
                transition={{ duration: 0.7, delay: 0.75, ease: [0.22, 1, 0.36, 1] }}
                aria-hidden
              />
              <p className="mt-3 text-balance text-center text-[10px] font-semibold uppercase leading-relaxed tracking-[0.2em] text-white sm:text-xs sm:tracking-[0.28em] md:text-[13px] md:tracking-[0.32em]">
                {/* Une seule chaine traduite : la coupure etait fixee par deux
                    fragments francais, que l'anglais n'aurait pas suivis.
                    text-balance repartit les lignes de lui-meme. */}
                <span className="text-primary">{t("baseline")}</span>
              </p>
            </div>
          </div>
        </motion.div>
      )}

    </section>
  )
}
