import { getCategories } from "@/lib/api";
import Link from "next/link";

export const dynamic = "force-dynamic";

export default async function CategoriesPage() {
  let categories;
  try {
    const response = await getCategories();
    categories = response.items;
  } catch {
    return (
      <div className="space-y-6">
        <h1 className="text-3xl font-bold">Categories</h1>
        <p className="text-[var(--muted-foreground)]">
          Unable to load categories. Please try again later.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <h1 className="text-3xl font-bold">Categories</h1>
      <p className="text-[var(--muted-foreground)]">
        Browse questions by data structure or algorithm category.
      </p>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {categories.map((category) => (
          <Link
            key={category.id}
            href={`/questions?category=${category.slug}`}
            className="p-6 rounded-lg border border-[var(--border)] bg-[var(--card)] hover:border-[var(--primary)] transition-colors"
          >
            <div className="flex items-center justify-between mb-2">
              <h3 className="font-semibold">{category.name}</h3>
              <span className="text-sm text-[var(--muted-foreground)]">
                {category.question_count} questions
              </span>
            </div>
            {category.description && (
              <p className="text-sm text-[var(--muted-foreground)]">
                {category.description}
              </p>
            )}
          </Link>
        ))}
      </div>
    </div>
  );
}
