"use client";

// The sidebar. A client component for one reason: the current path is the only
// thing here that cannot be known on the server, and without it every nav item
// looks identical no matter which page you are on.
//
// It sets aria-current="page", which is both the accessible signal and what the
// selected styling in globals.css keys off, so the two cannot disagree.

import Link from "next/link";
import { usePathname } from "next/navigation";

export type NavItem = { href: string; label: string };

function isCurrent(pathname: string, href: string) {
  // /admin is a prefix of every other admin route, so it only matches exactly.
  // Everything else matches its subtree, so /admin/inventory/series/<id> still
  // highlights Inventory.
  if (href === "/admin") return pathname === "/admin";
  return pathname === href || pathname.startsWith(href + "/");
}

export function AdminNav({ items }: { items: NavItem[] }) {
  const pathname = usePathname();

  return (
    <ul className="space-y-1 text-sm">
      {items.map((item) => {
        const current = isCurrent(pathname, item.href);
        return (
          <li key={item.href}>
            <Link
              href={item.href}
              aria-current={current ? "page" : undefined}
              className="admin-nav-button block px-3 py-2 font-medium"
            >
              {item.label}
            </Link>
          </li>
        );
      })}
    </ul>
  );
}
