"use client";

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

type LinkProps = ComponentProps<typeof Link>;

export interface NavLinkProps extends Omit<LinkProps, "href"> {
  href: string;
  exact?: boolean;
  className?: string;
  activeClassName?: string;
  inactiveClassName?: string;
  children: React.ReactNode;
}

function isActive(pathname: string, href: string, exact?: boolean): boolean {
  if (!pathname || !href) return false;
  if (exact) return pathname === href;
  if (href === "/") return pathname === "/";
  return pathname === href || pathname.startsWith(`${href}/`);
}

export function NavLink({
  href,
  exact,
  className,
  activeClassName = "text-primary",
  inactiveClassName = "text-foreground/80 hover:text-foreground",
  children,
  ...rest
}: NavLinkProps) {
  const pathname = usePathname();
  const active = isActive(pathname, href, exact);

  const cn = [
    "inline-flex items-center text-sm font-medium transition-colors",
    active ? activeClassName : inactiveClassName,
    className ?? "",
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <Link
      href={href}
      className={cn}
      aria-current={active ? "page" : undefined}
      {...rest}
    >
      {children}
    </Link>
  );
}