"use client";

import { Fragment } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { FOCUS_RING_CLASSES } from "@/components/ui/styles";
import { cn } from "@/lib/utils";

function isActive(pathname: string, href: string, basePath: string) {
  if (href === basePath) return pathname === basePath;
  return pathname === href || pathname.startsWith(`${href}/`);
}

export function TabNav({
  tabs,
  basePath,
}: {
  tabs: readonly { href: string; label: string; group?: string }[];
  basePath: string;
}) {
  const pathname = usePathname();

  return (
    <nav className="mt-6 flex flex-wrap items-center gap-2 border-b border-kolabora-neutral-dark/10 pb-2">
      {tabs.map((tab, i) => {
        const active = isActive(pathname, tab.href, basePath);
        // Chunk long tab bars (Admin has 13) into scannable clusters instead
        // of one flat wall of labels — Miller's Law / Hick's Law.
        const showDivider = i > 0 && tab.group !== undefined && tab.group !== tabs[i - 1].group;
        return (
          <Fragment key={tab.href}>
            {showDivider && <span aria-hidden="true" className="h-4 w-px bg-kolabora-neutral-dark/15" />}
            <Link
              href={tab.href}
              aria-current={active ? "page" : undefined}
              className={cn(
                "rounded-full px-4 py-1.5 text-sm font-medium",
                FOCUS_RING_CLASSES,
                active
                  ? "bg-kolabora-primary/10 text-kolabora-primary"
                  : "text-kolabora-neutral-dark/70 hover:bg-kolabora-neutral-dark/5 hover:text-kolabora-neutral-dark",
              )}
            >
              {tab.label}
            </Link>
          </Fragment>
        );
      })}
    </nav>
  );
}
