"use client";

import { RevealGroup, RevealItem } from "../../../components/Reveal";
import { formatDate } from "../../../lib/format";
import { ProductCard } from "../../../components/ProductCard";
import { useWishlist } from "../../../lib/useWishlist";
import type { Product } from "../../../lib/payload";

// Client Component so removing an item (WishlistButton toggling it off)
// disappears from this grid immediately — the server-rendered initial
// list alone doesn't react to that client-side toggle at all (the parent
// page.tsx is a Server Component, its render is fixed at request time).
// useWishlist()'s live `items` is the actual source of truth for which
// products are still wishlisted; `initialProducts` only supplies the
// display data (name/image/price) for whatever numericIds are currently
// wishlisted, since the wishlist itself only stores product ids.
export function MerklisteGrid({
  initialProducts,
  defaultTaxRate,
  kleinunternehmer,
}: {
  initialProducts: Product[];
  defaultTaxRate: number;
  kleinunternehmer: boolean;
}) {
  const { items } = useWishlist();
  // Preserve the wishlist's own order (most-recently-added-first, via
  // `items`) rather than initialProducts' own order. Zipped with the
  // originating wishlist item (not just the product) so purchasedAt stays
  // attached — the earlier `.map().filter()` chain that only kept the
  // product lost that association.
  const productsByNumericId = new Map(initialProducts.map((p) => [p.numericId, p]));
  const visibleEntries = items
    .map((item) => ({ item, product: productsByNumericId.get(item.productId) }))
    .filter((entry): entry is { item: (typeof items)[number]; product: Product } => Boolean(entry.product));

  if (visibleEntries.length === 0) {
    return <p className="text-body text-text-muted">Du hast noch keine Produkte gemerkt.</p>;
  }

  return (
    // No items-start, and grid-auto-rows + subgrid on each RevealItem —
    // see ProductGrid.tsx's own comment on why both are needed for
    // ProductCard's internal rows (price, etc.) to actually line up
    // across cards, not just overall card height.
    <RevealGroup className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 [grid-auto-rows:auto_auto_auto_auto_auto_minmax(0,1fr)] w-full">
      {visibleEntries.map(({ item, product }) => (
        <RevealItem key={`${product.id}-${item.variant}`} className="grid [grid-template-rows:subgrid] [grid-row:span_6]">
          <ProductCard
            product={product}
            defaultTaxRate={defaultTaxRate}
            kleinunternehmer={kleinunternehmer}
            wishlistEnabled
            // Already-purchased takes precedence over the default
            // Ausverkauft/discount badge — a customer who already bought
            // this doesn't need a restock notice, they need to know they
            // already own it (and can still remove it manually via
            // WishlistButton — this is a status note, not an
            // auto-removal, see feedback discussion this implements).
            // undefined (not purchased) falls through to ProductCard's
            // own default Ausverkauft/discount badge.
            topLeftBadge={
              item.purchasedAt ? (
                <span className="absolute top-3 left-3 rounded-full bg-success-subtle px-2.5 py-1 text-label font-bold text-success">
                  Gekauft am {formatDate(item.purchasedAt)}
                </span>
              ) : undefined
            }
          />
        </RevealItem>
      ))}
    </RevealGroup>
  );
}
