import { useLayout } from "@/context/hooks/useLayout";
import { useProduct } from "@/context/helpers/product";
import { useRouter } from "next/router";
import { useEffect, useMemo } from "react";
import ProductDetailsSkeleton from "@/features/product/skeletons/ProductDetailsSkeleton";
import ProductDescriptionSkeleton from "@/features/product/skeletons/ProductDescriptionSkeleton";
import RelatedProductsSkeleton from "@/features/product/skeletons/RelatedProductsSkeleton";
import { getLayoutProduct } from "@/layouts/registry";

/**
 * Layout-aware Product Page wrapper
 *
 * Loads the correct product page based on the active layout. The layout →
 * component mapping lives in the layout registry (src/layouts/registry.js),
 * which lazy-loads only the active layout's code.
 */
export default function ProductPage() {
  const { layout } = useLayout();
  const { getProductDetails, isLoading } = useProduct();
  const router = useRouter();

  // Fetch product details when route changes
  useEffect(() => {
    if (router.query.id) {
      const getDetails = async () => {
        await getProductDetails(router.query.id);
      };
      getDetails();
    }
  }, [router.query.id, getProductDetails]);

  const ProductPageComponent = useMemo(
    () => getLayoutProduct(layout),
    [layout]
  );

  // Show loading skeleton while data is loading
  if (isLoading) {
    return (
      <main className="flex flex-col gap-8 mx-auto px-5 xl:px-0 py-8 max-w-7xl container">
        <ProductDetailsSkeleton />
        <ProductDescriptionSkeleton />
        <RelatedProductsSkeleton />
      </main>
    );
  }

  // Render the layout-specific Product Page
  return <ProductPageComponent />;
}
