﻿// react
import React from "react";
// third-party
import classNames from "classnames";
import { useRouter } from "next/router";
// application
import AppLink from "./AppLink";

interface Props {
  isOpen: boolean;
}

function Sidebar({ isOpen }: Props) {
  const router = useRouter();

    const menuItems = [
    {
      title: "Dashboard",
      icon: "fas fa-tachometer-alt",
      href: "/admin",
      exact: true,
    },
    {
      title: "Sección Principal",
      icon: "fas fa-image",
      href: "/hero",
      routes: ["/hero", "/footer"],
    },
    {
      title: "Inventario",
      icon: "fas fa-warehouse",
      href: "/productos",
      routes: ["/productos", "/brands", "/models", "/ofertas"],
    },
    {
      title: "Sobre Nosotros",
      icon: "fas fa-building",
      href: "/services",
      routes: ["/services", "/sucursal", "/about-us"],
    },
    {
      title: "Envíos y Pagos",
      icon: "fas fa-money-check-alt",
      href: "/payment",
      routes: ["/payment", "/bank-payments"],
    },
    {
      title: "Gestión de Datos",
      icon: "fas fa-database",
      href: "/reportes",
      routes: ["/reportes", "/sincronizar-excel"],
    },
    {
      title: "Configuración",
      icon: "fas fa-cog",
      href: "/configuracion",
      routes: ["/configuracion", "/admin/registro"],
    },
  ];

  const isActive = (item: (typeof menuItems)[number]) => {
    // El panel vive bajo /admin (monolito); las rutas del menú no lo incluyen.
    const normalize = (r: string) =>
      r === '/' || r.startsWith('/admin') ? r : `/admin${r}`;

    // Si el ítem agrupa varias rutas, se marca con cualquiera de ellas
    if (item.routes && item.routes.length > 0) {
      return item.routes.some((route) => {
        const rr = normalize(route);
        return router.pathname === rr || router.pathname.startsWith(`${rr}/`);
      });
    }
    if (item.exact) {
      return router.pathname === normalize(item.href);
    }
    return router.pathname.startsWith(normalize(item.href));
  };

  return (
    <aside
      className={classNames("sidebar", {
        "sidebar--open": isOpen,
        "sidebar--closed": !isOpen,
      })}
    >
      <div className="sidebar__header">
        <div className="sidebar__logo">
          <h2>MONTICARS</h2>
          <span className="sidebar__subtitle">Admin Panel</span>
        </div>
      </div>
      <nav className="sidebar__nav">
        <ul className="sidebar__menu">
          {menuItems.map((item) => (
            <li key={item.href} className="sidebar__menu-item">
              <AppLink
                href={item.href}
                className={classNames("sidebar__menu-link", {
                  "sidebar__menu-link--active": isActive(item),
                })}
              >
                <i className={item.icon} />
                <span>{item.title}</span>
              </AppLink>
            </li>
          ))}
        </ul>
      </nav>
    </aside>
  );
}

export default Sidebar;
