"use client"

import { useState, useEffect, useRef, useMemo } from "react"
import Link from "next/link"
import Image from "next/image"
import { useTranslations, useLocale } from 'next-intl'
import { usePathname, useRouter } from 'next/navigation'
import { Menu, X, ChevronDown, Search, LogOut, Settings, ChevronRight, Phone, MapPin, Mail } from "lucide-react"
import { motion, AnimatePresence } from "framer-motion"
import { locales } from '@/i18n'
import { searchStaticPages, type StaticPage } from '@/lib/static-search-index'

interface AuthUser {
  email: string
  name?: string
}

const SAR_USER_KEY = "sar_user"

export default function Navbar() {
  const t = useTranslations('navbar')
  // Les entrées de « Qui sommes-nous ? » reprennent les onglets de la page
  // Entreprise : un seul libellé à maintenir pour les deux.
  const tSections = useTranslations('entreprise.onglets')
  // Idem pour « Que faisons-nous ? » et les onglets de la page Activités.
  const tMetiers = useTranslations('activites.onglets')
  // Et pour « Fondation SAR » et les onglets de la page Fondation.
  const tFondation = useTranslations('fondation.onglets')
  const locale = useLocale()
  const pathname = usePathname()
  const router = useRouter()
  const [isOpen, setIsOpen] = useState(false)
  const [hidden, setHidden] = useState(false)

  const [openDropdown, setOpenDropdown] = useState<string | null>(null)
  const [langDropdownOpen, setLangDropdownOpen] = useState(false)
  const [searchOpen, setSearchOpen] = useState(false)
  const [searchValue, setSearchValue] = useState("")
  const [activeSuggestion, setActiveSuggestion] = useState(-1)

  const suggestions = useMemo<StaticPage[]>(() => {
    if (searchValue.trim().length < 2) return []
    return searchStaticPages(searchValue, locale).slice(0, 5)
  }, [searchValue, locale])
  const [currentUser, setCurrentUser] = useState<AuthUser | null>(null)
  const searchRef = useRef<HTMLDivElement>(null)
  const langRef = useRef<HTMLDivElement>(null)

  // Lire l'utilisateur depuis localStorage (au montage + à chaque changement de page,
  // pour refléter une connexion/déconnexion faite sur la page /login ou /admin)
  useEffect(() => {
    try {
      const stored = localStorage.getItem(SAR_USER_KEY)
      setCurrentUser(stored ? JSON.parse(stored) : null)
    } catch { /* ignoré */ }
  }, [pathname])

  const handleLogout = async () => {
    await fetch("/api/auth/logout", { method: "POST" }).catch(() => {})
    localStorage.removeItem(SAR_USER_KEY)
    setCurrentUser(null)
    router.push(`/${locale}`)
  }

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      const t = e.target as Node
      if (searchRef.current && !searchRef.current.contains(t)) { setSearchOpen(false); setSearchValue(""); setActiveSuggestion(-1) }
      if (langRef.current && !langRef.current.contains(t)) setLangDropdownOpen(false)
    }
    document.addEventListener("mousedown", handleClickOutside)
    return () => document.removeEventListener("mousedown", handleClickOutside)
  }, [])


  // Fermer le menu mobile au passage en vue desktop
  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth >= 1280) {
        setIsOpen(false)
        setOpenDropdown(null)
      }
    }
    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [])

  // Le navbar n'est visible qu'en tout haut de la page ; dès qu'on défile, il disparaît
  useEffect(() => {
    const onScroll = () => {
      if (isOpen) { setHidden(false); return }
      const atTop = window.scrollY <= 8
      setHidden(!atTop)
      // L'étage 1 se replie : ses panneaux déroulants doivent se fermer avec lui
      if (!atTop) {
        setOpenDropdown(null)
        setLangDropdownOpen(false)
        setSearchOpen(false)
        setSearchValue("")
        setActiveSuggestion(-1)
      }
    }
    onScroll()
    window.addEventListener("scroll", onScroll, { passive: true })
    return () => window.removeEventListener("scroll", onScroll)
  }, [isOpen])

  const scrollToTop = () => {
    if (typeof window !== "undefined") {
      window.scrollTo({ top: 0, behavior: "smooth" })
    }
  }

  // Un lien vers une ancre doit rejoindre sa section : ne pas le renvoyer en haut
  /**
   * Clic sur une entree de menu.
   *
   * Sans ancre : on remonte en tete de page.
   *
   * Avec une ancre pointant sur la page COURANTE : `Link` ne fait rien si l'URL
   * est deja celle-la, et le navigateur n'emet pas de `hashchange` pour une URL
   * identique. L'onglet visee restait donc ferme, et le menu paraissait mort.
   * On ecrit alors le hash nous-memes et on emet l'evenement : les pages a
   * onglets l'ecoutent et ouvrent la bonne section.
   */
  const remonterSiPasDAncre = (href: string, e?: React.MouseEvent) => {
    if (!href.includes("#")) {
      scrollToTop()
      return
    }
    const [chemin, ancre] = href.split("#")
    if (chemin.replace(/\/$/, "") !== pathname.replace(/\/$/, "")) return
    e?.preventDefault()
    if (window.location.hash !== `#${ancre}`) {
      history.pushState(null, "", `#${ancre}`)
    }
    window.dispatchEvent(new HashChangeEvent("hashchange"))
  }

  const menuItems = [
    { name: t('home'),        href: `/${locale}`,                 priority: true },
    {
      name: t('sarGroup'),
      href: `/${locale}/entreprise`,
      priority: false,
      dropdown: [
        // Libellé propre au menu : « Mot du Directeur général » y tenait sur
        // deux lignes et déséquilibrait le panneau.
        { name: t('directorMessageShort'),   href: `/${locale}/entreprise#mot-du-directeur` },
        { name: tSections('mission'),        href: `/${locale}/entreprise#mission` },
        { name: tSections('valeurs'),        href: `/${locale}/entreprise#valeurs` },
        { name: tSections('gouvernance'),    href: `/${locale}/entreprise#gouvernance` },
        { name: tSections('organigramme'),   href: `/${locale}/entreprise#organigramme` },
        { name: tSections('projets'),        href: `/${locale}/entreprise#projets` },
      ],
    },
    {
      name: t('activities'),
      href: `/${locale}/activites`,
      priority: false,
      dropdown: [
        { name: tMetiers('raffinage'),    href: `/${locale}/activites#refining` },
        { name: tMetiers('formation'),    href: `/${locale}/activites#training-videos` },
        { name: tMetiers('etatDesLieux'), href: `/${locale}/activites#etat-des-lieux` },
        { name: tMetiers('produits'),     href: `/${locale}/activites#products` },
        { name: tMetiers('securite'),     href: `/${locale}/activites#safety` },
        { name: tMetiers('laboratoire'),  href: `/${locale}/activites#laboratory` },
      ],
    },
    {
      name: t('foundation'),
      href: `/${locale}/fondation`,
      priority: false,
      dropdown: [
        { name: tFondation('raisonDetre'),  href: `/${locale}/fondation#raison-detre` },
        { name: tFondation('axes'),         href: `/${locale}/fondation#axes` },
        { name: tFondation('objectifs'),    href: `/${locale}/fondation#objectifs` },
        { name: tFondation('zones'),        href: `/${locale}/fondation#zones` },
        { name: tFondation('realisations'), href: `/${locale}/fondation#realisations` },
      ],
    },
    {
      name: t('corporateLife'),
      href: `/${locale}/medias`,
      priority: false,
      dropdown: [
        { name: t('news'),       href: `/${locale}/medias#actualite` },
        { name: t('mediatheque'),href: `/${locale}/medias#mediatheque` },
      ],
    },
    {
      name: t('opportunities'),
      href: `/${locale}/opportunites`,
      priority: false,
      dropdown: [
        { name: t('jobOffers'),  href: `/${locale}/opportunites#emploi` },
        { name: t('applyNow'),   href: `/${locale}/opportunites#candidature` },
        { name: t('tenders'),    href: `/${locale}/opportunites#avis-appel-offres` },
        { name: t('partnership'),href: `/${locale}/opportunites#demande-agrement` },
      ],
    },
    { name: t('contact'),     href: `/${locale}/contact`,         priority: true },
  ]


  const changeLanguage = (newLocale: string) => {
    setLangDropdownOpen(false)
    const newPathname = pathname.replace(`/${locale}`, `/${newLocale}`)
    router.push(newPathname)
  }

  // Les pages a onglets empilent navbar + barre d'onglets + panneau : leur
  // contenu manque de hauteur. Elles replient l'etage 1 en permanence
  // (desktop uniquement : en mobile il porte le bouton du menu).
  // Les pages a rail d'onglets replient l'etage 1 en permanence : navbar,
  // barre d'onglets et panneau s'empilent, chaque pixel gagne en haut est un
  // pixel de contenu visible.
  const pagesSansEtage1 = [
    `/${locale}/entreprise`,
    `/${locale}/activites`,
    `/${locale}/fondation`,
    `/${locale}/opportunites`,
    `/${locale}/medias`,
  ]
  const pageSansEtage1 = pagesSansEtage1.some((prefixe) => pathname.startsWith(prefixe))
  const etage1Replie = hidden || pageSansEtage1


  const isItemActive = (href: string) =>
    href === `/${locale}`
      ? pathname === `/${locale}` || pathname === `/${locale}/`
      : pathname.startsWith(href)

  // Une entête de menu reste active tant qu'on est sur l'une de ses sous-pages
  const isSectionActive = (item: { href: string; dropdown?: { href: string }[] }) =>
    isItemActive(item.href) || (item.dropdown?.some((s) => isItemActive(s.href)) ?? false)

  return (
    <>

      {/* Navbar principale */}
      <motion.nav
        // Repère stable pour les pages qui doivent ancrer un élément juste sous
        // la navbar : sa hauteur varie (repli du premier étage au défilement).
        id="navbar-principal"
        className="fixed top-0 w-full z-50 bg-white shadow-md"
        initial={{ y: -100 }}
        animate={{ y: 0 }}
        transition={{ duration: 0.3, ease: "easeInOut" }}
      >
        {/* ══ Étage 1 : logo + utilitaires, replié au scroll (desktop) ════ */}
        {/* `overflow-hidden` uniquement pendant le repli : sinon il rognerait les
            panneaux déroulants (recherche, langue) positionnés en absolu ici. */}
        <div className={`transition-all duration-300 ${etage1Replie ? "overflow-hidden xl:max-h-0 xl:opacity-0" : "xl:max-h-24 xl:opacity-100"}`}>
        {/* Pleine largeur : le logo et les utilitaires viennent au plus près des
            bords de l'écran, la marge latérale les empêche de les toucher. */}
        <div className="w-full px-5 sm:px-8 lg:px-12 xl:px-16 2xl:px-24">
          <div className="flex items-center justify-between h-14 sm:h-16 min-h-[44px]">
          <Link href={`/${locale}`} className="flex flex-shrink-0 items-center space-x-2 sm:space-x-3 min-h-[44px]">
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} className="flex-shrink-0">
              <Image
                src="/logosar.png"
                alt="SAR Logo"
                width={200}
                height={70}
                className="h-9 w-auto object-contain sm:h-12"
                priority
              />
            </motion.div>
            <span className="text-black text-xs sm:text-sm font-semibold tracking-wide">
              SOCIÉTÉ AFRICAINE DE RAFFINAGE
            </span>
          </Link>

          {/* ── Infos utiles au centre (xl+) : adresse + email, façon Port de Dakar ── */}
          <div className="hidden xl:flex flex-1 items-center justify-center gap-4 text-sm font-medium tracking-wide text-gray-600 whitespace-nowrap">
            <span className="inline-flex items-center gap-1.5">
              <MapPin size={15} className="text-primary flex-shrink-0" />
              Km 18, Route de Rufisque, Mbao
            </span>
            <span className="w-px h-4 bg-neutral-300" aria-hidden />
            <a href="mailto:sar@sar.sn" className="inline-flex items-center gap-1.5 hover:text-primary transition-colors">
              <Mail size={15} className="text-primary flex-shrink-0" />
              sar@sar.sn
            </a>
          </div>

          {/* ══ CÔTÉ DROIT ══════════════════════════════════════════════════ */}
          <div className="flex flex-shrink-0 items-center">

          {/* ── Utilitaires (xl+) : search · langue · numéro vert · connexion ── */}
          <div className="hidden xl:flex items-center gap-4">

            {/* Search */}
            <div className="relative" ref={searchRef}>
              <button
                type="button"
                onClick={() => { setSearchOpen(v => !v); if (searchOpen) { setSearchValue(""); setActiveSuggestion(-1) } }}
                className={`flex items-center justify-center w-8 h-8 transition-colors ${searchOpen ? "text-primary" : "text-foreground/70 hover:text-accent"}`}
                aria-label="Rechercher"
              >
                {searchOpen ? <X size={16} /> : <Search size={16} />}
              </button>

              <AnimatePresence>
                {searchOpen && (
                  <motion.div
                    key="search-dropdown"
                    initial={{ opacity: 0, y: -8 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -8 }}
                    transition={{ duration: 0.2 }}
                    className="absolute top-full right-0 mt-3 w-80 bg-white border border-neutral-200 shadow-xl z-50"
                  >
                    <div className="p-4">
                      <p className="text-[9px] font-semibold uppercase tracking-widest text-gray-400">
                        {locale === "en" ? "Search" : "Recherche"}
                      </p>
                      <div className="h-0.5 w-8 bg-primary/70 mt-1 mb-3" aria-hidden />
                      <div className="flex gap-2">
                        <input
                          type="text"
                          autoFocus
                          value={searchValue}
                          onChange={e => { setSearchValue(e.target.value); setActiveSuggestion(-1) }}
                          placeholder={locale === "en" ? "Keyword…" : "Mot-clé…"}
                          className="flex-1 h-9 px-3 text-sm border border-neutral-200 bg-gray-50 focus:outline-none focus:border-primary transition-colors placeholder:text-gray-400"
                          onKeyDown={e => {
                            if (e.key === "Escape") { setSearchOpen(false); setSearchValue(""); setActiveSuggestion(-1) }
                            if (e.key === "ArrowDown") { e.preventDefault(); setActiveSuggestion(i => Math.min(i + 1, suggestions.length - 1)) }
                            if (e.key === "ArrowUp") { e.preventDefault(); setActiveSuggestion(i => Math.max(i - 1, -1)) }
                            if (e.key === "Enter") {
                              if (activeSuggestion >= 0 && suggestions[activeSuggestion]) {
                                const p = suggestions[activeSuggestion]
                                router.push(`/${locale}${p.url || ""}`)
                                setSearchOpen(false); setSearchValue(""); setActiveSuggestion(-1)
                              } else if (searchValue.trim()) {
                                router.push(`/${locale}/recherche?q=${encodeURIComponent(searchValue.trim())}`)
                                setSearchOpen(false); setSearchValue(""); setActiveSuggestion(-1)
                              }
                            }
                          }}
                        />
                        <button
                          type="button"
                          onClick={() => {
                            if (searchValue.trim()) {
                              router.push(`/${locale}/recherche?q=${encodeURIComponent(searchValue.trim())}`)
                              setSearchOpen(false); setSearchValue(""); setActiveSuggestion(-1)
                            }
                          }}
                          className="h-9 px-3 bg-accent text-white hover:bg-accent/90 transition-colors flex items-center"
                        >
                          <Search size={14} />
                        </button>
                      </div>
                    </div>
                    {suggestions.length > 0 && (
                      <div className="border-t border-neutral-100">
                        {suggestions.map((page, i) => {
                          const title = locale === "en" ? page.titleEn : page.titleFr
                          const isActive = i === activeSuggestion
                          return (
                            <button
                              key={page.url + i}
                              type="button"
                              onMouseEnter={() => setActiveSuggestion(i)}
                              onMouseLeave={() => setActiveSuggestion(-1)}
                              onClick={() => {
                                router.push(`/${locale}${page.url || ""}`)
                                setSearchOpen(false); setSearchValue(""); setActiveSuggestion(-1)
                              }}
                              className={`w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors ${isActive ? "bg-primary/5" : "hover:bg-gray-50"}`}
                            >
                              <div className={`h-0.5 w-4 flex-shrink-0 transition-colors ${isActive ? "bg-primary" : "bg-neutral-200"}`} />
                              <span className={`text-xs font-semibold truncate transition-colors ${isActive ? "text-primary" : "text-gray-700"}`}>{title}</span>
                              <ChevronRight className={`w-3 h-3 ml-auto flex-shrink-0 transition-colors ${isActive ? "text-primary" : "text-gray-300"}`} />
                            </button>
                          )
                        })}
                        <div className="border-t border-neutral-100">
                          <button
                            type="button"
                            onClick={() => {
                              router.push(`/${locale}/recherche?q=${encodeURIComponent(searchValue.trim())}`)
                              setSearchOpen(false); setSearchValue(""); setActiveSuggestion(-1)
                            }}
                            className="w-full flex items-center justify-between px-4 py-2.5 text-[10px] font-semibold uppercase tracking-widest text-gray-400 hover:text-primary hover:bg-gray-50 transition-colors"
                          >
                            {locale === "en" ? "See all results" : "Voir tous les résultats"}
                            <ChevronRight className="w-3 h-3" />
                          </button>
                        </div>
                      </div>
                    )}
                  </motion.div>
                )}
              </AnimatePresence>
            </div>

            {/* Langue */}
            <div className="relative" ref={langRef}>
              <motion.button
                onClick={() => setLangDropdownOpen(!langDropdownOpen)}
                className="flex items-center gap-1.5 h-8 px-2 text-sm font-semibold uppercase tracking-wider text-foreground/80 hover:text-accent transition-colors"
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                aria-haspopup="listbox"
                aria-expanded={langDropdownOpen}
              >
                <span>{locale.toUpperCase()}</span>
                <ChevronDown size={14} className={`transition-transform ${langDropdownOpen ? "rotate-180" : ""}`} />
              </motion.button>
              <AnimatePresence>
                {langDropdownOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.2 }}
                    className="absolute top-full right-0 mt-2 min-w-[4.5rem] bg-white shadow-xl border border-neutral-200 z-50"
                    role="listbox"
                  >
                    {locales.map((loc) => (
                      <button
                        key={loc}
                        onClick={() => changeLanguage(loc)}
                        role="option"
                        aria-selected={locale === loc}
                        className={`flex items-center w-full px-3 py-2 text-left border-b border-neutral-100 last:border-b-0 transition-colors ${
                          locale === loc
                            ? 'bg-primary/5 text-primary'
                            : 'text-foreground/80 hover:bg-gray-50 hover:text-primary'
                        }`}
                      >
                        <span className={`text-[13px] uppercase tracking-wider whitespace-nowrap ${locale === loc ? 'font-semibold' : 'font-medium'}`}>
                          {loc}
                        </span>
                      </button>
                    ))}
                  </motion.div>
                )}
              </AnimatePresence>
            </div>

            {/* Numéro vert. Le halo qui pulsait autour a ete retire : il
                signalait le numero en continu, la ou le navbar doit rester
                calme. Le numero se lit seul. */}
            <div className="w-px h-8 bg-neutral-200" />
            <div className="inline-flex items-center gap-2 px-3.5 h-8 bg-white text-green-600 text-sm font-bold tracking-wide whitespace-nowrap select-none">
              <Phone size={15} className="flex-shrink-0" />
              <span>{locale === 'en' ? 'Toll-free' : 'N° vert'} : 800 00 34 34</span>
            </div>

            {/* Séparateur + Déconnexion, seulement si connecté */}
            {currentUser && <div className="w-px h-8 bg-neutral-200" />}

            <div className="relative">
              {currentUser ? (
                <div className="flex items-center gap-2">
                  <Link
                    href={`/${locale}/admin`}
                    className="flex items-center justify-center w-8 h-8 bg-primary hover:bg-primary/90 transition-colors"
                  >
                    <Settings size={13} className="text-white" />
                  </Link>
                  <button
                    type="button"
                    onClick={handleLogout}
                    className="flex items-center gap-1.5 px-3 h-8 bg-neutral-100 text-xs font-semibold uppercase tracking-wider text-foreground/70 hover:bg-red-50 hover:text-red-600 transition-colors"
                    title={currentUser.email}
                  >
                    <LogOut size={12} />
                    Déconnexion
                  </button>
                </div>
              ) : null}
            </div>
          </div>{/* fin utilitaires */}

          <motion.button
            onClick={() => setIsOpen(!isOpen)}
            className="xl:hidden ml-2 p-2 hover:bg-gray-50 touch-manipulation min-h-[44px] min-w-[44px] flex items-center justify-center transition-colors"
            whileTap={{ scale: 0.9 }}
            aria-label={isOpen ? "Fermer le menu" : "Ouvrir le menu"}
            aria-expanded={isOpen}
          >
            <AnimatePresence mode="wait">
              {isOpen ? (
                <motion.div
                  key="close"
                  initial={{ rotate: -90, opacity: 0 }}
                  animate={{ rotate: 0, opacity: 1 }}
                  exit={{ rotate: 90, opacity: 0 }}
                  transition={{ duration: 0.2 }}
                >
                  <X size={24} />
                </motion.div>
              ) : (
                <motion.div
                  key="menu"
                  initial={{ rotate: 90, opacity: 0 }}
                  animate={{ rotate: 0, opacity: 1 }}
                  exit={{ rotate: -90, opacity: 0 }}
                  transition={{ duration: 0.2 }}
                >
                  <Menu size={24} />
                </motion.div>
              )}
            </AnimatePresence>
          </motion.button>
          </div>{/* fin côté droit */}
        </div>
      </div>
      </div>{/* fin Étage 1 (replié au scroll) */}

      {/* ══ Étage 2 : barre de menu (noire), desktop, items aérés ══════════ */}
      <div className="hidden xl:block bg-black">
        <div className="max-w-7xl mx-auto px-3 sm:px-4 lg:px-8">
          <div className="flex items-center justify-center gap-10 2xl:gap-14 h-9">
            {menuItems.map((item) => {
              const active = isSectionActive(item)
              return (
                <div
                  key={`bar-${item.href}`}
                  className="relative h-full flex items-center"
                  onMouseEnter={item.dropdown ? () => setOpenDropdown(item.name) : undefined}
                  onMouseLeave={item.dropdown ? () => setOpenDropdown(null) : undefined}
                >
                  {item.dropdown ? (
                    <>
                      <button className={`flex items-center gap-1 text-[13px] font-semibold uppercase tracking-wider transition-colors ${active || openDropdown === item.name ? "text-white" : "text-white/80 hover:text-white"}`}>
                        {item.name}
                        <ChevronDown size={14} className={`transition-transform ${openDropdown === item.name ? "rotate-180" : ""}`} />
                      </button>
                      <AnimatePresence>
                        {openDropdown === item.name && (
                          <motion.div
                            initial={{ opacity: 0, y: -8 }}
                            animate={{ opacity: 1, y: 0 }}
                            exit={{ opacity: 0, y: -8 }}
                            transition={{ duration: 0.2 }}
                            className="absolute top-full left-1/2 -translate-x-1/2 w-56 bg-white border border-neutral-200 shadow-xl z-50"
                          >
                            {/* Un filet gris entre deux entrees, comme au rail
                                « Autres projets » de la page Entreprise. Chacune
                                portait un court trait rouge sous son intitule :
                                empiles, ils se lisaient comme des soulignements
                                et rien ne marquait la limite entre deux liens.
                                `last:border-b-0` : le dernier filet doublerait
                                la bordure du panneau. */}
                            <div className="py-1">
                              {item.dropdown.map((subItem) => (
                                <Link
                                  key={subItem.href}
                                  href={subItem.href}
                                  onClick={(e) => remonterSiPasDAncre(subItem.href, e)}
                                  className="block group border-b border-neutral-200 px-4 py-3 transition-colors last:border-b-0 hover:bg-gray-50"
                                >
                                  <p className="text-xs font-semibold uppercase tracking-widest text-gray-400 group-hover:text-primary transition-colors leading-snug">{subItem.name}</p>
                                </Link>
                              ))}
                            </div>
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </>
                  ) : (
                    <Link
                      href={item.href}
                      onClick={scrollToTop}
                      className={`relative group text-[13px] font-semibold uppercase tracking-wider transition-colors ${active ? "text-white" : "text-white/80 hover:text-white"}`}
                    >
                      {item.name}
                      <span className={`absolute -bottom-2 left-0 h-0.5 bg-white transition-all duration-300 ${active ? "w-full" : "w-0 group-hover:w-full"}`} />
                    </Link>
                  )}
                </div>
              )
            })}
          </div>
        </div>
      </div>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            className="xl:hidden bg-white border-t border-neutral-200 max-h-[calc(100dvh-56px)] overflow-y-auto overscroll-contain"
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.25 }}
          >
            <div className="pb-3">

              {/* ── Recherche mobile ── */}
              <div className="border-b border-neutral-100">
                <div className="px-4 pt-2.5 pb-2 flex gap-2">
                  <input
                    type="text"
                    value={searchValue}
                    onChange={e => { setSearchValue(e.target.value); setActiveSuggestion(-1) }}
                    placeholder={locale === "en" ? "Search…" : "Rechercher…"}
                    className="flex-1 h-8 px-3 text-xs border border-neutral-200 bg-gray-50 focus:outline-none focus:border-primary transition-colors placeholder:text-gray-400"
                    onKeyDown={e => {
                      if (e.key === "Enter") {
                        if (activeSuggestion >= 0 && suggestions[activeSuggestion]) {
                          const p = suggestions[activeSuggestion]
                          router.push(`/${locale}${p.url || ""}`)
                          setSearchValue(""); setActiveSuggestion(-1); setIsOpen(false)
                        } else if (searchValue.trim()) {
                          router.push(`/${locale}/recherche?q=${encodeURIComponent(searchValue.trim())}`)
                          setSearchValue(""); setActiveSuggestion(-1); setIsOpen(false)
                        }
                      }
                    }}
                  />
                  <button
                    type="button"
                    onClick={() => {
                      if (searchValue.trim()) {
                        router.push(`/${locale}/recherche?q=${encodeURIComponent(searchValue.trim())}`)
                        setSearchValue(""); setActiveSuggestion(-1); setIsOpen(false)
                      }
                    }}
                    className="h-8 px-3 bg-primary text-white flex items-center transition-colors hover:bg-primary/90"
                  >
                    <Search size={13} />
                  </button>
                </div>

                {/* Suggestions mobile */}
                {suggestions.length > 0 && (
                  <div className="border-t border-neutral-100">
                    {suggestions.map((page, i) => {
                      const title = locale === "en" ? page.titleEn : page.titleFr
                      const isActive = i === activeSuggestion
                      return (
                        <button
                          key={page.url + i}
                          type="button"
                          onClick={() => {
                            router.push(`/${locale}${page.url || ""}`)
                            setSearchValue(""); setActiveSuggestion(-1); setIsOpen(false)
                          }}
                          className={`w-full flex items-center gap-3 px-4 py-2 text-left border-b border-neutral-100 last:border-b-0 transition-colors ${isActive ? "bg-primary/5" : "hover:bg-gray-50"}`}
                        >
                          <div className={`h-0.5 w-4 flex-shrink-0 ${isActive ? "bg-primary" : "bg-neutral-200"}`} />
                          <span className={`text-xs font-semibold truncate ${isActive ? "text-primary" : "text-gray-700"}`}>{title}</span>
                          <ChevronRight className={`w-3 h-3 ml-auto flex-shrink-0 ${isActive ? "text-primary" : "text-gray-300"}`} />
                        </button>
                      )
                    })}
                    <button
                      type="button"
                      onClick={() => {
                        router.push(`/${locale}/recherche?q=${encodeURIComponent(searchValue.trim())}`)
                        setSearchValue(""); setActiveSuggestion(-1); setIsOpen(false)
                      }}
                      className="w-full flex items-center justify-between px-4 py-2 text-[10px] font-semibold uppercase tracking-widest text-gray-400 hover:text-primary hover:bg-gray-50 transition-colors"
                    >
                      {locale === "en" ? "See all results" : "Voir tous les résultats"}
                      <ChevronRight className="w-3 h-3" />
                    </button>
                  </div>
                )}
              </div>

              {/* ── Nav items ── */}
              {menuItems.map((item) => {
                const isActive = isSectionActive(item)

                return (
                  <div key={item.href}>
                    {item.dropdown ? (
                      <>
                        <button
                          onClick={() => setOpenDropdown(openDropdown === item.name ? null : item.name)}
                          className={`flex items-center justify-between w-full px-4 py-2.5 border-l-4 transition-colors touch-manipulation ${
                            openDropdown === item.name || isActive
                              ? "border-l-primary bg-primary/[0.03]"
                              : "border-l-transparent hover:border-l-primary/40 hover:bg-gray-50/80"
                          }`}
                        >
                          <p className={`text-xs font-semibold uppercase tracking-widest text-left transition-colors ${
                            openDropdown === item.name || isActive ? "text-primary" : "text-gray-500"
                          }`}>
                            {item.name}
                          </p>
                          <ChevronDown
                            size={13}
                            className={`flex-shrink-0 transition-transform duration-200 ${
                              openDropdown === item.name ? "rotate-180 text-primary" : "text-gray-400"
                            }`}
                          />
                        </button>

                        <AnimatePresence>
                          {openDropdown === item.name && (
                            <motion.div
                              initial={{ height: 0, opacity: 0 }}
                              animate={{ height: "auto", opacity: 1 }}
                              exit={{ height: 0, opacity: 0 }}
                              transition={{ duration: 0.2 }}
                              className="overflow-hidden"
                            >
                              <div className="border-l-4 border-l-primary/30 bg-gray-50/70">
                                {item.dropdown.map((subItem) => {
                                  const subActive = pathname.startsWith(subItem.href)
                                  return (
                                    <Link
                                      key={subItem.href}
                                      href={subItem.href}
                                      onClick={(e) => { remonterSiPasDAncre(subItem.href, e); setIsOpen(false) }}
                                      className="group flex items-center px-6 py-2 border-b border-neutral-100 last:border-b-0 hover:bg-primary/[0.04] transition-colors touch-manipulation"
                                    >
                                      <p className={`text-xs font-semibold uppercase tracking-widest transition-colors leading-snug ${
                                        subActive ? "text-primary" : "text-gray-400 group-hover:text-primary"
                                      }`}>
                                        {subItem.name}
                                      </p>
                                    </Link>
                                  )
                                })}
                              </div>
                            </motion.div>
                          )}
                        </AnimatePresence>
                      </>
                    ) : (
                      <Link
                        href={item.href}
                        onClick={() => { scrollToTop(); setIsOpen(false) }}
                        className={`flex items-center px-4 py-2.5 border-l-4 transition-colors touch-manipulation ${
                          isActive
                            ? "border-l-primary bg-primary/[0.03]"
                            : "border-l-transparent hover:border-l-primary/40 hover:bg-gray-50/80"
                        }`}
                      >
                        <p className={`text-xs font-semibold uppercase tracking-widest transition-colors ${
                          isActive ? "text-primary" : "text-gray-500"
                        }`}>
                          {item.name}
                        </p>
                      </Link>
                    )}
                  </div>
                )
              })}

              {/* ── Pied : langue + connexion ── */}
              <div className="mx-4 border-t border-neutral-200 mt-2 pt-2 flex items-center justify-between gap-3">

                {/* Langue */}
                <div className="flex gap-1.5">
                  {locales.map((loc) => (
                    <button
                      key={loc}
                      onClick={() => changeLanguage(loc)}
                      className={`inline-flex items-center justify-center min-w-[44px] px-3 py-1.5 text-[11px] font-semibold border transition-colors touch-manipulation ${
                        locale === loc
                          ? 'bg-primary text-white border-primary'
                          : 'border-neutral-200 text-gray-500 hover:border-primary/50 hover:text-primary'
                      }`}
                    >
                      {loc.toUpperCase()}
                    </button>
                  ))}
                </div>

                {/* Connexion */}
                {currentUser ? (
                  <div className="flex gap-1.5">
                    <Link
                      href={`/${locale}/admin`}
                      onClick={() => setIsOpen(false)}
                      className="inline-flex items-center justify-center w-8 h-8 bg-primary hover:bg-primary/90 transition-colors"
                    >
                      <Settings size={13} className="text-white" />
                    </Link>
                    <button
                      type="button"
                      onClick={() => { setIsOpen(false); handleLogout() }}
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 border border-neutral-200 text-[10px] font-semibold uppercase tracking-widest text-gray-500 hover:bg-red-50 hover:text-red-600 transition-colors"
                    >
                      <LogOut size={11} />
                      {locale === "en" ? "Logout" : "Déconnexion"}
                    </button>
                  </div>
                ) : null}
              </div>

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