import Link from "next/link";
import Image from "next/image";
import { getProducts, getShippingSettings } from "../../lib/payload";
import { formatPrice, discountPercent } from "../../lib/format";
import { RevealGroup, RevealItem } from "../../components/Reveal";
import { AddToCartInlineButton } from "../../components/AddToCartInlineButton";

// Server Component — fetches straight from Payload (getProducts(), ISR
// cached 60s) rather than going through the client-side useProducts()
// hook /cart's components need; this grid doesn't react to cart state, so
// there's no reason to pay for a client fetch when a server one already
// gives faster first paint and no loading flash.

export async function ProductGrid() {
  const [allProducts, shipping] = await Promise.all([getProducts(), getShippingSettings()]);
  const products = allProducts.filter((p) => p.active);

  if (products.length === 0) {
    return (
      <section className="w-full bg-bg-base flex flex-col items-center pb-16 md:pb-20 px-[var(--layout-padding-x)]">
        <p className="text-body text-text-muted">Aktuell keine Produkte verfügbar.</p>
      </section>
    );
  }

  return (
    <section className="w-full bg-bg-base flex flex-col pb-16 md:pb-20 px-[var(--layout-padding-x)]">
      <RevealGroup className="grid grid-cols-1 md:grid-cols-12 gap-6 md:gap-[var(--layout-grid-gap)] w-full">
        {products.map((product) => {
          const discount = discountPercent(product.price, product.compareAtPrice);
          return (
          <RevealItem
            key={product.id}
            className="group md:col-span-3 bg-bg-base border border-border rounded-md overflow-hidden flex flex-col h-full transition-transform duration-300 hover:-translate-y-1"
          >
            <div className="relative w-full aspect-[276/210] overflow-hidden">
              <Image
                src={product.image}
                alt={product.name}
                fill
                sizes="(min-width: 768px) 25vw, 100vw"
                className="object-cover transition-transform duration-500 group-hover:scale-105"
              />
              {discount !== null && (
                <span className="absolute top-3 left-3 rounded-full bg-brand px-2.5 py-1 text-label font-bold text-text-primary">
                  -{discount}%
                </span>
              )}
            </div>
            <div className="flex flex-col gap-4 items-start px-5 pb-5 pt-4 w-full flex-1">
              <p
                className="font-semibold text-h4 text-text-primary w-full"
                style={{ fontFamily: "var(--font-lora)" }}
              >
                {product.name}
              </p>
              <div className="flex flex-col gap-1 items-start">
                <p className="flex items-baseline gap-1.5">
                  {discount !== null && (
                    <span className="text-label text-text-muted line-through">{formatPrice(product.compareAtPrice!)}</span>
                  )}
                  <span className="font-bold text-h4 text-text-primary">{formatPrice(product.price)}</span>
                  <span className="text-label text-text-muted">inkl. MwSt.</span>
                </p>
                <p className="text-label text-text-muted">
                  Lieferzeit: {shipping.totalDays.min}–{shipping.totalDays.max} Werktage innerhalb Deutschlands
                </p>
              </div>
              {product.href && (
                <Link
                  href={product.href}
                  className="flex items-center gap-1 font-bold text-label text-text-primary hover:text-brand transition-colors"
                >
                  <span>Mehr erfahren</span>
                  <span aria-hidden>→</span>
                </Link>
              )}

              {/* flex-1 spacer — pins every card's button to the same Y
                  regardless of the "Mehr erfahren" line only products with
                  a detail page have (see figma-to-nextjs skill's Tools.tsx
                  equal-height lesson). */}
              <div className="flex-1" />

              <AddToCartInlineButton id={product.id} />
            </div>
          </RevealItem>
          );
        })}
      </RevealGroup>
    </section>
  );
}
