import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { ProductCard } from '@/components/product-card';
import { getBrandBySlug, 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 loadBrand(slug: string) {
  try {
    return await getBrandBySlug(slug);
  } catch {
    notFound();
  }
}

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

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

export default async function BrandPage({ params }: PageProps) {
  const { slug } = await params;
  const brand = await loadBrand(slug);
  const products = await searchProducts({ brandSlug: brand.slug, limit: 24, offset: 0 }).catch(
    () => [],
  );
  const breadcrumbs = breadcrumbJsonLd([
    { name: 'Inicio', path: '/' },
    { name: brand.name, path: brand.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>{brand.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">Marca</p>
        <h1 className="text-4xl font-bold tracking-tight text-emerald-950 md:text-5xl">
          {brand.name}
        </h1>
        <p className="text-lg leading-8 text-stone-700">
          {brand.seoDescription ?? 'Productos seleccionados de esta marca.'}
        </p>
      </header>

      <section className="mt-10" aria-label={`Productos de ${brand.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 marca.
          </div>
        )}
      </section>
    </div>
  );
}
