"use client"

import { usePathname } from "next/navigation"
import { useEffect, useRef, useState } from "react"
import { motion, AnimatePresence } from "framer-motion"
import Image from "next/image"
import { useLoading } from "@/components/loading-context"

export default function PageTransitionLoader() {
  const pathname = usePathname()
  const prevPathRef = useRef(pathname)
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const [loading, setLoading] = useState(true)
  const [canHide, setCanHide] = useState(false)
  const { setIsLoaded, pageDataReady, setPageDataReady } = useLoading()

  const startLoading = () => {
    if (timerRef.current) clearTimeout(timerRef.current)
    setCanHide(false)
    setLoading(true)
    setIsLoaded(false)
    // Réinitialiser pageDataReady pour les pages sans données async
    setPageDataReady(true)
    // Durée minimale d'un cycle de barre (0.8s)
    timerRef.current = setTimeout(() => setCanHide(true), 800)
  }

  // Fermer le loader quand le temps min est écoulé ET que la page est prête
  useEffect(() => {
    if (canHide && pageDataReady) {
      if (typeof window !== "undefined") {
        const hash = window.location.hash
        if (hash) {
          // Scroller vers la section ciblée par l'ancre
          const target = document.querySelector(hash)
          if (target) {
            target.scrollIntoView({ behavior: "instant" as ScrollBehavior })
          }
        } else {
          // Pas d'ancre : remonter en haut (l'overlay cache le saut pendant le fade-out)
          window.scrollTo(0, 0)
        }
      }
      setLoading(false)
      setIsLoaded(true)
    }
  }, [canHide, pageDataReady])

  // Afficher au montage (refresh)
  useEffect(() => {
    startLoading()
    return () => { if (timerRef.current) clearTimeout(timerRef.current) }
  }, [])

  // Afficher à chaque changement de route
  useEffect(() => {
    if (pathname !== prevPathRef.current) {
      prevPathRef.current = pathname
      startLoading()
    }
  }, [pathname])

  return (
    <AnimatePresence>
      {loading && (
        <motion.div
          initial={{ opacity: 1 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.25 }}
          className="fixed inset-0 z-[9998] flex flex-col items-center justify-center bg-white"
        >
          <div className="mb-6">
            <Image
              src="/loader-sar-logo.png"
              alt="SAR - Société Africaine de Raffinage"
              width={400}
              height={200}
              className="w-72 md:w-96 h-auto object-contain"
              priority
            />
          </div>

          <div className="w-48 md:w-64 h-1.5 bg-gray-200 rounded-full overflow-hidden">
            <div className="loader-bar h-full bg-[#E52621] w-1/3 rounded-full" />
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
