"use client";

import { useEffect, useState } from "react";
import type { Product } from "./payload";

export type { Product };

// Products now live in Payload's "products" collection (tenant
// einfach-produktiv), not a hardcoded catalog — see lib/payload.ts's
// getProducts() for the server-side fetch. Client components (CartContent,
// RelatedProducts) can't call that directly the way a Server Component
// can, so this hook fetches the same-origin /api/products proxy instead,
// with a tiny module-level cache so /cart's two consumers (CartContent +
// RelatedProducts) share one request instead of firing it twice.
let cache: Product[] | null = null;
let inflight: Promise<Product[]> | null = null;

async function fetchProducts(): Promise<Product[]> {
  if (cache) return cache;
  if (!inflight) {
    inflight = fetch("/api/products")
      .then((res) => (res.ok ? res.json() : []))
      .then((data: Product[]) => {
        cache = data;
        return data;
      })
      .catch(() => []);
  }
  return inflight;
}

// Starts empty (SSR-safe — matches useCart()'s pattern of a safe default
// that fills in after a client-only effect, see lib/cart.ts) and updates
// once the fetch resolves.
export function useProducts(): Product[] {
  const [products, setProducts] = useState<Product[]>(cache ?? []);

  useEffect(() => {
    let cancelled = false;
    fetchProducts().then((data) => {
      if (!cancelled) setProducts(data);
    });
    return () => {
      cancelled = true;
    };
  }, []);

  return products;
}
