"use client"

import { useState, useEffect } from "react"
import { motion } from "framer-motion"
import { useRevelationInView } from "@/lib/panel-reveal"
import { useTranslations, useLocale } from "next-intl"
import { Play, ArrowRight, Info } from "lucide-react"
import Link from "next/link"
import SectionLabel from "./section-label"
import { useCookieConsent } from "./cookie-consent"
import CookieIframePlaceholder from "./cookie-iframe-placeholder"

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

type VideoItem = { videoKey: string; duration: string; videoId: string; title?: string; titleEn?: string }
type Props = { sectionTitle?: string; videos?: VideoItem[]; section?: string; showMediathequeLink?: boolean; showAiDisclaimer?: boolean; bgClass?: string; titleVariant?: "overline" | "sr-only" }

const defaultVideos: VideoItem[] = [
  { videoKey: "video1",  duration: "3:57", videoId: "QOTPxn9Wg-A" },
  { videoKey: "video7",  duration: "3:25", videoId: "E_eTqXMnlK4" },
  { videoKey: "video8",  duration: "4:15", videoId: "_6uIvDzqsXE" },
  { videoKey: "video9",  duration: "4:50", videoId: "6nuFQhwJNGk" },
  { videoKey: "video34", duration: "",     videoId: "7sg70K0WBu0" },
  { videoKey: "video14", duration: "",     videoId: "XtijmErwOe8" },
]

// Détection de la source vidéo : Cloudflare Stream (auto-hébergé) vs YouTube
const isCloudflare = (src: string) => src.includes("cloudflarestream.com")
const cfBase = (src: string) => {
  const m = src.match(/(https?:\/\/[^/]*cloudflarestream\.com\/[A-Za-z0-9]+)/)
  return m ? m[1] : src.replace(/\/(watch|iframe)\/?$/, "")
}
const embedSrc = (videoId: string) =>
  isCloudflare(videoId)
    ? `${cfBase(videoId)}/iframe?autoplay=true&muted=true&loop=true`
    : `https://www.youtube.com/embed/${videoId}?autoplay=1&mute=1&loop=1&playlist=${videoId}&rel=0&modestbranding=1`

export default function InstitutionalVideo({ sectionTitle, videos, section = "home", showMediathequeLink = true, showAiDisclaimer = false, bgClass = "bg-white", titleVariant = "overline" }: Props = {}) {
  const t = useTranslations("institutionalVideo")
  const locale = useLocale()
  const [ref, inView] = useRevelationInView({ triggerOnce: true, threshold: 0.15 })
  const [activeIndex, setActiveIndex] = useState(0)
  const [apiVideos, setApiVideos] = useState<VideoItem[] | null>(null)

  // Si aucune liste n'est passée en prop (section "Vidéos" de l'accueil), on charge depuis l'API.
  useEffect(() => {
    if (videos) return
    fetch(`${API_URL}/api/videos?section=${section}`, { signal: AbortSignal.timeout(5000) })
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((data: Record<string, unknown>[]) => {
        if (!Array.isArray(data) || data.length === 0) return
        setApiVideos(
          data.map((v) => ({
            videoKey: `api-${v.id}`,
            videoId: String(v.youtube_id ?? ""),
            duration: (v.duration as string) ?? "",
            title: (v.title as string) ?? "",
            titleEn: (v.title_en as string) || (v.title as string) || "",
          }))
        )
      })
      .catch(() => { /* repli silencieux sur defaultVideos */ })
  }, [videos, section])

  const videoList = videos ?? (apiVideos && apiVideos.length ? apiVideos : defaultVideos)
  const active = videoList[activeIndex] ?? videoList[0]
  const { consent } = useCookieConsent()

  // Titre : depuis l'API/prop si présent, sinon depuis les traductions (vidéos par défaut)
  const vTitle = (v: VideoItem) =>
    v.title ? (locale === "en" ? (v.titleEn || v.title) : v.title) : t(`videos.${v.videoKey}.title`)

  if (videoList.length === 0) {
    return (
      <section ref={ref} className={`pt-8 sm:pt-10 md:pt-12 pb-14 sm:pb-16 md:pb-20 ${bgClass} overflow-hidden`}>
        <div className="px-3 sm:px-4 lg:px-6">
          <div className="max-w-[98%] mx-auto">
            <SectionLabel title={sectionTitle ?? t("sectionTitle")} size="small" variant={titleVariant} />
          </div>
        </div>
        {showAiDisclaimer && (
          <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 mt-4 mb-2">
            <div className="flex gap-3 bg-neutral-50 border border-neutral-200 border-l-4 border-l-neutral-400 px-4 py-3">
              <Info className="w-4 h-4 text-neutral-400 flex-shrink-0 mt-0.5" />
              <p className="text-[11px] text-neutral-500 leading-relaxed">
                {locale === "en"
                  ? "These videos were generated by artificial intelligence (Google NotebookLM) for educational purposes, to illustrate the main stages of the refining process. Although based on verified sources, they may contain inaccuracies. SAR declines all liability for any errors or omissions."
                  : "Ces vidéos ont été générées par intelligence artificielle (Google NotebookLM) à des fins pédagogiques, afin d'illustrer les grandes étapes du processus de raffinage. Bien que fondées sur des sources vérifiées, elles sont susceptibles de contenir des inexactitudes. La SAR décline toute responsabilité en cas d'erreur ou d'omission."}
              </p>
            </div>
          </div>
        )}
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 mt-8">
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={inView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.6 }}
            className="flex flex-col items-center justify-center py-16 border border-dashed border-neutral-300 bg-neutral-50 text-center gap-3"
          >
            <Play className="w-10 h-10 text-neutral-300" />
            <p className="text-sm font-semibold text-neutral-400 uppercase tracking-widest">
              {locale === "en" ? "Training videos coming soon" : "Vidéos de formation bientôt disponibles"}
            </p>
          </motion.div>
        </div>
      </section>
    )
  }

  return (
    <section ref={ref} className={`pt-8 sm:pt-10 md:pt-12 pb-14 sm:pb-16 md:pb-20 ${bgClass} overflow-hidden`}>
      {/* Label */}
      <div className="px-3 sm:px-4 lg:px-6">
        <div className="max-w-[98%] mx-auto">
          <SectionLabel title={sectionTitle ?? t("sectionTitle")} size="small" variant={titleVariant} />
        </div>
      </div>

      {showAiDisclaimer && (
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 mt-4 mb-2">
          <div className="flex gap-3 bg-neutral-50 border border-neutral-200 border-l-4 border-l-neutral-400 px-4 py-3">
            <Info className="w-4 h-4 text-neutral-400 flex-shrink-0 mt-0.5" />
            <p className="text-[11px] text-neutral-500 leading-relaxed">
              {locale === "en"
                ? "These videos were generated by artificial intelligence (Google NotebookLM) for educational purposes, to illustrate the main stages of the refining process. Although based on verified sources, they may contain inaccuracies. SAR declines all liability for any errors or omissions."
                : "Ces vidéos ont été générées par intelligence artificielle (Google NotebookLM) à des fins pédagogiques, afin d'illustrer les grandes étapes du processus de raffinage. Bien que fondées sur des sources vérifiées, elles sont susceptibles de contenir des inexactitudes. La SAR décline toute responsabilité en cas d'erreur ou d'omission."}
            </p>
          </div>
        </div>
      )}

      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
        <motion.div
          className="flex flex-col gap-5 lg:grid"
          style={{ gridTemplateColumns: '1fr 15rem', gridTemplateRows: 'auto 1fr' }}
          initial={{ opacity: 0, y: 24 }}
          animate={inView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
        >
          {/* ── [lg: col1/row1] En lecture header ───────────────────────── */}
          <div className="mb-3 flex items-start justify-between gap-4">
            <div>
              <p className="text-[11px] font-semibold uppercase tracking-widest text-primary mb-1">
                En lecture
              </p>
              <h3 className="text-base sm:text-lg font-bold text-gray-900 leading-snug line-clamp-2">
                {vTitle(active)}
              </h3>
            </div>
          </div>

          {/* ── [lg: col1/row2] Player ──────────────────────────────────── */}
          <div
            className="overflow-hidden shadow-[0_8px_40px_rgba(15,23,42,0.12)] border-2 border-gray-200 min-w-0"
            style={{ gridColumn: 1, gridRow: 2 }}
          >
            <div className="relative w-full" style={{ paddingBottom: "56.25%" }}>
              {isCloudflare(active.videoId) || consent === "accepted" ? (
                <iframe
                  key={active.videoId}
                  src={embedSrc(active.videoId)}
                  className="absolute inset-0 w-full h-full"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen"
                  allowFullScreen
                  style={{ border: "none" }}
                  title={vTitle(active)}
                />
              ) : (
                <CookieIframePlaceholder
                  type="youtube"
                  className="absolute inset-0 w-full h-full"
                />
              )}
            </div>
          </div>

          {/* ── [lg: col2/row2] Playlist ────────────────────────────────── */}
          <div
            className="flex flex-col border-2 border-gray-200"
            style={{ gridColumn: 2, gridRow: 2 }}
          >
            {/* Header */}
            <div className="px-4 py-3 border-b border-neutral-100">
              <p className="text-[9px] font-semibold uppercase tracking-widest text-primary/60">
                Playlist
              </p>
            </div>

            {/* Items */}
            <div className="flex-1 grid grid-cols-2 lg:flex lg:flex-col divide-y divide-neutral-100 overflow-hidden">
              {videoList.map((video, index) => {
                const isActive = index === activeIndex
                return (
                  <motion.button
                    key={video.videoId}
                    onClick={() => setActiveIndex(index)}
                    initial={{ opacity: 0, x: 12 }}
                    animate={inView ? { opacity: 1, x: 0 } : {}}
                    transition={{ duration: 0.4, delay: 0.15 + index * 0.07 }}
                    className={`group flex items-start gap-3 px-4 py-3 text-left w-full transition-colors duration-150 ${
                      isActive ? "bg-primary/5" : "bg-white hover:bg-neutral-50"
                    }`}
                  >
                    {/* Icône play */}
                    <div className={`flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center mt-0.5 transition-all duration-150 ${
                      isActive ? "bg-primary" : "bg-neutral-200 group-hover:bg-neutral-300"
                    }`}>
                      <Play className={`w-2.5 h-2.5 ml-0.5 ${isActive ? "text-white" : "text-gray-500"}`} fill="currentColor" />
                    </div>

                    {/* Texte */}
                    <div className="min-w-0 flex-1">
                      <p className={`text-[11px] font-semibold leading-snug line-clamp-2 transition-colors ${
                        isActive ? "text-primary" : "text-gray-700 group-hover:text-gray-900"
                      }`}>
                        {vTitle(video)}
                      </p>
                      {video.duration && (
                        <span className="text-[10px] text-gray-400 font-mono mt-0.5 block">{video.duration}</span>
                      )}
                    </div>
                  </motion.button>
                )
              })}
            </div>

            {/* Lien médiathèque */}
            {showMediathequeLink && (
              <Link
                href={`/${locale}/medias#mediatheque`}
                className="flex items-center justify-center gap-1.5 w-full py-2.5 text-[9px] font-semibold uppercase tracking-widest text-gray-400 hover:text-primary border-t border-neutral-200 hover:bg-neutral-50 transition-all duration-200 group"
              >
                {locale === "en" ? "See all videos" : "Voir toutes les vidéos"}
                <ArrowRight className="w-3 h-3 group-hover:translate-x-0.5 transition-transform duration-200" />
              </Link>
            )}
          </div>

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