import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { ProductCard } from '@/components/product-card';
import { getCategoryBySlug, searchProducts } from '@/lib/api';
import { absoluteUrl, metadataTitle } from '@/lib/seo';
import { breadcrumbJsonLd, JsonLdScript } from '@/lib/seo/json-ld';

export const revalidate = 300;

type PageProps = Readonly<{ params: Promise<{ slug: string }> }>;

export function generateStaticParams() {
  return [];
}

async function loadCategory(slug: string) {
  try {
    return await getCategoryBySlug(slug);
  } catch {
    notFound();
  }
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const category = await loadCategory(slug);
  const title = category.seoTitle ?? category.name;
  const description =
    category.seoDescription ?? `Productos de la categoría ${category.name} en mercadodevida.`;

  return {
    title: metadataTitle(title),
    description,
    alternates: { canonical: absoluteUrl(category.url) },
    openGraph: {
      title,
      description,
      url: absoluteUrl(category.url),
      type: 'website',
    },
  };
}

export default async function CategoryPage({ params }: PageProps) {
  const { slug } = await params;
  const category = await loadCategory(slug);
  const products = await searchProducts({
    categorySlug: category.slug,
    limit: 24,
    offset: 0,
  }).catch(() => []);
  const breadcrumbs = breadcrumbJsonLd([
    { name: 'Inicio', path: '/' },
    { name: category.name, path: category.url },
  ]);

  return (
    <div className="mx-auto max-w-6xl px-6 py-12">
      <JsonLdScript data={breadcrumbs} />
      <nav className="text-sm text-stone-600" aria-label="Breadcrumb">
        <a href="/" className="hover:text-emerald-800">
          Inicio
        </a>{' '}
        / <span>{category.name}</span>
      </nav>

      <header className="mt-8 max-w-3xl space-y-4">
        <p className="text-sm font-semibold uppercase tracking-[0.25em] text-emerald-700">
          Categoría
        </p>
        <h1 className="text-4xl font-bold tracking-tight text-emerald-950 md:text-5xl">
          {category.emoji ? `${category.emoji} ${category.name}` : category.name}
        </h1>
        <p className="text-lg leading-8 text-stone-700">
          {category.seoDescription ?? 'Descubrí productos seleccionados dentro de esta categoría.'}
        </p>
      </header>

      <section className="mt-10" aria-label={`Productos de ${category.name}`}>
        {products.length > 0 ? (
          <div className="grid gap-5 md:grid-cols-3">
            {products.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        ) : (
          <div className="rounded-3xl bg-emerald-50 p-6 text-emerald-950">
            Todavía no hay productos visibles para esta categoría.
          </div>
        )}
      </section>
    </div>
  );
}
