import { headers } from "next/headers";
import { storefrontApi } from "@/lib/api";
import { getTemplate } from "@/lib/template";
import ProductCard from "./ProductCard";

interface RelatedProductsProps {
  barcode: string;
  currency?: string;
}

export default async function RelatedProducts({
  barcode,
  currency = "EGP",
}: RelatedProductsProps) {
  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "default";

  const [relatedRes, configRes] = await Promise.all([
    storefrontApi
      .getRelatedProducts(tenantSlug, barcode)
      .catch(() => ({ products: [] })),
    storefrontApi.getConfig(tenantSlug).catch(() => null),
  ]);

  const products = relatedRes.products ?? [];
  if (products.length === 0) return null;

  const templateId = (configRes?.website as any)?.template_id ?? "default";
  const template = getTemplate(templateId);

  return (
    <section className="mt-20 pt-12 border-t border-gray-100">
      <div className="flex items-center gap-4 mb-8">
        <div>
          <h2 className="text-xl font-bold text-gray-900">You may also like</h2>
          <div className="divider-primary mt-2" />
        </div>
      </div>
      {/* Horizontal scroll on mobile, grid on desktop */}
      <div className="flex gap-4 overflow-x-auto pb-2 scrollbar-hide md:grid md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 md:overflow-visible md:pb-0">
        {products.map((product) => (
          <div
            key={product.barcode}
            className="flex-shrink-0 w-[160px] sm:w-[180px] md:w-auto"
          >
            <ProductCard
              product={product}
              currency={currency}
              template={template}
            />
          </div>
        ))}
      </div>
    </section>
  );
}
