"use client"

import { useState, useEffect, useRef } from "react"
import { motion, AnimatePresence } from "framer-motion"
import Image from "next/image"
import Link from "next/link"
import { useLocale } from "next-intl"
import { ExternalLink, ArrowRight, ArrowLeft, X } from "lucide-react"
import type { SocialAction } from "@/lib/actualites-data"
import { useCookieConsent } from "./cookie-consent"
import CookieIframePlaceholder from "./cookie-iframe-placeholder"

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

function getLinkedInEmbedUrl(postUrl: string): string {
  if (postUrl.includes('urn:li:')) {
    const urnMatch = postUrl.match(/urn:li:(ugcPost|activity|share):(\d+)/)
    if (urnMatch) {
      const fullUrn = `urn:li:${urnMatch[1]}:${urnMatch[2]}`
      return `https://www.linkedin.com/embed/feed/update/${fullUrn}`
    }
  }

  let match = postUrl.match(/activity[-:](\d+)/)
  if (match) return `https://www.linkedin.com/embed/feed/update/urn:li:activity:${match[1]}`

  match = postUrl.match(/ugcPost[-:](\d+)/)
  if (match) return `https://www.linkedin.com/embed/feed/update/urn:li:ugcPost:${match[1]}`

  match = postUrl.match(/share[-:](\d+)/)
  if (match) return `https://www.linkedin.com/embed/feed/update/urn:li:share:${match[1]}`

  return postUrl
}

function mapApiToSocialAction(item: Record<string, unknown>): SocialAction {
  let imageUrl = (item.image as string) || '/media/generique.jpg'

  if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
    imageUrl = `${API_URL}/${imageUrl}`
  }

  // Les URLs LinkedIn CDN requièrent un token Bearer → fallback immédiat pour éviter le flash
  if (imageUrl.includes('media.licdn.com') || imageUrl.includes('dms.licdn.com')) {
    imageUrl = '/media/generique.jpg'
  }

  return {
    id: String(item.id),
    title: (item.title as string) || '',
    titleEn: (item.title_en as string) || (item.title as string) || '',
    description: (item.content as string) || '',
    descriptionEn: (item.content_en as string) || (item.content as string) || '',
    date: (item.date_iso as string) || (item.date as string) || '',
    category: 'communautaire',
    image: imageUrl,
    linkedInUrl: (item.linkedin_url as string) || undefined,
  }
}

const SLIDE_INTERVAL = 3500

export default function RSEFeaturedCards() {
  const locale = useLocale()
  const { consent } = useCookieConsent()
  const [modalIndex, setModalIndex] = useState<number | null>(null)
  const [apiActions, setApiActions] = useState<SocialAction[] | null>(null)
  // Carrousel continu : on décale d'UNE carte à la fois (fenêtre glissante)
  const [index, setIndex] = useState(0)
  const [visibleCount, setVisibleCount] = useState(4)
  const [noTransition, setNoTransition] = useState(false)
  const isPausedRef = useRef(false)

  useEffect(() => {
    fetch(`${API_URL}/api/actualites/?locale=${locale}`)
      .then((res) => res.ok ? res.json() : Promise.reject())
      .then((data: unknown[]) => {
        const list = Array.isArray(data) ? data : []
        setApiActions(list.map((item) => mapApiToSocialAction(item as Record<string, unknown>)))
      })
      .catch(() => setApiActions(null))
  }, [locale])

  // Nombre de cartes visibles selon la largeur (1 / 2 / 4)
  useEffect(() => {
    const mqLg = window.matchMedia("(min-width: 1024px)")
    const mqSm = window.matchMedia("(min-width: 640px)")
    const sync = () => setVisibleCount(mqLg.matches ? 4 : mqSm.matches ? 2 : 1)
    sync()
    mqLg.addEventListener("change", sync)
    mqSm.addEventListener("change", sync)
    return () => { mqLg.removeEventListener("change", sync); mqSm.removeEventListener("change", sync) }
  }, [])

  const actions: SocialAction[] = apiActions ?? []
  const isFr = locale === 'fr'
  const listLength = actions.length
  const canSlide = listLength > visibleCount

  // Réinitialise la position si la liste ou le nombre visible change
  useEffect(() => { setIndex(0) }, [listLength, visibleCount])

  // Actions avec LinkedIn (navigables dans le modal)
  const linkedInActions = actions.filter(a => a.linkedInUrl)
  const modalLinkedInUrl = modalIndex !== null ? (linkedInActions[modalIndex]?.linkedInUrl ?? null) : null
  const modalPrev = () => setModalIndex(i => i !== null ? (i - 1 + linkedInActions.length) % linkedInActions.length : null)
  const modalNext = () => setModalIndex(i => i !== null ? (i + 1) % linkedInActions.length : null)

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

  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])

  // Auto-avance d'une carte à la fois
  useEffect(() => {
    if (!canSlide) return
    const timer = setInterval(() => {
      if (isPausedRef.current || modalIndex !== null) return
      setIndex((i) => i + 1)
    }, SLIDE_INTERVAL)
    return () => clearInterval(timer)
  }, [canSlide, modalIndex])

  // À la fin de la transition vers les cartes clonées, on revient au début sans animation
  const onTrackTransitionEnd = (e: React.TransitionEvent<HTMLDivElement>) => {
    if (e.target !== e.currentTarget || e.propertyName !== "transform") return
    if (index >= listLength) {
      setNoTransition(true)
      setIndex(0)
      requestAnimationFrame(() => requestAnimationFrame(() => setNoTransition(false)))
    }
  }

  // Liste affichée : on ajoute des clones en fin pour une boucle continue
  const extended = canSlide ? [...actions, ...actions.slice(0, visibleCount)] : actions
  const slotPct = 100 / visibleCount

  if (apiActions !== null && actions.length === 0) {
    return (
      <div className="bg-white border border-neutral-200 border-l-4 border-l-primary p-8 flex flex-col items-center text-center">
        <p className="text-xs font-semibold uppercase tracking-widest text-gray-400 mb-2">
          {isFr ? "Information" : "Information"}
        </p>
        <div className="h-0.5 w-10 bg-primary/70 rounded-full mb-3" aria-hidden />
        <p className="text-sm text-neutral-600">
          {isFr ? "Aucune actualité disponible pour le moment." : "No news available at the moment."}
        </p>
      </div>
    )
  }

  return (
    <>
      <div className="space-y-4">
        {/* La sortie de section est annoncee avant les cartes : le visiteur sait
            des le depart qu'il peut tout voir, sans avoir a parcourir le
            carrousel jusqu'au bout. */}
        <div className="flex justify-center">
          <Link
            href={`/${locale}/medias#actualite`}
            className="group inline-flex items-center gap-2 text-[12px] font-bold uppercase tracking-widest text-white drop-shadow-[0_1px_3px_rgba(0,0,0,0.5)] transition-opacity hover:opacity-80"
          >
            <span className="underline decoration-2 underline-offset-4">
              {isFr ? "Toutes les actualités" : "All news"}
            </span>
            <ArrowRight className="size-4 transition-transform group-hover:translate-x-1" />
          </Link>
        </div>

        {/* Piste du carrousel (défilement carte par carte) */}
        <div
          className="relative overflow-hidden"
          onMouseEnter={() => { isPausedRef.current = true }}
          onMouseLeave={() => { isPausedRef.current = false }}
        >
          <div
            className="flex py-4"
            style={{
              transform: `translateX(-${index * slotPct}%)`,
              transition: noTransition || !canSlide ? "none" : "transform 0.6s ease-in-out",
            }}
            onTransitionEnd={onTrackTransitionEnd}
          >
            {extended.map((action, i) => {
              const title = isFr ? action.title : action.titleEn
              const fullDescription = isFr ? action.description : action.descriptionEn
              const description = fullDescription.length > 160
                ? fullDescription.substring(0, 160) + "..."
                : fullDescription
              const hasLinkedIn = Boolean(action.linkedInUrl)
              const dateLabel = action.date
                ? new Date(action.date).toLocaleDateString(
                    locale === "en" ? "en-GB" : "fr-FR",
                    { day: "numeric", month: "long", year: "numeric" }
                  )
                : null

              const CardWrapper = hasLinkedIn && action.linkedInUrl
                ? ({ children }: { children: React.ReactNode }) => (
                    <button
                      type="button"
                      onClick={() => setModalIndex(linkedInActions.findIndex(a => a.linkedInUrl === action.linkedInUrl))}
                      className="flex flex-col h-full w-full text-left !rounded-none border-2 border-gray-200 transition-all duration-300 shadow-sm bg-white overflow-hidden hover:shadow-xl hover:-translate-y-1 hover:scale-[1.02] cursor-pointer"
                    >
                      {children}
                    </button>
                  )
                : ({ children }: { children: React.ReactNode }) => (
                    <Link
                      href={`/${locale}/medias#actualite`}
                      className="flex flex-col h-full w-full !rounded-none border-2 border-gray-200 transition-all duration-300 shadow-sm bg-white overflow-hidden hover:shadow-xl hover:-translate-y-1 hover:scale-[1.02]"
                    >
                      {children}
                    </Link>
                  )

              return (
                <div
                  key={`${action.id}-${i}`}
                  className="flex flex-col px-2 sm:px-2.5 lg:px-3"
                  style={{ flex: `0 0 ${slotPct}%`, maxWidth: `${slotPct}%` }}
                >
                  <CardWrapper>
                    {/* Le filet de separation reprend le cadre de la carte :
                        l'image et le texte se lisent comme deux registres. */}
                    <div className="relative w-full aspect-[4/3] overflow-hidden border-b-2 border-gray-200 bg-gray-100">
                      <Image
                        src={action.image || "/media/generique.jpg"}
                        alt={title}
                        fill
                        className="object-cover transition-transform duration-500 hover:scale-105"
                        sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 25vw"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement
                          target.src = "/media/generique.jpg"
                        }}
                      />
                    </div>

                    {/* Meme hierarchie que les fiches de la page Actualites :
                        la date en surtitre, le filet rouge, puis le texte. */}
                    <div className="p-4 sm:p-5 flex-1 flex flex-col justify-between min-h-0">
                      <div>
                        {dateLabel && (
                          <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-400 mb-1">
                            {dateLabel}
                          </p>
                        )}
                        <div className="h-0.5 w-10 bg-primary/70 rounded-full mb-3" aria-hidden />
                        <p className="text-sm text-neutral-600 leading-relaxed line-clamp-4">
                          {description}
                        </p>
                      </div>
                      <div className="mt-4 pt-3 border-t border-gray-100 flex justify-end">
                        <span className="inline-flex items-center gap-1 text-[11px] font-semibold uppercase tracking-widest text-primary">
                          {isFr ? "Lire la suite" : "Read more"}
                          <ArrowRight className="w-3 h-3" />
                        </span>
                      </div>
                    </div>
                  </CardWrapper>
                </div>
              )
            })}
          </div>
        </div>
      </div>

      <AnimatePresence>
        {modalIndex !== null && modalLinkedInUrl && (() => {
          const currentAction = linkedInActions[modalIndex]
          const title = isFr ? currentAction?.title : currentAction?.titleEn
          return (
            <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 sm:items-center justify-center sm:p-6 lg:p-12"
              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 sm:max-w-2xl flex flex-col overflow-hidden shadow-2xl h-[100dvh] sm:h-[min(90vh,680px)]"
                onClick={e => e.stopPropagation()}
              >

                {/* Barre de tête */}
                <div className="flex items-center gap-3 bg-white border-b border-neutral-100 border-l-4 border-l-primary 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>
                  <p className="flex-1 text-[10px] font-semibold uppercase tracking-widest text-gray-600 truncate">
                    {title}
                  </p>
                  <a
                    href={modalLinkedInUrl}
                    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"
                  >
                    <ExternalLink className="w-3 h-3" />
                    LinkedIn
                  </a>
                </div>

                {/* Iframe */}
                <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: "#E52621 #f3f4f6", scrollbarWidth: "thin" }}
                >
                  {consent === "accepted" ? (
                    <iframe
                      key={modalLinkedInUrl}
                      src={getLinkedInEmbedUrl(modalLinkedInUrl)}
                      title="Post LinkedIn"
                      className="w-full border-0 block"
                      style={{ minHeight: "520px", height: "100%" }}
                      sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
                    />
                  ) : (
                    <CookieIframePlaceholder
                      type="linkedin"
                      className="w-full"
                      style={{ minHeight: "520px" }}
                    />
                  )}
                </div>

                {/* Navigation prev/next */}
                {linkedInActions.length > 1 && (
                  <div className="flex items-center justify-between bg-white border-t border-neutral-200 px-5 py-3 flex-shrink-0">
                    <button
                      type="button"
                      onClick={modalPrev}
                      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" />
                      {isFr ? "Précédent" : "Previous"}
                    </button>
                    <span className="text-[11px] font-mono text-gray-400 font-bold">
                      {(modalIndex ?? 0) + 1} / {linkedInActions.length}
                    </span>
                    <button
                      type="button"
                      onClick={modalNext}
                      className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-widest text-primary hover:text-primary/70 transition-colors"
                    >
                      {isFr ? "Suivant" : "Next"}
                      <ArrowRight className="w-4 h-4" />
                    </button>
                  </div>
                )}

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