import Image from 'next/image'
import productbg from '../public/productbg.webp'
import ProductCard from '@/components/ProductCard'

async function getData(id) {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/public/content/index/${id}`)
 
  if (!res.ok) {
    throw new Error('Failed to fetch data')
  }
 
  return res.json()
}

export default async function Products({ lang }){
    const data = await getData(lang === 'fa' ? 1 : 2);
    
    // Add safety checks for data structure
    if (!data || typeof data !== 'object') {
        console.error('Products: Invalid data received from API');
        return null;
    }
    
    return(
        <div className="relative flex flex-col">
            <Image alt="" src={productbg} className="absolute top-0 w-full object-cover h-[500px] md:h-96 lg:h-fit"/>
            <div className="flex flex-col z-10 text-white font-[5] pt-8 lg:pt-16 w-full items-center ">
                <span>{data.productsSuper?.[0]?.body || ''}</span>
                <span className="font-[4] text-3xl lg:text-4xl pt-4">{data.productsHead?.[0]?.body || ''}</span>
                <p className="max-w-4xl text-center pt-6 px-8 text-sm sm:text-md lg:pt-12">{data.productsDesc?.[0]?.body || ''}</p>
            </div> 
            <div className="flex justify-center z-10 py-16 overflow-x-scroll">
                {
                    data.productImages?.map((image, index) => (
                        <ProductCard key={index} image={image?.body || ''} desc={data.productDescs?.[index]?.body || ''} />
                    )) || []
                }
            </div>
        </div>
    )
}
