"use client";

import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { cn } from "@/lib/utils";

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

export function SidebarNav({ items }: { items: NavItem[] }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const scope = (searchParams.get("scope") ?? "").trim().toUpperCase();
  const activeHref = items
    .filter((item) => pathname === item.href || pathname.startsWith(`${item.href}/`))
    .sort((a, b) => b.href.length - a.href.length)[0]?.href;

  return (
    <nav className="space-y-2">
      {items.map((item) => {
        const active = activeHref === item.href;
        const href = scope ? `${item.href}?scope=${encodeURIComponent(scope)}` : item.href;

        return (
          <Link
            key={item.href}
            href={href}
            className={cn(
              "group block rounded-2xl px-4 py-3 text-sm font-medium transition duration-200",
              active
                ? "bg-[linear-gradient(155deg,rgba(255,255,255,0.32)_0%,rgba(144,183,230,0.3)_100%)] text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.6),0_10px_24px_-16px_rgba(7,26,52,0.95)]"
                : "text-blue-100/95 hover:bg-white/10 hover:text-white",
            )}
          >
            <span className="flex items-center justify-between gap-3">
              <span className="flex items-center gap-2.5">
                <span
                  className={cn(
                    "h-2.5 w-2.5 rounded-full bg-[#F7993A]",
                    active
                      ? "shadow-[0_0_12px_rgba(247,153,58,0.95)]"
                      : "opacity-80 group-hover:opacity-100",
                  )}
                />
                {item.label}
              </span>
            </span>
          </Link>
        );
      })}
    </nav>
  );
}
