import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";

const Categories = () => {
  const navigate = useNavigate();
  const API_URL = import.meta.env.VITE_API_URL;

  const [categories, setCategories] = useState([]);

  useEffect(() => {
    fetchCategories();
  }, []);

  const fetchCategories = async () => {
    try {
      const res = await axios.get(`${API_URL}/api/category/allcategory`);

      const list = res.data.categories || res.data;

      if (!Array.isArray(list)) {
        console.warn("Unexpected API shape", res.data);
        return;
      }

      const formatted = list.map((cat) => ({
        id: cat._id,
        slug: cat.slug,                 // ✅ IMPORTANT
        name: cat.name,
        image: cat.image?.startsWith("http")
          ? cat.image
          : `${API_URL}${cat.image}`,
      }));

      setCategories(formatted);
    } catch (err) {
      console.error("Error loading categories:", err);
    }
  };

  return (
    <div className="w-full bg-white py-5">
      <div className="flex flex-row gap-8 px-8 sm:px-14 overflow-x-auto lg:overflow-x-visible flex-nowrap scrollbar-hide">

        {categories.map((cat) => (
          <div
            key={cat.id}
            onClick={() => navigate(`/category/${cat.slug}/${cat.id}`)}  // ✅ FIXED
            className="flex flex-col items-center text-center cursor-pointer min-w-[80px] lg:min-w-0"
          >
            <img
              src={cat.image}
              alt={cat.name}
              className="w-14 h-14 sm:w-16 sm:h-16 md:w-20 md:h-20 rounded-lg object-cover"
            />
            <p className="mt-1 text-[10px] sm:text-sm md:text-base text-gray-800 leading-tight truncate w-full">
              {cat.name}
            </p>
          </div>
        ))}

      </div>
    </div>
  );
};

export default Categories;
