"use client";

import { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
import Image from "next/image";
import { Menu, X, ChevronDown } from "lucide-react";

type NavChild = { label: string; href: string; desc?: string; disabled?: boolean };
type NavLink  = { label: string; href: string; children?: NavChild[]; disabled?: boolean };

const NAV: NavLink[] = [
  { label: "Accueil", href: "/" },
  {
    label: "À propos",
    href: "#",
    children: [
      { label: "Présentation d'ANED", href: "/#mission",    desc: "Notre histoire et notre organisation" },
      { label: "Mot de la Présidente", href: "/mot-de-la-presidente", desc: "Message de la présidente de l'ANED" },
      { label: "Mission & Vision",   href: "/mission",    desc: "Nos valeurs et nos domaines d'action" },
    ],
  },
  { label: "Projets & Activités", href: "/projets" },
  { label: "Partenaires",         href: "/#partenaires" },
  { label: "Actualités",          href: "/actualites" },
  { label: "Soutenir",            href: "/soutenir" },
];

export function Navbar() {
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen]         = useState(false);
  const [mobileExpanded, setMobileExpanded] = useState<string | null>(null);
  const [desktopOpen, setDesktopOpen]       = useState<string | null>(null);
  const [scrolled, setScrolled]             = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setScrolled(window.scrollY > 20);
    };
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const isActive = (href: string) => {
    if (href === "/") return pathname === "/";
    return pathname.startsWith(href);
  };

  const isParentActive = (link: NavLink) => {
    if (link.children) {
      return link.children.some(child => isActive(child.href));
    }
    return false;
  };

  return (
    <nav className={`fixed top-0 left-0 right-0 z-50 bg-white/95 backdrop-blur-md transition-all duration-300 ${
      mobileOpen ? "" : scrolled ? "shadow-lg border-b border-gray-100" : "border-b border-gray-100 shadow-sm"
    }`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className={`flex items-center justify-between transition-all duration-300 ${
          scrolled ? "h-20" : "h-28"
        }`}>

          {/* Logo */}
          <a href="/" className="flex-shrink-0">
            <Image
              src="/aned-logo.png"
              alt="ANED – Association Nutrition Et Développement"
              width={160}
              height={160}
              className={`w-auto transition-all duration-300 ${scrolled ? "h-20" : "h-26"}`}
              priority
            />
          </a>

          {/* Desktop links */}
          <div className="hidden lg:flex items-center gap-1">
            {NAV.map((link) =>
              link.children ? (
                <div
                  key={link.label}
                  className="relative"
                  onMouseEnter={() => setDesktopOpen(link.label)}
                  onMouseLeave={() => setDesktopOpen(null)}
                >
                  <button className={`flex items-center gap-1 px-3 py-2 rounded-lg text-sm font-medium transition-all relative ${
                    isParentActive(link)
                      ? "text-[#4A7C59] font-semibold after:absolute after:bottom-1 after:left-3 after:right-3 after:h-0.5 after:bg-[#4A7C59] after:rounded-full"
                      : "text-gray-700 hover:text-[#4A7C59] hover:bg-gray-50"
                  }`}>
                    {link.label}
                    <ChevronDown
                      size={14}
                      className={`transition-transform duration-200 ${desktopOpen === link.label ? "rotate-180" : ""}`}
                    />
                  </button>

                  <div
                    className={`absolute top-full left-0 pt-2 w-64 transition-all duration-200 ${
                      desktopOpen === link.label ? "opacity-100 translate-y-0 pointer-events-auto" : "opacity-0 -translate-y-1 pointer-events-none"
                    }`}
                  >
                    <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
                    {link.children.map((child) =>
                      child.disabled ? (
                        <span
                          key={child.href}
                          className="flex items-center justify-between px-4 py-3 border-b border-gray-50 last:border-0 cursor-not-allowed opacity-45"
                        >
                          <span className="flex flex-col">
                            <span className="text-sm font-medium text-gray-800">{child.label}</span>
                            {child.desc && <span className="text-xs text-gray-400 mt-0.5">{child.desc}</span>}
                          </span>
                          <span className="text-[10px] font-semibold text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded ml-2 flex-shrink-0">Bientôt</span>
                        </span>
                      ) : (
                        <a
                          key={child.href}
                          href={child.href}
                          className={`flex flex-col px-4 py-3 transition-colors border-b border-gray-50 last:border-0 ${
                            isActive(child.href)
                              ? "bg-[#4A7C59]/5"
                              : "hover:bg-gray-50"
                          }`}
                        >
                          <span className={`text-sm font-medium ${
                            isActive(child.href) ? "text-[#4A7C59] font-semibold" : "text-gray-800"
                          }`}>
                            {child.label}
                          </span>
                          {child.desc && <span className="text-xs text-gray-400 mt-0.5">{child.desc}</span>}
                        </a>
                      )
                    )}
                    </div>
                  </div>
                </div>
              ) : link.disabled ? (
                <span
                  key={link.label}
                  className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium text-gray-400 cursor-not-allowed whitespace-nowrap"
                >
                  {link.label}
                  <span className="text-[10px] font-semibold text-gray-300 bg-gray-100 px-1.5 py-0.5 rounded">Bientôt</span>
                </span>
              ) : (
                <a
                  key={link.label}
                  href={link.href}
                  className={`px-3 py-2 rounded-lg text-sm font-medium transition-all whitespace-nowrap relative ${
                    isActive(link.href)
                      ? "text-[#4A7C59] font-semibold after:absolute after:bottom-1 after:left-3 after:right-3 after:h-0.5 after:bg-[#4A7C59] after:rounded-full"
                      : "text-gray-700 hover:text-[#4A7C59] hover:bg-gray-50"
                  }`}
                >
                  {link.label}
                </a>
              )
            )}
          </div>

          {/* Right side */}
          <div className="flex items-center gap-3">
            {/* Contact CTA - Desktop */}
            <a
              href="/contact"
              className="hidden lg:inline-flex items-center gap-2 bg-[#4A7C59] hover:bg-[#3d6849] text-white px-5 py-2 rounded-lg text-sm font-semibold transition-all hover:shadow-lg"
            >
              Contact
            </a>

            {/* Mobile Menu Button */}
            <button
              onClick={() => setMobileOpen((v) => !v)}
              aria-label={mobileOpen ? "Fermer le menu" : "Ouvrir le menu"}
              className="lg:hidden w-9 h-9 flex items-center justify-center rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 transition-colors"
            >
              {mobileOpen ? <X size={17} /> : <Menu size={17} />}
            </button>
          </div>
        </div>
      </div>

      {/* Mobile Backdrop */}
      {mobileOpen && (
        <div
          className="lg:hidden fixed inset-0 bg-black/20 backdrop-blur-sm z-30"
          style={{ top: scrolled ? '64px' : '80px' }}
          onClick={() => setMobileOpen(false)}
        />
      )}

      {/* Mobile panel */}
      <div
        className={`lg:hidden overflow-hidden transition-all duration-300 ease-in-out bg-white/95 backdrop-blur-md relative z-40 ${
          mobileOpen ? "max-h-[600px]" : "max-h-0"
        }`}
      >
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-3 space-y-0.5">
          {NAV.map((link) =>
            link.children ? (
              <div key={link.label}>
                <button
                  onClick={() => setMobileExpanded((v) => (v === link.label ? null : link.label))}
                  className={`flex items-center justify-between w-full px-3 py-3 rounded-lg text-sm font-medium transition-all relative ${
                    isParentActive(link)
                      ? "text-[#4A7C59] font-semibold after:absolute after:bottom-2 after:left-3 after:right-12 after:h-0.5 after:bg-[#4A7C59] after:rounded-full"
                      : "text-gray-700 hover:bg-gray-50"
                  }`}
                >
                  {link.label}
                  <ChevronDown
                    size={14}
                    className={`text-gray-400 transition-transform duration-200 ${mobileExpanded === link.label ? "rotate-180" : ""}`}
                  />
                </button>
                {mobileExpanded === link.label && (
                  <div className="ml-4 mb-1 space-y-0.5 border-l-2 border-gray-100 pl-3">
                    {link.children.map((child) =>
                      child.disabled ? (
                        <span
                          key={child.href}
                          className="flex items-center justify-between px-3 py-2.5 rounded-lg opacity-45 cursor-not-allowed"
                        >
                          <span className="flex flex-col">
                            <span className="text-sm font-medium text-gray-700">{child.label}</span>
                            {child.desc && <span className="text-xs text-gray-400 mt-0.5">{child.desc}</span>}
                          </span>
                          <span className="text-[10px] font-semibold text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded ml-2 flex-shrink-0">Bientôt</span>
                        </span>
                      ) : (
                        <a
                          key={child.href}
                          href={child.href}
                          onClick={() => { setMobileOpen(false); setMobileExpanded(null); }}
                          className={`flex flex-col px-3 py-2.5 rounded-lg transition-colors ${
                            isActive(child.href)
                              ? "bg-[#4A7C59]/10"
                              : "hover:bg-gray-50"
                          }`}
                        >
                          <span className={`text-sm font-medium ${
                            isActive(child.href) ? "text-[#4A7C59] font-semibold" : "text-gray-700"
                          }`}>
                            {child.label}
                          </span>
                          {child.desc && <span className="text-xs text-gray-400 mt-0.5">{child.desc}</span>}
                        </a>
                      )
                    )}
                  </div>
                )}
              </div>
            ) : link.disabled ? (
              <span
                key={link.label}
                className="flex items-center justify-between px-3 py-3 rounded-lg text-sm font-medium text-gray-400 cursor-not-allowed opacity-45"
              >
                {link.label}
                <span className="text-[10px] font-semibold text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded">Bientôt</span>
              </span>
            ) : (
              <a
                key={link.label}
                href={link.href}
                onClick={() => setMobileOpen(false)}
                className={`flex items-center px-3 py-3 rounded-lg text-sm font-medium transition-all relative ${
                  isActive(link.href)
                    ? "text-[#4A7C59] font-semibold after:absolute after:bottom-2 after:left-3 after:right-3 after:h-0.5 after:bg-[#4A7C59] after:rounded-full"
                    : "text-gray-700 hover:bg-gray-50 hover:text-[#4A7C59]"
                }`}
              >
                {link.label}
              </a>
            )
          )}

          {/* Mobile Contact CTA */}
          <a
            href="/contact"
            onClick={() => setMobileOpen(false)}
            className="flex items-center justify-center gap-2 bg-[#4A7C59] hover:bg-[#3d6849] text-white px-4 py-3 rounded-lg text-sm font-semibold transition-all mt-4 mx-3"
          >
            Contact
          </a>
        </div>
      </div>
    </nav>
  );
}
