"use client";

import Image from "next/image";

export default function ProductDetails({ productItem }) {
  if (!productItem) {
    return (
      <section className="product-details-simple fix section-padding">
        <div className="container">
          <p className="text-center text-danger">Product not found.</p>
        </div>
      </section>
    );
  }

  const groupedImages = [];
  for (let i = 0; i < productItem.images.length; i += 2) {
    groupedImages.push(productItem.images.slice(i, i + 2));
  }

  return (
    <section className="product-details-simple fix section-padding">
      <div className="container">
        <div className="row g-4">
          <div className="col-12">
            <div className="single-product-post">
              <div
                className="post-featured-thumb bg-cover rounded"
                style={{
                  backgroundImage: `url(${productItem.bigImage})`,
                  height: "400px",
                  backgroundSize: "cover",
                  backgroundPosition: "center",
                  borderRadius: "12px",
                  marginBottom: "30px",
                }}
              />

              <h2 className="product-title mb-3">{productItem.title}</h2>

              <div
                className="post-description product-description"
                dangerouslySetInnerHTML={{ __html: productItem.description }}
              />

              {groupedImages.map((imagePair, index) => (
                <div className="row mt-5 mb-5" key={index}>
                  {imagePair.map((imgSrc, subIndex) => (
                    <div
                      className={`${
                        subIndex === 0 ? "col-lg-6" : "col-lg-6 col-md-12"
                      } mt-2`}
                      key={subIndex}
                    >
                      <div className="details-image">
                        <Image
                          src={imgSrc}
                          width={633}
                          height={460}
                          alt={`Product Image ${index * 2 + subIndex + 1}`}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
