"use client";
import React, { useEffect, useState } from "react";
import CategoryBox from "./CategoryBox";
import ProductCart from "./ProductCart";

export default function Category() {
  const [width, setWidth] = useState(0);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const categories = Array.from({ length: 12 }).map((_, i) => ({
    src: "/image/test/Untitle6d.jpg",
    title: `Category ${i + 1}`,
    Classification: Math.floor(Math.random() * 20),
    product: Math.floor(Math.random() * 2000),
  }));

  const getProductCount = () => {
    if (width > 1691) return 20;
    if (width > 1444) return 16;
    if (width > 1210) return 12;
    if (width > 1198) return 9;
    return 6;
  };

  const products = Array.from({ length: getProductCount() }).map((_, i) => ({
    image: "/image/test/Untitle6d.jpg",
    title: `Product ${i + 1} with long title for test`,
    price: 145000,
    discountedPrice: 80000,
    monetaryUnit: "تومان",
    score: 4 + Math.random(),
    heartStyle: "text-black",
  }));

  return (
    <div className="px-4 no-scrollbar justify-center   w-full max-lg:overflow-auto mx-auto flex flex-col lg:flex-row gap-8">
      {/* Categories */}
      {products.length === 0 ? (
        <div className="overflow-x-auto no-scrollbar py-3">
          <div
            className="inline-flex flex-col gap-4 max-lg:gap-2"
            style={{ height: "480px" }}
          >
            {/* ارتفاع 3 ردیف × 160px */}
            {categories.map((cat, i) => (
              <div
                key={i}
                className="flex-shrink-0 flex justify-center items-center h-[160px] w-[150px] lg:w-full"
              >
                <CategoryBox
                  {...cat}
                  style="hover:scale-105 transition-transform duration-300 shadow hover:shadow-lg"
                />
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="flex lg:flex-col lg:overflow-visible gap-4 py-3 max-lg:gap-0">
          {categories.map((cat, i) => (
            <div
              key={i}
              className="flex-shrink-0 flex items-center justify-center min-w-[150px] lg:min-w-full"
            >
              <CategoryBox
                {...cat}
                style="hover:scale-105 transition-transform duration-300 shadow hover:shadow-lg"
              />
            </div>
          ))}
        </div>
      )}

      {/* Products Grid */}
      <div className="hidden lg:flex gap-[7px] flex-row max-w-[1300px] overflow-hidden flex-wrap">
        {products.map((prod, i) => (
          <ProductCart
            key={i}
            {...prod}
            style="hover:scale-105 transition-transform duration-300 shadow hover:shadow-lg"
          />
        ))}
      </div>
    </div>
  );
}
