import Image from 'next/image'
import productbg from '../public/productbg.webp'
import ProductCard from '@/components/ProductCard'
import { productImages } from '@/lib/localImages'

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 id="products" className="relative flex scroll-mt-28 flex-col overflow-hidden">
            <Image alt="" src={productbg} className="absolute top-0 h-full min-h-[560px] w-full object-cover"/>
            <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="z-10 flex gap-4 overflow-x-auto px-6 py-16 sm:px-10 lg:flex-wrap lg:justify-center lg:gap-6 lg:px-28">
                {
                    productImages.map((image, index) => (
                        <ProductCard key={image} image={image} desc={data.productDescs?.[index]?.body || ''} />
                    ))
                }
            </div>
        </div>
    )
}
