import React from "react";
import { useNavigate } from "react-router-dom";
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, FreeMode } from "swiper/modules";
import { useGetCategoriesQuery } from "../../app/api/categories.js";
import styles from "./CategorySlider.module.scss";

import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/free-mode";

const CategoryCarousel = () => {
  const { data, isLoading } = useGetCategoriesQuery("tree");
  const navigate = useNavigate();

  const mainCategories =
    data?.data?.filter((cat) => cat.parent_id === null) ?? [];

  const handleCardClick = (id) => {
    navigate(`/category/${id}`);
  };

  if (isLoading || mainCategories.length === 0) return null;

  return (
    <div className={styles.wrapper}>
      <Swiper
        modules={[Navigation, FreeMode]}
        navigation={{
          prevEl: `.${styles.prev}`,
          nextEl: `.${styles.next}`,
        }}
        freeMode={{ enabled: true, momentum: true, momentumRatio: 0.5 }}
        slidesPerView="auto"
        spaceBetween={12}
        grabCursor={true}
        className={styles.swiper}
      >
        {mainCategories.map((cat) => {
          const thumb =
            cat.media?.[0]?.images_400x400 ??
            cat.media?.[0]?.thumbnail ??
            null;

          return (
            <SwiperSlide key={cat.id} className={styles.slide}>
              <div
                className={styles.card}
                onClick={() => handleCardClick(cat.id)}
              >
                <div className={styles.imgWrap}>
                  {thumb ? (
                    <img
                      src={thumb}
                      alt={cat.name}
                      loading="lazy"
                      draggable={false}
                    />
                  ) : (
                    <div className={styles.placeholder} />
                  )}
                </div>
                <span className={styles.name}>{cat.name}</span>
              </div>
            </SwiperSlide>
          );
        })}
      </Swiper>

      <button className={`${styles.arrow} ${styles.prev}`} aria-label="Scroll left">
        ‹
      </button>
      <button className={`${styles.arrow} ${styles.next}`} aria-label="Scroll right">
        ›
      </button>
    </div>
  );
};

export default CategoryCarousel;