"use client";

import httpClient from "@/request/api";
import { endPoints } from "@/request/links";
import { useQuery } from "@tanstack/react-query";
import { useCategory } from "@/store/useCategory";
import Card from "./card";

export function MainSubCategory() {
  const category = useCategory((state) => state.category);
  const { data, isLoading, error } = useQuery({
    queryKey: ["subCategory"],
    queryFn: () => httpClient(endPoints.subCategory.byId(category.id)),
    select: (data) => data?.data?.results,
  });

  if (isLoading) {
    return (
      <div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5">
        {[1, 2, 3].map((i) => (
          <div key={i} className="h-96 bg-gray-800 animate-pulse rounded-2xl" />
        ))}
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center text-red-500 py-10">
        Ma'lumotlarni yuklashda xatolik yuz berdi
      </div>
    );
  }

  if (!data || data.length === 0) {
    return (
      <div className="text-center text-gray-400 py-10">
        Mahsulotlar topilmadi
      </div>
    );
  }
  return (
    <div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5">
      {data.map((item: any) => (
        <Card
          key={item.id} // ✅ index o'rniga id ishlatish
          title={item.name}
          image={item.image}
          slug={item.slug}
          id={item.id}
          category={item.category}
        />
      ))}
    </div>
  );
}
