import { fetchQuery } from "convex/nextjs";
import { api } from "../../../../../../convex/_generated/api";
import type { Id } from "../../../../../../convex/_generated/dataModel";
import { ShopProductGrid } from "@/components/shop/ShopProductGrid";
import { PRODUCT_DETAIL_SECTION_IDS } from "@/lib/product-detail/constants";
import {
  enrichedProductToCardProps,
  type EnrichedProduct,
} from "@/lib/shop/productMapper";

const RELATED_LIMIT = 8;

type ProductDetailRelatedSectionProps = {
  categoryId: Id<"categories">;
  slug: string;
};

/**
 * Related products from the same category (excluding current product).
 * Product links use the product object as single source of truth.
 */
export async function ProductDetailRelatedSection({
  categoryId,
  slug,
}: ProductDetailRelatedSectionProps) {
  const list = await fetchQuery(api.products.listActive, {
    categoryId,
    limit: RELATED_LIMIT + 1,
  });

  const others = (list ?? [])
    .filter((p: { slug: string }) => p.slug !== slug)
    .slice(0, RELATED_LIMIT) as EnrichedProduct[];

  if (others.length === 0) return null;

  const products = others.map((p) => ({
    ...enrichedProductToCardProps(p),
    id: p._id,
  }));

  return (
    <section
      id={PRODUCT_DETAIL_SECTION_IDS.related}
      aria-label="Related products"
      className="py-6 md:py-8"
    >
      <div
        className="mb-6 h-px w-full bg-[var(--separator)] md:mb-8"
        role="separator"
      />
      <h2 className="mb-4 font-[family-name:var(--font-fraunces)] text-lg font-semibold tracking-tight text-[var(--foreground)] md:mb-6 md:text-xl">
        You might also like
      </h2>
      <ShopProductGrid products={products} />
    </section>
  );
}
