import Link from 'next/link';
import Image from 'next/image';
import type { Metadata } from 'next';
import { fetchBrandBySlug, fetchProducts, formatPrice } from '@/lib/api';
import { formatRichText } from '@/lib/format-rich-text';

// Brand data comes from the live backend; resolve it at request time.
export const dynamic = 'force-dynamic';

interface Props {
  params: Promise<{ slug: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const brand = await fetchBrandBySlug(slug);
  if (!brand) return { title: 'Marca no encontrada' };
  return {
    title: brand.seoTitle ?? brand.name,
    description: brand.seoDescription ?? `Productos ${brand.name} en mercadodevida.`,
  };
}

export default async function BrandPage({ params }: Props) {
  const { slug } = await params;
  const [brand, products] = await Promise.all([
    fetchBrandBySlug(slug),
    fetchProducts({ brandSlug: slug, limit: 24 }),
  ]);

  if (!brand) {
    return (
      <div className="max-w-7xl mx-auto px-4 py-16 text-center">
        <h1 className="text-2xl font-bold text-gray-900 mb-4">Marca no encontrada</h1>
        <Link href="/brands" className="text-[#70ad47] font-medium hover:underline">
          Ver todas las marcas →
        </Link>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Breadcrumb */}
      <nav className="mb-6" aria-label="Breadcrumb">
        <ol className="flex items-center gap-2 text-sm text-gray-500">
          <li><Link href="/" className="hover:text-[#70ad47]">Inicio</Link></li>
          <li><span className="text-gray-300">/</span></li>
          <li><Link href="/brands" className="hover:text-[#70ad47]">Marcas</Link></li>
          <li><span className="text-gray-300">/</span></li>
          <li className="text-gray-900 font-medium">{brand.name}</li>
        </ol>
      </nav>

      {/* Header */}
      <div className="mb-8 flex items-center gap-4">
        <div className="w-16 h-16 bg-[#70ad47]/10 rounded-2xl flex items-center justify-center">
          <span className="text-2xl font-bold text-[#70ad47]">
            {brand.name.slice(0, 2).toUpperCase()}
          </span>
        </div>
        <div>
          <h1 className="text-3xl font-bold text-gray-900" style={{ fontFamily: 'var(--font-heading)' }}>
            {brand.name}
          </h1>
          {brand.seoDescription && (
            <p className="mt-1 text-gray-600">{brand.seoDescription}</p>
          )}
          <p className="mt-1 text-sm text-gray-500">{products.length} producto{products.length !== 1 ? 's' : ''}</p>
        </div>
      </div>

      {/* Products */}
      {products.length === 0 ? (
        <div className="py-16 text-center">
          <p className="text-gray-500">No hay productos de esta marca todavía.</p>
          <Link href="/brands" className="text-[#70ad47] font-medium hover:underline mt-4 inline-block">
            Ver otras marcas →
          </Link>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 justify-items-center">
          {products.map((product) => (
            <Link key={product.id} href={`/products/${product.slug}`} className="group block">
              <div className="bg-gray-50 rounded-xl overflow-hidden border border-gray-100 hover:border-[#70ad47] transition-all hover:shadow-md">
                <div className="relative aspect-square w-full bg-white flex items-center justify-center overflow-hidden">
                  {product.images?.[0] ? (
                    <Image src={product.images[0].url} alt={product.name} fill className="object-contain" sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw" />
                  ) : (
                    <span className="text-5xl">🌿</span>
                  )}
                </div>
                <div className="p-4">
                  <h3 className="font-semibold text-gray-900 group-hover:text-[#70ad47] transition-colors line-clamp-2 text-sm">
                    {product.name}
                  </h3>
                  {product.description && (
                    <div
                      className="text-gray-500 text-xs mt-1 line-clamp-2 rich-text prose prose-xs max-w-none"
                      dangerouslySetInnerHTML={{ __html: formatRichText(product.description) }}
                    />
                  )}
                  <div className="mt-3 pr-2">
                    <span className="text-lg font-bold text-[#70ad47]">{formatPrice(0)}</span>
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
