"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";

function buildCategoryHref(active: string[], category: string): string {
  const next = active.includes(category) ? active.filter((c) => c !== category) : [...active, category];
  return next.length > 0 ? `/blog?categories=${next.map(encodeURIComponent).join(",")}` : "/blog";
}

// Client-side navigation (not a plain <Link>) specifically so `isPending`
// can gate the chips: rapid clicks used to fire multiple concurrent RSC
// navigations with no guarantee they'd commit in the order they were
// requested, so a slower, stale navigation could land after a newer one and
// briefly show the wrong (sometimes empty) result. Disabling the chips
// while a navigation is in flight makes that ordering race impossible —
// only one navigation can ever be outstanding at a time.
export function BlogCategoryFilter({ allCategories, activeCategories }: { allCategories: string[]; activeCategories: string[] }) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  return (
    <div className="flex flex-wrap gap-2 w-full">
      {allCategories.map((category) => {
        const active = activeCategories.includes(category);
        return (
          <button
            key={category}
            type="button"
            disabled={isPending}
            onClick={() => startTransition(() => router.push(buildCategoryHref(activeCategories, category)))}
            className={`inline-flex items-center px-3 py-1.5 rounded-full text-body-sm font-semibold whitespace-nowrap border transition-colors disabled:opacity-60 disabled:pointer-events-none ${
              active
                ? "bg-brand border-brand text-text-primary"
                : "bg-bg-muted border-border text-text-muted hover:border-brand hover:text-brand"
            }`}
          >
            {category}
          </button>
        );
      })}
    </div>
  );
}
