"use client";

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

export function TabLink({
  href,
  children,
}: {
  href: string;
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const isActive = pathname === href;
  const [isPending, startTransition] = useTransition();

  function handleClick(e: React.MouseEvent) {
    e.preventDefault();
    if (isActive) return;
    startTransition(() => router.push(href)); // triggers route change
  }

  return (
    <button
      onClick={handleClick}
      disabled={isPending}
      className={cn(
        "px-4 py-2 text-sm font-medium border-b-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",
        isActive
          ? "border-primary text-foreground"
          : "border-transparent text-muted-foreground hover:text-foreground hover:border-primary"
      )}
    >
      {isPending ? (
        <span className="flex items-center gap-2">
          <span className="animate-spin h-3 w-3 border-2 border-primary border-t-transparent rounded-full" />
          {children}
        </span>
      ) : (
        children
      )}
    </button>
  );
}
