// import React, { useState, useEffect } from "react";
// import {
//   FiHome,
//   FiBox,
//   FiUsers,
//   FiShoppingCart,
//   FiLogOut,
//   FiX,
//   FiChevronDown,
//   FiChevronUp,
// } from "react-icons/fi";
// import { Link } from "react-router-dom";
// import { useLocation, useNavigate } from "react-router-dom";
// import ConfirmModal from "../common/ConfirmModal";

// const Sidebar = ({
//   isCollapsed,
//   // toggleSidebar,
//   mobileOpen,
//   toggleMobileSidebar,
// }) => {
//   const location = useLocation();
//   const navigate = useNavigate();

//   // Separate dropdown states
//   const [productsOpen, setProductsOpen] = useState(false);
//   const [categoriesOpen, setCategoriesOpen] = useState(false);
//   const [logoutOpen, setLogoutOpen] = useState(false);

//   // Auto-open dropdown when route matches
//   useEffect(() => {
//     if (location.pathname.startsWith("/products")) setProductsOpen(true);
//     if (location.pathname.startsWith("/categories")) setCategoriesOpen(true);
//   }, [location.pathname]);

//   const menuItems = [
//     { name: "Dashboard", icon: <FiHome />, path: "/dashboard" },
//     { name: "Orders", icon: <FiShoppingCart />, path: "/orders" },
//     {
//       name: "Products",
//       icon: <FiBox />,
//       subMenu: [
//         { name: "Product List", path: "/products" },
//         { name: "Add Product", path: "/products/add" },
//       ],
//       state: productsOpen,
//       setState: setProductsOpen,
//     },
//     { name: "Users", icon: <FiUsers />, path: "/users" },
//     // { name: "Report", icon: <FiUsers />, path: "/reports" },
//     {
//       name: "Categories",
//       icon: <FiBox />,
//       subMenu: [
//         { name: "Category List", path: "/categories" },
//         { name: "Add Category", path: "/categories/add" },
//       ],
//       state: categoriesOpen,
//       setState: setCategoriesOpen,
//     },
//      { name: "Returns", icon: <FiBox />, path: "/returns" },
//      { name: "Coupons", icon: <FiBox />, path: "/coupons" },
//   ];

//   const isActive = (path) => location.pathname === path;

//   const handleLogout = () => {
//     setLogoutOpen(false);
//     navigate("/login");
//   };

//   const activeClass = `
//     ${isCollapsed ? "w-12 justify-center" : "w-[193px] justify-start"}
//     bg-[#4880FF] text-white rounded-[6px] h-[46px] flex items-center gap-[10px] px-4 py-[12px]
//     shadow-md transition-all duration-200
//   `;

//   const normalClass = `
//     ${isCollapsed ? "w-12 justify-center" : "w-[193px] justify-start"}
//     text-gray-700 hover:bg-[#4880FF]/10 hover:text-[#4880FF] rounded-[6px] h-[46px]
//     flex items-center gap-[10px] px-4 py-[12px] transition-all duration-200
//   `;

//   return (
//     <>
//       {/* Mobile overlay */}
//       <div
//         className={`fixed inset-0 bg-black/40 z-40 md:hidden transition-opacity ${
//           mobileOpen ? "opacity-100 visible" : "opacity-0 invisible"
//         }`}
//         onClick={toggleMobileSidebar}
//       ></div>

//       {/* Sidebar */}
//       <div
//         className={`fixed inset-y-0 left-0 z-50 bg-white shadow-lg transform transition-all duration-300
//           ${
//             mobileOpen ? "translate-x-0" : "-translate-x-full"
//           } md:translate-x-0 md:static
//           ${isCollapsed ? "w-20" : "w-64"} flex flex-col justify-between
//         `}
//       >
//         {/* Logo & Hamburger */}
//         <div className="flex items-center m-3 px-4 py-4 border-gray-200">
//           <h2
//             className={`absolute left-1/2 -translate-x-1/2 font-bold text-xl text-[#4880FF] ${
//               isCollapsed ? "hidden" : "block"
//             }`}
//           >
//             Vaishnavi
//           </h2>

//           <div className="flex items-center gap-2">
//             <button
//               className="md:hidden p-2 rounded-md hover:bg-gray-100 transition"
//               onClick={toggleMobileSidebar}
//             >
//               <FiX className="text-[#4880FF]" />
//             </button>
//           </div>
//         </div>

//         {/* Menu */}
//         <nav className="mt-2 flex-1 px-2 space-y-2 flex flex-col items-center">
//           {menuItems.map((item, index) => {
//             if (item.subMenu) {
//               const parentActive = item.subMenu.some((sub) =>
//                 isActive(sub.path)
//               );

//               return (
//                 <div key={index}>
//                   <button
//                     className={`flex items-center justify-between px-4 py-[12px] rounded-[6px] transition-all duration-200
//                       ${isCollapsed ? "w-12" : "w-[193px]"}
//                       ${
//                         item.state || parentActive
//                           ? "bg-[#4880FF] text-white shadow-md"
//                           : "text-gray-700 hover:bg-[#4880FF]/10 hover:text-[#4880FF]"
//                       }
//                     `}
//                     onClick={() => item.setState(!item.state)}
//                   >
//                     <div className="flex items-center gap-[10px]">
//                       {item.icon}
//                       <span
//                         className={`${
//                           isCollapsed ? "hidden" : "block font-medium"
//                         }`}
//                       >
//                         {item.name}
//                       </span>
//                     </div>
//                     {!isCollapsed &&
//                       (item.state ? <FiChevronUp /> : <FiChevronDown />)}
//                   </button>

//                   {/* Submenu */}
//                   {item.state && !isCollapsed && (
//                     <div className="ml-6 mt-2 flex flex-col gap-2">
//                       {/* {item.subMenu.map((sub) => (
//                         <Link
//                           to={sub.path}
//                           className={
//                             isActive(sub.path) ? activeClass : normalClass
//                           }
//                         >
//                           {sub.name}
//                         </Link>
//                       ))} */}
//                       {item.subMenu.map((sub) => (
//                         <Link
//                           key={sub.id} // 👈 ADD THIS
//                           to={sub.path}
//                           className={
//                             isActive(sub.path) ? activeClass : normalClass
//                           }
//                         >
//                           {sub.name}
//                         </Link>
//                       ))}
//                     </div>
//                   )}
//                 </div>
//               );
//             }

//             return (
//               <Link
//                 key={index}
//                 to={item.path}
//                 className={isActive(item.path) ? activeClass : normalClass}
//               >
//                 {item.icon}
//                 <span
//                   className={`${isCollapsed ? "hidden" : "block font-medium"}`}
//                 >
//                   {item.name}
//                 </span>
//               </Link>
//             );
//           })}
//         </nav>

//         {/* Logout */}
//         <div className="px-4 mb-6 flex justify-center">
//           <button
//             className={`flex items-center justify-center gap-[10px]
//               ${isCollapsed ? "w-12" : "w-[193px]"}
//               h-[46px] px-4 py-[12px] rounded-[6px]
//               bg-red-100 text-red-600 hover:bg-red-200 transition-all`}
//             onClick={() => setLogoutOpen(true)}
//           >
//             <FiLogOut />
//             {!isCollapsed && <span className="font-medium">Logout</span>}
//           </button>
//         </div>
//       </div>

//       {/* Confirm Modal */}
//       <ConfirmModal
//         isOpen={logoutOpen}
//         title="Logout"
//         message="Are you sure you want to logout?"
//         onCancel={() => setLogoutOpen(false)}
//         onConfirm={handleLogout}
//       />
//     </>
//   );
// };

// export default Sidebar;




import React, { useState, useEffect } from "react";
import {
  FiHome, FiBox, FiUsers, FiShoppingCart, FiLogOut, FiX,
  FiChevronDown, FiTag, FiRefreshCw, FiPercent, FiGrid,
} from "react-icons/fi";
import { Link, useLocation, useNavigate } from "react-router-dom";
import ConfirmModal from "../common/ConfirmModal";

const NAV_ITEMS = [
  { name: "Dashboard",  icon: FiHome,         path: "/dashboard" },
  { name: "Orders",     icon: FiShoppingCart, path: "/orders" },
  {
    name: "Products", icon: FiBox,
    subMenu: [
      { name: "Product List", path: "/products" },
      { name: "Add Product",  path: "/products/add" },
    ],
  },
  { name: "Users",    icon: FiUsers,    path: "/users" },
  {
    name: "Categories", icon: FiGrid,
    subMenu: [
      { name: "Category List", path: "/categories" },
      { name: "Add Category",  path: "/categories/add" },
    ],
  },
   { name: "Report", icon: FiRefreshCw, path: "/reports" },
  { name: "Returns", icon: FiRefreshCw, path: "/returns" },
  { name: "Coupons", icon: FiPercent,   path: "/coupons" },
];

const Sidebar = ({ isCollapsed, mobileOpen, toggleMobileSidebar }) => {
  const location  = useLocation();
  const navigate  = useNavigate();
  const [openMenus,   setOpenMenus]   = useState({});
  const [logoutOpen,  setLogoutOpen]  = useState(false);

  // Auto-expand parent when child route is active
  useEffect(() => {
    NAV_ITEMS.forEach((item) => {
      if (item.subMenu?.some((s) => location.pathname.startsWith(s.path))) {
        setOpenMenus((prev) => ({ ...prev, [item.name]: true }));
      }
    });
  }, [location.pathname]);

  const toggle = (name) =>
    setOpenMenus((prev) => ({ ...prev, [name]: !prev[name] }));

  const isActive     = (path) => location.pathname === path;
  const isParentActive = (item) =>
    item.subMenu?.some((s) => location.pathname.startsWith(s.path));

  return (
    <>
      {/* Mobile overlay */}
      <div
        className={`fixed inset-0 bg-black/50 backdrop-blur-sm z-40 md:hidden transition-opacity duration-300 ${
          mobileOpen ? "opacity-100 visible" : "opacity-0 invisible pointer-events-none"
        }`}
        onClick={toggleMobileSidebar}
      />

      {/* Sidebar */}
      <aside
        className={`
          fixed inset-y-0 left-0 z-50 flex flex-col
          bg-[#0f172a] text-white
          transform transition-all duration-300 ease-in-out
          ${mobileOpen ? "translate-x-0" : "-translate-x-full"}
          md:translate-x-0 md:static
          ${isCollapsed ? "w-[72px]" : "w-64"}
        `}
      >
        {/* ── Logo ─────────────────────────────────────── */}
        <div className={`flex items-center h-16 px-4 border-b border-white/10 flex-shrink-0 ${isCollapsed ? "justify-center" : "justify-between"}`}>
          {!isCollapsed && (
            <div className="flex items-center gap-2">
              <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-violet-600 flex items-center justify-center shadow-lg">
                <span className="text-white font-black text-sm">V</span>
              </div>
              <span className="font-bold text-lg tracking-tight text-white">
                Vaishnavi
              </span>
            </div>
          )}
          {isCollapsed && (
            <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-blue-500 to-violet-600 flex items-center justify-center shadow-lg">
              <span className="text-white font-black text-sm">V</span>
            </div>
          )}
          <button
            className="md:hidden p-1.5 rounded-lg hover:bg-white/10 transition"
            onClick={toggleMobileSidebar}
          >
            <FiX size={18} />
          </button>
        </div>

        {/* ── Navigation ───────────────────────────────── */}
        <nav className="flex-1 overflow-y-auto py-4 px-2 space-y-0.5 scrollbar-thin scrollbar-thumb-white/10">
          {!isCollapsed && (
            <p className="text-[10px] font-semibold uppercase tracking-widest text-white/30 px-3 pb-2 pt-1">
              Main Menu
            </p>
          )}

          {NAV_ITEMS.map((item) => {
            const Icon        = item.icon;
            const hasSubMenu  = !!item.subMenu;
            const isOpen      = openMenus[item.name];
            const parentActive = isParentActive(item);

            if (hasSubMenu) {
              return (
                <div key={item.name}>
                  <button
                    onClick={() => toggle(item.name)}
                    className={`
                      w-full flex items-center gap-3 px-3 py-2.5 rounded-xl
                      text-sm font-medium transition-all duration-150 group
                      ${isOpen || parentActive
                        ? "bg-white/10 text-white"
                        : "text-white/60 hover:bg-white/5 hover:text-white"
                      }
                      ${isCollapsed ? "justify-center" : "justify-between"}
                    `}
                  >
                    <div className="flex items-center gap-3 min-w-0">
                      <span className={`flex-shrink-0 transition-colors ${isOpen || parentActive ? "text-blue-400" : "text-white/40 group-hover:text-white/70"}`}>
                        <Icon size={18} />
                      </span>
                      {!isCollapsed && <span className="truncate">{item.name}</span>}
                    </div>
                    {!isCollapsed && (
                      <FiChevronDown
                        size={14}
                        className={`flex-shrink-0 text-white/40 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
                      />
                    )}
                  </button>

                  {/* Submenu */}
                  {isOpen && !isCollapsed && (
                    <div className="ml-4 mt-0.5 mb-1 pl-3 border-l border-white/10 space-y-0.5">
                      {item.subMenu.map((sub) => (
                        <Link
                          key={sub.path}
                          to={sub.path}
                          className={`
                            flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-all duration-150
                            ${isActive(sub.path)
                              ? "bg-blue-600 text-white font-medium shadow-md shadow-blue-900/40"
                              : "text-white/50 hover:bg-white/5 hover:text-white"
                            }
                          `}
                        >
                          <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${isActive(sub.path) ? "bg-white" : "bg-white/30"}`} />
                          {sub.name}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              );
            }

            // Regular link
            const active = isActive(item.path);
            return (
              <Link
                key={item.path}
                to={item.path}
                className={`
                  flex items-center gap-3 px-3 py-2.5 rounded-xl
                  text-sm font-medium transition-all duration-150 group
                  ${isCollapsed ? "justify-center" : ""}
                  ${active
                    ? "bg-blue-600 text-white shadow-md shadow-blue-900/40"
                    : "text-white/60 hover:bg-white/5 hover:text-white"
                  }
                `}
              >
                <span className={`flex-shrink-0 transition-colors ${active ? "text-white" : "text-white/40 group-hover:text-white/70"}`}>
                  <Icon size={18} />
                </span>
                {!isCollapsed && <span className="truncate">{item.name}</span>}

                {/* Active indicator dot when collapsed */}
                {isCollapsed && active && (
                  <span className="absolute right-1 w-1.5 h-1.5 rounded-full bg-blue-400" />
                )}
              </Link>
            );
          })}
        </nav>

        {/* ── User + Logout ─────────────────────────────── */}
        <div className="flex-shrink-0 p-3 border-t border-white/10 space-y-2">
          {!isCollapsed && (
            <div className="flex items-center gap-3 px-3 py-2.5 rounded-xl bg-white/5">
              <div className="w-8 h-8 rounded-full bg-gradient-to-br from-blue-400 to-violet-500 flex items-center justify-center text-xs font-bold flex-shrink-0">
                A
              </div>
              <div className="min-w-0">
                <p className="text-sm font-medium text-white truncate">Admin</p>
                <p className="text-xs text-white/40 truncate">Super Admin</p>
              </div>
            </div>
          )}

          <button
            onClick={() => setLogoutOpen(true)}
            className={`
              w-full flex items-center gap-3 px-3 py-2.5 rounded-xl
              text-sm font-medium text-white/60
              hover:bg-red-500/15 hover:text-red-400
              transition-all duration-150 group
              ${isCollapsed ? "justify-center" : ""}
            `}
          >
            <FiLogOut size={18} className="flex-shrink-0 group-hover:text-red-400 transition-colors" />
            {!isCollapsed && <span>Logout</span>}
          </button>
        </div>
      </aside>

      <ConfirmModal
        isOpen={logoutOpen}
        title="Logout"
        message="Are you sure you want to logout?"
        onCancel={() => setLogoutOpen(false)}
        onConfirm={() => { setLogoutOpen(false); navigate("/login"); }}
      />
    </>
  );
};

export default Sidebar;