"use client"

import { useState, useEffect, useRef, forwardRef } from "react"
import HTMLFlipBook from "react-pageflip"
import Image from "next/image"
import { useLocale } from "next-intl"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { RSE_ACTIONS, type RseAction } from "./projets-phares-carousel"

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

// react-pageflip n'expose pas de types stricts pour toutes ses props → cast souple
const FlipBook = HTMLFlipBook as unknown as React.ComponentType<any>

const SERIF = { fontFamily: "var(--font-playfair), Georgia, serif" }

const CAT: 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" },
}

// Pages, react-pageflip exige que chaque page transmette une ref vers un élément DOM
const Page = forwardRef<HTMLDivElement, { children: React.ReactNode; className?: string }>(
  function Page({ children, className = "" }, ref) {
    return <div ref={ref} className={`bg-white ${className}`}>{children}</div>
  }
)

export default function ProjetsPharesBook() {
  const locale = useLocale()
  const isFr = locale !== "en"
  const bookRef = useRef<any>(null)
  // Données résolues UNE seule fois : react-pageflip prend le contrôle du DOM,
  // on ne doit pas changer ses enfants après initialisation (sinon erreur removeChild avec React 19).
  const [items, setItems] = useState<RseAction[] | null>(null)

  useEffect(() => {
    let cancelled = false
    fetch(`${API_URL}/api/fondation-projets`, { signal: AbortSignal.timeout(5000) })
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((data: Record<string, unknown>[]) => {
        if (cancelled) return
        if (!Array.isArray(data) || data.length === 0) { setItems(RSE_ACTIONS); 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(() => { if (!cancelled) setItems(RSE_ACTIONS) })
    return () => { cancelled = true }
  }, [])

  const flip = (dir: number) => {
    const pf = bookRef.current?.pageFlip?.()
    if (!pf) return
    if (dir > 0) pf.flipNext()
    else pf.flipPrev()
  }

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "ArrowRight") flip(1)
      if (e.key === "ArrowLeft") flip(-1)
    }
    window.addEventListener("keydown", onKey)
    return () => window.removeEventListener("keydown", onKey)
  }, [])

  if (!items) {
    return <div className="text-center text-sm text-gray-400 py-12">Chargement…</div>
  }

  return (
    <div className="flex flex-col items-center">
      <FlipBook
        key={`book-${items.length}`}
        ref={bookRef}
        width={400}
        height={450}
        size="stretch"
        minWidth={260}
        maxWidth={460}
        minHeight={300}
        maxHeight={500}
        maxShadowOpacity={0.4}
        showCover={false}
        usePortrait={true}
        mobileScrollSupport={true}
        flippingTime={700}
        drawShadow={true}
        className="select-none"
        style={{}}
      >
        {/* ── Pages projets (le livre est toujours ouvert, pas de couverture) ── */}
        {items.map((p, i) => {
          const title = isFr ? p.titleFr : p.titleEn
          const desc = isFr ? p.descFr : p.descEn
          const cat = isFr ? CAT[p.category]?.fr : CAT[p.category]?.en
          return (
            <Page key={p.id} className="relative flex flex-col h-full overflow-hidden border-2 border-gray-200">
              {/* 2/5 et non la moitié : la page ayant été raccourcie, l'image
                  cède de la hauteur au texte, dont la description est tronquée
                  par overflow-hidden dès qu'elle déborde. */}
              <div className="relative h-2/5 w-full bg-gray-100 flex-shrink-0">
                <Image src={p.image} alt={title} fill className="object-cover" sizes="460px" />
                <span className="absolute top-3 left-3 inline-flex items-center px-2.5 py-1 text-[10px] font-semibold uppercase tracking-widest text-white bg-primary/90">{cat}</span>
              </div>
              {/* pb-7 réserve la bande du folio : la description porte flex-1 et
                  s'étendrait sinon jusqu'au bord, en passant sous le numéro. */}
              <div className="flex-1 flex flex-col p-4 pb-10 min-h-0">
                {/* Le filet rouge reste solidaire du titre, écart serré au-dessus,
                    large en dessous : c'est ce qui détache la description du titre
                    au lieu de les faire lire comme un seul bloc. */}
                <h4 className="font-bold text-gray-900 leading-snug mb-3 line-clamp-3" style={SERIF}>{title}</h4>
                <div className="h-0.5 w-8 bg-primary/70 rounded-full mb-6" aria-hidden />
                <p className="text-[12px] text-gray-600 leading-relaxed flex-1 overflow-hidden">{desc}</p>
              </div>
              {/* Folio, ancré au bas de la page et centré sur toute sa largeur,
                  comme dans un livre imprimé, et non plus à la suite du texte.
                  Le total est porté par les commandes sous le livre : une page
                  imprimée ne rappelle pas le nombre de pages du volume. */}
              <span
                className="pointer-events-none absolute bottom-3 left-0 right-0 text-center text-lg font-bold tabular-nums text-gray-600"
                style={SERIF}
              >
                {i + 1}
              </span>
            </Page>
          )
        })}

        {/* ── Page de fin ──
            Une derniere page de livre porte l'embleme de la maison, rien
            d'autre. Meme filet que les pages projets : le fond bleu nuit
            precedent faisait lire une carte rapportee. */}
        <Page className="relative h-full border-2 border-gray-200 p-8 text-center">
          {/* Tout tient dans un calque qui couvre la page : react-pageflip
              impose son propre affichage sur l'element de page, et un `flex`
              pose dessus reste sans effet. Le calque, lui, garde le sien. */}
          <div className="absolute inset-0 flex flex-col items-center gap-4 p-8 pt-12">
            <p className="text-[12.5px] leading-relaxed text-gray-600">
              {isFr
                ? "Merci d’avoir parcouru nos réalisations."
                : "Thank you for reading through our work."}
            </p>
            <p className="text-[12.5px] leading-relaxed text-gray-600">
              {isFr
                ? "La Fondation SAR poursuit son engagement auprès des communautés."
                : "The SAR Foundation continues its commitment alongside communities."}
            </p>

            <div className="h-0.5 w-10 rounded-full bg-primary/70" aria-hidden />

            <Image
              src="/fondation-sar-logo.jpg"
              alt={isFr ? "Logo Fondation SAR" : "SAR Foundation logo"}
              width={830}
              height={445}
              /* Le JPEG est detoure sur blanc : multiply efface son fond au lieu
                 de poser un rectangle plus clair que le papier. */
              className="mt-2 h-auto w-44 mix-blend-multiply"
            />
          </div>
        </Page>
      </FlipBook>

      {/* ── Contrôles ── */}
      <div className="flex items-center justify-center gap-4 mt-4">
        <button type="button" onClick={() => flip(-1)} aria-label={isFr ? "Page précédente" : "Previous page"}
          className="w-11 h-11 inline-flex items-center justify-center border-2 border-gray-200 bg-white text-primary hover:bg-gray-50 hover:border-gray-300 transition-colors shadow-sm">
          <ChevronLeft className="w-5 h-5" />
        </button>
        <button type="button" onClick={() => flip(1)} aria-label={isFr ? "Page suivante" : "Next page"}
          className="w-11 h-11 inline-flex items-center justify-center border-2 border-gray-200 bg-white text-primary hover:bg-gray-50 hover:border-gray-300 transition-colors shadow-sm">
          <ChevronRight className="w-5 h-5" />
        </button>
      </div>
    </div>
  )
}
