"use client";

import { useEffect, useState } from "react";
import { ProductCard } from "@/components/product/ProductCard";
import { PageShell } from "@/components/layout/PageShell";
import { Reveal } from "@/components/motion/Reveal";
import { Button } from "@/components/ui/Button";
import { useWishlist } from "@/context/wishlist-context";
import type { Product } from "@/data/types";

export default function WishlistPage() {
  const { ids } = useWishlist();
  const [catalog, setCatalog] = useState<Product[]>([]);

  useEffect(() => {
    void fetch("/api/products")
      .then((res) => res.json())
      .then((data: { products?: Product[] }) => setCatalog(data.products ?? []));
  }, []);

  const list = catalog.filter((product) => ids.includes(product.id));

  return (
    <PageShell
      crumbs={[{ label: "Home", href: "/" }, { label: "Wishlist" }]}
      eyebrow="Saved"
      title="Wishlist"
      description="Keep products you love and return when you're ready."
    >
      {ids.length === 0 ? (
        <Reveal className="border border-border bg-[var(--paper)] p-8">
          <p className="text-muted">No saved items yet.</p>
          <Button href="/shop" className="mt-6">
            Browse products
          </Button>
        </Reveal>
      ) : list.length === 0 ? (
        <p className="text-sm text-muted">Loading saved items…</p>
      ) : (
        <div className="product-grid">
          {list.map((product, index) => (
            <ProductCard key={product.id} product={product} index={index} />
          ))}
        </div>
      )}
    </PageShell>
  );
}
