"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { NavIcon } from "@/components/nav-icon";
import { cn } from "@/lib/utils";

function isActive(pathname: string, href: string): boolean {
  // Strip query/fragment from href before matching.
  const cleaned = href.split("#")[0]?.split("?")[0] ?? href;
  if (cleaned === "/") return pathname === "/" || pathname.startsWith("/d/");
  return pathname === cleaned || pathname.startsWith(cleaned + "/");
}

interface Props {
  href: string;
  icon: string;
  label: string;
  className?: string;
  iconClassName?: string;
  variant?: "sidebar" | "bottom";
}

export function NavLink({
  href,
  icon,
  label,
  className,
  iconClassName,
  variant = "sidebar",
}: Props) {
  const pathname = usePathname() ?? "";
  const active = isActive(pathname, href);

  if (variant === "bottom") {
    return (
      <Link href={href} aria-current={active ? "page" : undefined} className={className}>
        <NavIcon name={icon} className={cn("size-5", iconClassName)} />
        <span>{label}</span>
      </Link>
    );
  }

  return (
    <Link
      href={href}
      aria-current={active ? "page" : undefined}
      className={cn("nav-item", className)}
      title={label}
    >
      <NavIcon name={icon} className={cn("size-4", iconClassName)} />
      <span className="nav-label">{label}</span>
    </Link>
  );
}
