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

// The catalog is served by the live backend; never fetch it during build.
export const dynamic = 'force-dynamic';

export const metadata: Metadata = {
  title: 'Productos — mercadodevida',
  description: 'Todos los productos naturales y orgánicos.',
};

function findCatName(cats: ReturnType<typeof flattenCats>, id: string): string | undefined {
  return cats.find((c) => c.id === id)?.name;
}

function flattenCats(cats: Awaited<ReturnType<typeof fetchCategories>>): Array<{ id: string; name: string; slug: string }> {
  const flat: Array<{ id: string; name: string; slug: string }> = [];
  function walk(c: typeof cats[number]) {
    flat.push({ id: c.id, name: c.name, slug: c.slug });
    if (c.children?.length) c.children.forEach(walk);
  }
  cats.forEach(walk);
  return flat;
}

export default async function ProductsPage() {
  const [products, brands, categories] = await Promise.all([
    fetchProducts({ limit: 24 }),
    fetchBrands(),
    fetchCategories(),
  ]);
  const flatCats = flattenCats(categories);

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900" style={{ fontFamily: 'var(--font-heading)' }}>
          Todos los productos
        </h1>
        <p className="mt-2 text-gray-600">{products.length} productos disponibles</p>
        {/* Plantilla CMS editable desde Admin → CMS (slug: products) */}
        <CmsBlock slug="products" />
      </div>

      {products.length === 0 ? (
        <p className="text-gray-500 text-center py-16">No hay productos disponibles.</p>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {products.map((product) => {
            const brand = brands.find((b) => b.id === product.brandId);
            return (
              <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">
                  {/* Square aspect ratio so cards line up in a 4-col grid; the
                      image is letterboxed with `object-contain` so non-square
                      sources still display without distortion. */}
                  <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">
                    {brand && (
                      <p className="text-xs text-[#E76F51] font-medium uppercase tracking-wide mb-1">{brand.name}</p>
                    )}
                    <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>
  );
}
