"use client";

import { useState } from "react";
import { ResourceCard } from "@/components/resources/ResourceCard";
import type { ResourceCategory, ResourceSlug, ResourceSummary } from "@/content/types";
import { cn } from "@/lib/cn";

interface ResourceIndexProps {
  resources: ResourceSummary[];
  readTimes: Partial<Record<ResourceSlug, number>>;
}

/** Category filter. Every card is server-rendered, so the full list works without JavaScript. */
export function ResourceIndex({ resources, readTimes }: ResourceIndexProps) {
  const categories = Array.from(new Set(resources.map((resource) => resource.category)));
  const [active, setActive] = useState<ResourceCategory | "All">("All");
  const visible = active === "All" ? resources : resources.filter((resource) => resource.category === active);

  return (
    <>
      <div role="group" aria-label="Filter resources by topic" className="flex flex-wrap gap-2">
        {(["All", ...categories] as const).map((category) => (
          <button
            key={category}
            type="button"
            aria-pressed={active === category}
            onClick={() => setActive(category)}
            className={cn(
              "inline-flex min-h-11 items-center rounded-md border px-4 text-[0.9375rem] transition-colors",
              active === category ? "border-ink bg-ink text-paper" : "border-line-strong/60 hover:border-ink",
            )}
          >
            {category}
          </button>
        ))}
      </div>
      <p className="sr-only" aria-live="polite">
        {`${visible.length} resources shown`}
      </p>
      <ul className="mt-10 grid gap-5 md:grid-cols-2 xl:grid-cols-3">
        {visible.map((resource) => (
          <li key={resource.slug}>
            <ResourceCard resource={resource} readMinutes={readTimes[resource.slug]} headingLevel="h2" />
          </li>
        ))}
      </ul>
    </>
  );
}
