"use client"

import { useState, useEffect, useRef } from "react"
import { motion, AnimatePresence } from "framer-motion"
import Image from "next/image"
import { useLocale } from "next-intl"
import { ChevronLeft, ChevronRight, ExternalLink } from "lucide-react"

export type RseAction = {
  id: string
  category: "education" | "sante" | "environnement" | "communautaire"
  titleFr: string
  titleEn: string
  descFr: string
  descEn: string
  image: string
  /** Post LinkedIn associé. Si absent, dérivé du nom de l'image, sinon repli page SAR. */
  linkedInUrl?: string
}

// Page LinkedIn officielle de la SAR (repli quand aucun post précis n'est connu)
const SAR_LINKEDIN = "https://www.linkedin.com/company/societe-africaine-de-raffinage/posts/"

// Résout le lien LinkedIn d'un projet : override explicite → URN encodée dans l'image → repli SAR
export function resolveLinkedIn(a: RseAction): string {
  if (a.linkedInUrl) return a.linkedInUrl
  const m = a.image.match(/post_urn_li_share_(\d+)/)
  if (m) return `https://www.linkedin.com/feed/update/urn:li:share:${m[1]}`
  return SAR_LINKEDIN
}

// Tous les projets repris de la page RSE (vouée à disparaître).
export const RSE_ACTIONS: RseAction[] = [
  {
    id: "golf-nord",
    category: "education",
    titleFr: "Rénovation de l'école élémentaire de Golf Nord",
    titleEn: "Renovation of Golf Nord elementary school",
    descFr: "La SAR a contribué à la rénovation de l'école élémentaire de Golf Nord, en présence de Mme le Maire Khadija Mahecor Diouf de Golf Sud, de l'Association des résidents de la Cité SHS et de la communauté éducative. La SAR affirme sa conviction que l'éducation est un pilier fondamental pour construire un avenir durable et équitable.",
    descEn: "SAR contributed to the renovation of Golf Nord elementary school, attended by the Mayor of Golf Sud, the SHS City Residents' Association, and the educational community.",
    image: "/media/rse/32.png",
  },
  {
    id: "ecoles-primaires",
    category: "education",
    titleFr: "Réhabilitation de 3 écoles primaires",
    titleEn: "Rehabilitation of 3 primary schools",
    descFr: "Dans le cadre de sa politique RSE, la SAR a lancé la réhabilitation de trois écoles primaires : rénovation de salles de classe à l'école Baraque de Golf Nord (commune de Golf Sud), amélioration des infrastructures sanitaires aux écoles Mbaye Diouf et Moustapha Khaly Ndiaye (commune de Tivaouane Diacksao), et mise à niveau des espaces communs. Un programme concret pour offrir aux élèves et enseignants des conditions d'apprentissage dignes.",
    descEn: "As part of its CSR policy, SAR launched the rehabilitation of three primary schools: classroom renovation at Golf Nord school, sanitary infrastructure upgrades at Mbaye Diouf and Moustapha Khaly Ndiaye schools, and common area improvements.",
    image: "/media/as1.jpg",
  },
  {
    id: "banque-islamique",
    category: "education",
    titleFr: "Réhabilitation du lycée Banque islamique de Guédiawaye",
    titleEn: "Refurbishment of the Banque islamique secondary school in Guédiawaye",
    descFr: "Dans le cadre de son programme de réhabilitation des établissements scolaires, la Fondation SAR a mené une réhabilitation d'ensemble du lycée Banque islamique de Guédiawaye : 24 salles de classe réhabilitées et mobilier scolaire rénové, infirmerie rénovée et point d'eau installé avec un réservoir de 1 000 litres. Le Directeur général de la SAR en a réceptionné les travaux.",
    descEn: "As part of its school refurbishment programme, the SAR Foundation carried out a full refurbishment of the Banque islamique secondary school in Guédiawaye: 24 classrooms refurbished and school furniture renewed, the infirmary renovated and a water point installed with a 1,000-litre tank. SAR's Managing Director handed over the works.",
    image: "/media/rse/lycee-banque-islamique.jpg",
  },
  {
    id: "maternelle-doudou-ndoye",
    category: "education",
    titleFr: "Rénovation de la maternelle El Hadji Doudou Ndoye",
    titleEn: "Renovation of the El Hadji Doudou Ndoye nursery",
    descFr: "À l'école élémentaire El Hadji Doudou Ndoye, dans la commune de Yoff, la Fondation SAR est intervenue sur la section maternelle : 2 salles rénovées et repeintes, portes et fenêtres changées, et construction de toilettes.",
    descEn: "At the El Hadji Doudou Ndoye primary school, in the commune of Yoff, the SAR Foundation worked on the nursery section: 2 classrooms renovated and repainted, doors and windows replaced, and new toilets built.",
    image: "/media/rse/ecole-doudou-ndoye.jpg",
  },
  {
    id: "fondation-ndiandiar",
    category: "sante",
    titleFr: "Don de la Fondation SAR au poste de santé de Ndiandiar Makha",
    titleEn: "Fondation SAR donation to Ndiandiar Makha health post",
    descFr: "Le 24 décembre 2025, la Fondation SAR a effectué une remise de dons au poste de santé de Ndiandiar Makha. Cette initiative s'inscrit dans l'engagement de la SAR pour l'amélioration de l'accès aux soins, le renforcement des structures de santé et le bien-être durable des communautés.",
    descEn: "On December 24, 2025, the SAR Foundation donated supplies to the Ndiandiar Makha health post, reinforcing SAR's commitment to improving healthcare access and community well-being.",
    image: "/media/rse/11.png",
  },
]

const CATEGORY_LABELS: Record<string, { fr: string; en: string }> = {
  education:     { fr: "Éducation", en: "Education" },
  sante:         { fr: "Santé", en: "Health" },
  environnement: { fr: "Environnement", en: "Environment" },
  communautaire: { fr: "Communautaire", en: "Community" },
}

const CATEGORY_COLORS: Record<string, string> = {
  education:     "bg-blue-50 text-blue-700 border-blue-200",
  sante:         "bg-rose-50 text-rose-700 border-rose-200",
  environnement: "bg-emerald-50 text-emerald-700 border-emerald-200",
  communautaire: "bg-amber-50 text-amber-700 border-amber-200",
}

const VISIBLE_COUNT = 4
const SLIDE_INTERVAL = 5000

const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000"

export default function ProjetsPharesCarousel() {
  const locale = useLocale()
  const isFr = locale !== "en"
  const [startIndex, setStartIndex] = useState(0)
  const [direction, setDirection] = useState(1)
  const isPausedRef = useRef(false)
  // Données depuis l'API (gérées dans l'admin). Repli sur le contenu statique si indisponible.
  const [items, setItems] = useState<RseAction[]>(RSE_ACTIONS)

  useEffect(() => {
    let cancelled = false
    fetch(`${API_URL}/api/fondation-projets`, { signal: AbortSignal.timeout(5000) })
      .then((res) => (res.ok ? res.json() : Promise.reject()))
      .then((data: Record<string, unknown>[]) => {
        if (cancelled || !Array.isArray(data) || data.length === 0) return
        setItems(
          data.map((p) => ({
            id: String(p.id),
            category: (p.category as RseAction["category"]) ?? "communautaire",
            titleFr: (p.title_fr as string) ?? "",
            titleEn: (p.title_en as string) || (p.title_fr as string) || "",
            descFr: (p.description_fr as string) ?? "",
            descEn: (p.description_en as string) || (p.description_fr as string) || "",
            image: (p.image_url as string) || "/media/generique.jpg",
            linkedInUrl: (p.linkedin_url as string) || undefined,
          }))
        )
      })
      .catch(() => { /* repli silencieux sur les données statiques */ })
    return () => { cancelled = true }
  }, [])

  const listLength = items.length
  const totalPages = Math.ceil(listLength / VISIBLE_COUNT)

  // Auto-avance (en pause au survol)
  useEffect(() => {
    if (listLength <= VISIBLE_COUNT) return
    const timer = setInterval(() => {
      if (isPausedRef.current) return
      setDirection(1)
      setStartIndex((i) => ((Math.round(i / VISIBLE_COUNT) + 1) % totalPages) * VISIBLE_COUNT)
    }, SLIDE_INTERVAL)
    return () => clearInterval(timer)
  }, [listLength, totalPages])

  const handlePrev = () => {
    setDirection(-1)
    setStartIndex((i) => ((Math.round(i / VISIBLE_COUNT) - 1 + totalPages) % totalPages) * VISIBLE_COUNT)
  }
  const handleNext = () => {
    setDirection(1)
    setStartIndex((i) => ((Math.round(i / VISIBLE_COUNT) + 1) % totalPages) * VISIBLE_COUNT)
  }

  const visible = items.slice(startIndex, startIndex + VISIBLE_COUNT)

  return (
    <div className="space-y-4">
      {/* Grille de cartes */}
      <div
        className="relative overflow-hidden"
        onMouseEnter={() => { isPausedRef.current = true }}
        onMouseLeave={() => { isPausedRef.current = false }}
      >
        <AnimatePresence mode="popLayout" initial={false} custom={direction}>
          <motion.div
            key={startIndex}
            custom={direction}
            variants={{
              enter: (dir: number) => ({ x: dir > 0 ? "100%" : "-100%" }),
              center: { x: 0 },
              exit: (dir: number) => ({ x: dir > 0 ? "-100%" : "100%" }),
            }}
            initial="enter"
            animate="center"
            exit="exit"
            transition={{ duration: 0.5, ease: "easeInOut" }}
            className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-5 lg:gap-6 pt-4 items-stretch"
          >
            {visible.map((a) => {
              const title = isFr ? a.titleFr : a.titleEn
              const full = isFr ? a.descFr : a.descEn
              const description = full.length > 130 ? full.substring(0, 130) + "..." : full
              return (
                <div key={a.id} className="flex flex-col h-full">
                  <a
                    href={resolveLinkedIn(a)}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex flex-col h-full border-2 border-gray-200 bg-white overflow-hidden shadow-sm transition-all duration-300 hover:shadow-xl hover:shadow-accent/20 hover:-translate-y-1 hover:scale-[1.02] cursor-pointer group"
                  >
                    <div className="relative w-full aspect-[4/3] overflow-hidden bg-gray-100">
                      <Image
                        src={a.image}
                        alt={title}
                        fill
                        className="object-cover transition-transform duration-500 group-hover:scale-105"
                        sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 25vw"
                      />
                      {/* Pastille LinkedIn */}
                      <span className="absolute top-2 right-2 inline-flex items-center justify-center w-7 h-7 bg-[#0A66C2] text-white text-[11px] font-bold rounded-sm shadow-md opacity-0 group-hover:opacity-100 transition-opacity duration-300" aria-hidden>
                        in
                      </span>
                    </div>
                    <div className="p-4 sm:p-5 flex-1 flex flex-col gap-2.5 min-h-0">
                      <span className={`inline-flex self-start text-[10px] font-semibold uppercase tracking-widest px-2.5 py-1 border rounded-sm ${CATEGORY_COLORS[a.category]}`}>
                        {isFr ? CATEGORY_LABELS[a.category].fr : CATEGORY_LABELS[a.category].en}
                      </span>
                      <h3 className="text-sm font-bold text-gray-900 leading-snug line-clamp-2">
                        {title}
                      </h3>
                      <p className="text-gray-500 text-xs leading-relaxed flex-1 line-clamp-3">
                        {description}
                      </p>
                      <span className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-widest text-primary pt-1">
                        {isFr ? "Voir sur LinkedIn" : "View on LinkedIn"}
                        <ExternalLink className="w-3 h-3" />
                      </span>
                    </div>
                  </a>
                </div>
              )
            })}
          </motion.div>
        </AnimatePresence>
      </div>

      {/* Barre de progression auto */}
      {listLength > VISIBLE_COUNT && (
        <div className="h-px bg-gray-100 overflow-hidden mt-3">
          <motion.div
            key={startIndex}
            className="h-full bg-primary/40"
            initial={{ width: "0%" }}
            animate={{ width: "100%" }}
            transition={{ duration: SLIDE_INTERVAL / 1000, ease: "linear" }}
          />
        </div>
      )}

      {/* Pagination */}
      {listLength > VISIBLE_COUNT && (
        <div className="flex justify-center gap-2 mt-8">
          <button
            type="button"
            onClick={handlePrev}
            aria-label={isFr ? "Projets précédents" : "Previous projects"}
            className="w-8 h-8 flex items-center justify-center border border-primary/60 bg-white text-primary hover:bg-primary hover:text-white transition-colors"
          >
            <ChevronLeft className="w-3.5 h-3.5" />
          </button>
          <button
            type="button"
            onClick={handleNext}
            aria-label={isFr ? "Projets suivants" : "Next projects"}
            className="w-8 h-8 flex items-center justify-center border border-primary/60 bg-white text-primary hover:bg-primary hover:text-white transition-colors"
          >
            <ChevronRight className="w-3.5 h-3.5" />
          </button>
        </div>
      )}
    </div>
  )
}
