import { fetchQuery } from "convex/nextjs";
import { notFound } from "next/navigation";
import { api } from "../../../../../../convex/_generated/api";
import { ProductDetailHeroSection } from "./ProductDetailHeroSection";
import { ProductDetailTabsSection } from "./ProductDetailTabsSection";
import { ProductDetailDescriptionSection } from "./ProductDetailDescriptionSection";
import { ProductDetailAttributesSection } from "./ProductDetailAttributesSection";
import { ProductDetailReviewsPanel } from "../reviews/ProductDetailReviewsPanel";
import { ProductDetailErrorState } from "../state/ProductDetailErrorState";
import type { ProductDetailProduct } from "@/lib/product-detail/types";

type ProductDetailSectionsWrapperProps = {
  category: string;
  subCategory: string;
  slug: string;
};

/**
 * Async server component: fetches product by slug once and renders
 * Hero + Tabs (Description, Details, Reviews).
 * Reviews load independently via a nested Suspense boundary.
 */
export async function ProductDetailSectionsWrapper({
  category,
  subCategory,
  slug,
}: ProductDetailSectionsWrapperProps) {
  let product;
  try {
    product = await fetchQuery(api.products.getBySlug, { slug });
  } catch {
    return (
      <ProductDetailErrorState message="Unable to load product details. Please try again." />
    );
  }
  if (!product) notFound();

  return (
    <>
      <ProductDetailHeroSection
        product={product as ProductDetailProduct}
        category={category}
        subCategory={subCategory}
      />
      <ProductDetailTabsSection
        descriptionContent={
          <ProductDetailDescriptionSection description={product.description} />
        }
        detailsContent={
          <ProductDetailAttributesSection attributes={product.attributes} />
        }
        reviewsContent={
          <ProductDetailReviewsPanel
            productId={product._id}
            initialRating={product.averageRating}
            initialReviewCount={product.reviewCount}
          />
        }
        reviewCount={product.reviewCount}
      />
    </>
  );
}
