"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { CurrentUser } from "./user-context";

interface NavItem {
  href: string;
  label: string;
  icon: string;
  superAdminOnly?: boolean;
}

const NAV: NavItem[] = [
  { href: "/dashboard", label: "Tableau de bord", icon: "🏠" },
  { href: "/agenda", label: "Agenda", icon: "📅" },
  { href: "/mail", label: "Boîte mail", icon: "✉️" },
  { href: "/whatsapp", label: "WhatsApp", icon: "💬", superAdminOnly: true },
  { href: "/drive", label: "Documents", icon: "🗂️" },
  { href: "/tracking", label: "Localisation", icon: "📍" },
  { href: "/settings", label: "Paramètres", icon: "⚙️", superAdminOnly: true },
  { href: "/profile", label: "Mon profil", icon: "👤" },
  { href: "/admin/users", label: "Gestion des comptes", icon: "👥", superAdminOnly: true },
  { href: "/admin/config", label: "Configuration", icon: "🔧", superAdminOnly: true },
  { href: "/admin/logs", label: "Journal de connexions", icon: "📜", superAdminOnly: true },
];

export function Sidebar({
  user,
  open,
  onClose,
}: {
  user: CurrentUser;
  open: boolean;
  onClose: () => void;
}) {
  const pathname = usePathname();
  const router = useRouter();

  const items = NAV.filter((i) => !i.superAdminOnly || user.role === "super_admin");

  async function logout() {
    await fetch("/backend/auth/logout", { method: "POST", credentials: "include" });
    router.replace("/");
  }

  return (
    <>
      {/* Voile sombre sur mobile quand le tiroir est ouvert */}
      {open && (
        <div
          className="fixed inset-0 z-40 bg-black/40 md:hidden"
          onClick={onClose}
          aria-hidden
        />
      )}

      <aside
        className={[
          "fixed inset-y-0 left-0 z-50 flex w-64 flex-col border-r border-zinc-200 bg-white",
          "transition-transform duration-200 dark:border-zinc-800 dark:bg-zinc-950",
          open ? "translate-x-0" : "-translate-x-full",
          // Desktop : barre collée en haut, hauteur d'écran (reste visible quand la page défile)
          "md:sticky md:top-0 md:z-auto md:h-screen md:translate-x-0",
        ].join(" ")}
      >
        <div className="flex h-16 items-center justify-end px-5">
          <button
            onClick={onClose}
            className="rounded-md p-1 text-zinc-500 hover:bg-zinc-100 md:hidden dark:hover:bg-zinc-900"
            aria-label="Fermer le menu"
          >
            ✕
          </button>
        </div>

        <nav className="flex flex-1 flex-col gap-1 overflow-y-auto px-3">
          {items.map((item) => {
            const active = pathname === item.href;
            return (
              <Link
                key={item.href}
                href={item.href}
                onClick={onClose}
                className={[
                  "flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
                  active
                    ? "bg-zinc-100 text-black dark:bg-zinc-900 dark:text-zinc-50"
                    : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-900",
                ].join(" ")}
              >
                <span aria-hidden>{item.icon}</span>
                {item.label}
              </Link>
            );
          })}
        </nav>

        <div className="border-t border-zinc-200 p-3 dark:border-zinc-800">
          <div className="px-2 pb-2 text-xs text-zinc-500">
            {user.displayName || user.username}
          </div>
          <button
            onClick={logout}
            className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-900"
          >
            <span aria-hidden>↩</span>
            Se déconnecter
          </button>
        </div>
      </aside>
    </>
  );
}
