"use client";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React, { useState, useEffect } from "react";
import {
  faFacebookF,
  faTwitter,
  faInstagram,
  faYoutube,
} from "@fortawesome/free-brands-svg-icons";
import {
  faChevronDown,
  faChevronRight,
} from "@fortawesome/free-solid-svg-icons";
import Image from "next/image";
import { AnimatePresence, motion } from "framer-motion";
import Link from "next/link";

const springTransition = {
  type: "spring",
  stiffness: 260,
  damping: 20,
};

const smoothTransition = {
  duration: 0.5,
  ease: [0.4, 0, 0.2, 1], // cubic-bezier easeInOut
};

const animationVariants = {
  open: {
    opacity: 1,
    maxHeight: 500, // a value greater than expected content height
    transition: {
      duration: 0.5,
      ease: "easeInOut",
    },
  },
  closed: {
    opacity: 0,
    maxHeight: 0,
    transition: {
      duration: 0.3,
      ease: "easeInOut",
    },
  },
};

const topLine = {
  closed: { rotate: 0, y: 0 },
  open: { rotate: 45, y: 6 },
};
const midLine = {
  closed: { opacity: 1, scaleX: 1 },
  open: { opacity: 0, scaleX: 0 },
};
const botLine = {
  closed: { rotate: 0, y: 0 },
  open: { rotate: -45, y: -6 },
};

const sidebar = {
  open: {
    clipPath: "inset(0% 0% 0% 0%)",
    transition: {
      type: "spring",
      stiffness: 80,
      damping: 25,
      restDelta: 0.001,
    },
  },
  closed: {
    clipPath: "inset(0% 0% 100% 0%)",
    transition: {
      type: "spring",
      stiffness: 300,
      damping: 35,
      delay: 0.15,
    },
  },
};

const Navbar = ({ navMenu = { what_we_do: [] } }) => {
  const newItem = {
    name: "Working Areas",
    key: "/area",
    items: [],
    linked: true,
  };

  // Merge immutably
  const updatedNavMenu = {
    ...navMenu,
    what_we_do: [...navMenu.what_we_do, newItem],
  };

  const menu = [
    {
      label: "Who we are",
      key: "who_we_are",
      children: [
        {
          label: "Executive Committee",
          key: "/executives",
          children: [],
          linked: true,
        },
        {
          label: "Core Management",
          key: "/core",
          children: [],
          linked: true,
        },
        {
          label: "Achievements",
          key: "/achievements",
          children: [],
          linked: true,
        },
        {
          label: "Affiliation/Partnership",
          key: "/partnership",
          children: [],
          linked: true,
        },
      ],
      linked: false,
    },
    {
      label: "What we do",
      key: "what_we_do",
      children: updatedNavMenu?.what_we_do?.map((item, i) => ({
        label: item?.name,
        key: item.key ?? `/what_we_do/${i}`,
        children: item?.items?.map((child, j) => ({
          label: child?.name,
          key: `/objectives/details/${child.id}`,
          children: [], // you can map deeper if needed
        })),
        linked: item.linked ?? false,
      })),

      linked: false,
    },
    {
      label: "News & events",
      key: "/news_events",
      children: [
        {
          label: "News Archieve",
          key: "/news",
          children: [],
          linked: true,
        },
        {
          label: "Media Coverage",
          key: "/media",
          children: [],
          linked: true,
        },
        {
          label: "videos",
          key: "/videos",
          children: [],
          linked: true,
        },
      ],

      linked: false,
    },
    {
      label: "Publications",
      key: "/publications",
      children: [
        {
          label: "Success Stories",
          key: "/success",
          children: [],
          linked: true,
        },
        {
          label: "Mamata Barta",
          key: "/barta",
          children: [],
          linked: true,
        },
        {
          label: "Annual Reports",
          key: "/annual",
          children: [],
          linked: true,
        },
      ],
      linked: false,
    },
    {
      label: "Gallery",
      key: "/gallery",
      children: [],
      linked: true,
    },
    {
      label: "Contact",
      key: "/contact",
      children: [],
      linked: true,
    },
    {
      label: "Career",
      key: "/career",
      children: [],
      linked: true,
    },
  ];

  const [hoveredMenu, setHoveredMenu] = useState(null);
  const [scrolled, setScrolled] = useState(false);
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState(null);
  const [activeSubDropdown, setActiveSubDropdown] = useState(null);

  const toggle = () => setIsMenuOpen((prev) => !prev);
  const toggleDropdown = (key) =>
    setActiveDropdown((prev) => (prev === key ? null : key));
  const toggleSubDropdown = (key) =>
    setActiveSubDropdown((prev) => (prev === key ? null : key));

  useEffect(() => {
    function handleScroll() {
      if (window.scrollY > 40) {
        setScrolled(true);
      } else {
        setScrolled(false);
      }
    }
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return (
    <>
      {/* Top bar */}
      {/* <div className="bg-[#0F6939] w-full py-2 px-3 sm:px-4 lg:px-[initial]">
        <div className="container m-auto flex items-center justify-between">
          <div className="text-white">Since 1983</div>
          <div className="flex gap-4">
            <FontAwesomeIcon icon={faFacebookF} color="white" />
            <FontAwesomeIcon icon={faTwitter} color="white" />
            <FontAwesomeIcon icon={faInstagram} color="white" />
            <FontAwesomeIcon icon={faYoutube} color="white" />
          </div>
        </div>
      </div> */}

      {/* Navbar */}
      <div
        className={`w-full fixed top-0 z-[99999]
          transition-all duration-500 ease-out main-nav shadow-m px-3 sm:px-4 lg:px-[initial]
          ${scrolled ? "py-1" : "py-4"}`}
      >
        <div className="container m-auto flex items-center justify-between h-full w-full">
          {/* Logo */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.5 }}
          >
            <Link href="/">
              <Image
                src={`${process.env.NEXT_PUBLIC_API_URL}/images_cus/logo/logo.png`}
                alt="Mamata BD"
                width={70}
                height={70}
                className="transition-transform w-[70px] h-auto duration-500"
              />
            </Link>
          </motion.div>

          {/* Desktop Menu */}
          <ul className="lg:flex gap-1 hidden">
            {menu.map(({ label, key, children, linked }) => (
              <li key={key} className="relative group text-[17px]  text-wrap">
                <Link
                  className=" cursor-pointer p-2 flex gap-1"
                  onMouseEnter={() => setHoveredMenu(key)}
                  onMouseLeave={() => setHoveredMenu(null)}
                  disabled={children?.length === 0}
                  href={linked ? key : "#"}
                >
                  <div>{label}</div>
                  {children?.length > 0 && (
                    <span className="transition-transform duration-500">
                      <FontAwesomeIcon
                        icon={faChevronDown}
                        className={`transition-transform duration-500 ${
                          hoveredMenu === key ? "rotate-180" : ""
                        }`}
                      />
                    </span>
                  )}
                </Link>

                {children?.length > 0 && (
                  <ul
                    className="absolute rounded left-0 mt-0 w-40  bg-white text-black shadow-2xl px-2
                      opacity-0 translate-y-[-10px] group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-500 pointer-events-none group-hover:pointer-events-auto z-[9999999]"
                  >
                    {children.map((child, i) => (
                      <li
                        key={i}
                        className="py-[8px] text-[14px] hover:text-[#0F6939] border-b border-b-[#e5f3e7ee] cursor-pointer"
                        onMouseEnter={() => setHoveredMenu(child.key)}
                        onMouseLeave={() => setHoveredMenu(null)}
                      >
                        <div className="flex">
                          <Link href={child.linked ? child.key : "#"}  className="block w-full h-full">
                            <div className="w-[90%]">{child.label}</div>
                          </Link>

                          {child.children?.length > 0 && (
                            <div className="w-[10%] flex justify-center items-center relative">
                              <span className="transition-transform duration-500 ">
                                <FontAwesomeIcon
                                  icon={faChevronRight}
                                  className={`transition-transform duration-500 ${
                                    hoveredMenu === child.key ? "rotate-90" : ""
                                  }`}
                                />
                              </span>

                              <ul
                                onMouseEnter={() => setHoveredMenu(child.key)}
                                onMouseLeave={() => setHoveredMenu(null)}
                                className={`absolute rounded left-[-20px] top-[32px] mt-0 w-40 bg-white text-black shadow-2xl px-2
      opacity-0 translate-y-[-10px]
      ${
        hoveredMenu === child.key
          ? "opacity-100 translate-y-0 pointer-events-auto"
          : "opacity-0 pointer-events-none"
      }
      transition-all duration-500 z-[9999999]`}
                              >
                                {child.children.map((subChild, i) => (
                                  <li
                                    key={i}
                                    className="py-[8px] text-[14px] hover:text-[#0F6939] border-b border-b-[#e5f3e7ee] cursor-pointer"
                                  >
                                    <Link href={subChild.key} className="block w-full h-full">
                                      {subChild.label}
                                    </Link>
                                  </li>
                                ))}
                              </ul>
                            </div>
                          )}
                        </div>
                      </li>
                    ))}
                  </ul>
                )}
              </li>
            ))}
          </ul>

          {/* Mobile Hamburger */}
          <div className="lg:hidden py-2">
            <button
              onClick={toggle}
              className="relative z-50 flex flex-col justify-between w-8 h-6 cursor-pointer"
            >
              <motion.span
                className="block h-1 w-full rounded bg-gray-800 origin-center"
                variants={topLine}
                animate={isMenuOpen ? "open" : "closed"}
                transition={springTransition}
              />
              <motion.span
                className="block h-1 w-full rounded bg-gray-800 origin-center"
                variants={midLine}
                animate={isMenuOpen ? "open" : "closed"}
                transition={{ duration: 0.3, ease: "easeInOut" }}
              />
              <motion.span
                className="block h-1 w-full rounded bg-gray-800 origin-center"
                variants={botLine}
                animate={isMenuOpen ? "open" : "closed"}
                transition={springTransition}
              />
            </button>
          </div>
        </div>
      </div>

      <AnimatePresence>
        {isMenuOpen && (
          <motion.aside
            initial="closed"
            animate="open"
            exit="closed"
            variants={sidebar}
            className="left-0 w-full fixed top-[104px] lg:hidden bg-white shadow-xl z-[999999] overflow-y-auto border-t-[#917373] py-8 px-4 sm:px-5 lg:px-[initial] sidebar-scroll"
          >
            <motion.ul
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 10 }}
              transition={{ duration: 0.35, ease: "easeOut" }}
              className="flex flex-col gap-2 text-sm container m-auto "
            >
              {menu.map((item, i) => (
                <li key={i} className="flex flex-col  ">
                  <Link
                    className="flex justify-between items-center py-1 text-[20px] text-left"
                    onClick={() => toggleDropdown(item.key)}
                    href={item.linked ? item.key : "#"}
                  >
                    <span>{item.label}</span>

                    {item.children?.length > 0 && (
                      <FontAwesomeIcon
                        icon={faChevronDown}
                        className={`transition-transform duration-300 ${
                          activeDropdown === item.key ? "rotate-180" : ""
                        }`}
                      />
                    )}
                  </Link>
                  {item.children?.length > 0 && (
                    <ul
                      className={`overflow-hidden transition-all duration-500 ease-in-out
    ${
      activeDropdown === item.key
        ? "h-auto opacity-100 py-3"
        : "max-h-0 opacity-0"
    }
  `}
                    >
                      {item.children.map((sub, i) => (
                        <li
                          key={i}
                          className="py-1 pl-4 last:border-none hover:text-[#0F6939] text-[18px] cursor-pointer"
                        >
                          <div
                            className="flex"
                            onClick={() => toggleSubDropdown(sub.key)}
                          >
                            <Link href={sub.linked ? sub.key : "#"}  className="block w-full h-full">
                              <div className="w-[90%]">{sub.label}</div>
                            </Link>
                            <div className="w-[10%] flex justify-center items-center">
                              {sub.children?.length > 0 && (
                                <FontAwesomeIcon
                                  icon={faChevronRight}
                                  className={`transition-transform duration-300 ${
                                    activeSubDropdown === sub.key
                                      ? "rotate-90"
                                      : ""
                                  }`}
                                />
                              )}
                            </div>
                          </div>

                          <ul
                            className={`overflow-hidden transition-all duration-500 ease-in-out 
    ${
      activeSubDropdown === sub.key
        ? "h-auto opacity-100 py-3"
        : "max-h-0 opacity-0"
    }
  `}
                          >
                            {sub.children.map((subItem, i) => (
                              
                                <li key={i} className="py-2 pl-4 last:border-none hover:text-[#0F6939] cursor-pointer">
                                  <div className="flex">
                                    <Link  href={subItem.key} className="block w-full h-full">
                                    <div className="w-[90%]">
                                      {subItem.label}
                                    </div>
                                    </Link>
                                  </div>
                                </li>
                            
                            ))}
                          </ul>
                        </li>
                      ))}
                    </ul>
                  )}
                </li>
              ))}
            </motion.ul>
          </motion.aside>
        )}
      </AnimatePresence>
    </>
  );
};

export default Navbar;
