import Link from "next/link";
import Card from "./card";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getHomePageNewsCategory } from "@/store/homePageNewsCategory";


export default function CategoryCard() {
  const [data, setData] = useState();

  const { homePageNewsCategory, homePageNewsCategoryStatus } = useSelector(
    (state) => state.homePageNewsCategory
  );

  const dispatch = useDispatch();
  useEffect(() => {
    if (!homePageNewsCategoryStatus) {
      dispatch(getHomePageNewsCategory());
    }
    if (homePageNewsCategoryStatus) {
      setData(homePageNewsCategory);
    }
  }, [dispatch]);

  useEffect(() => {
    if (homePageNewsCategoryStatus) {
      setData(homePageNewsCategory);
    }
  }, [homePageNewsCategoryStatus]);


  if (!data) {
    return <></>;
  }
  return data.map((item, key) => (
    <div key={key} className="bg-white shadow-md rounded p-4 mb-6">
      <div className="flex justify-between items-center mb-2">
        <h5 className="text-xl font-semibold">{item.title}</h5>
        <Link
          title={item.title}
          className="text-lg text-gray-500"
          href={`${process.env.DETAIL_URL}category/${item.slug}`}
        >
          Tümü
        </Link>
      </div>
      <div className="grid sm:grid-cols-2 gap-4">
        {item.news &&
          item.news.length > 0 &&
          item.news.map((cardItem, key) =>
            <Card key={key} item={cardItem} category={item.slug} />)}

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

