"use client";

import { useEffect, useState } from "react";
import dynamic from "next/dynamic";

import { useT } from "@/context/I18nContext"; 

const DynamicShopFullwidth = dynamic(
     () => import("@/components/shop/ShopFullwidth"),
     { ssr: false }
);

import PageHeading from "@/components/common/PageHeading";

export default function ToateProdusele() {
     const [productsData, setProductsData] = useState([]);
     const [totalCount, setTotalCount] = useState(0);
     const [loading, setLoading] = useState(true);

     const { t } = useT(); 

     useEffect(() => {
          async function fetchProducts() {
               setLoading(true);
               try {

                    const response = await fetch(`/api/products/reduced`);
                    const data = await response.json();

                    if (data.products) {
                         setProductsData(data.products);
                         setTotalCount(data.totalCount);
                    }
               } catch (error) {
                    console.error("Error loading products:", error);
               } finally {
                    setLoading(false);
               }
          }

          fetchProducts();
     }, []);

     if (loading) {
          return (
               <div style={{ 
                    minHeight: "400px", 
                    display: "flex", 
                    alignItems: "center", 
                    justifyContent: "center" 
               }}>
                    <p>Se încarcă produsele...</p>
               </div>
          );
     }

     return (
          <>
               <PageHeading title={t("reduceri_heading")} />
               <DynamicShopFullwidth productsData={productsData} />
          </>
     );
}