import { useRef } from 'react';
import ArticleCard from './ArticleCard';
import { ChevronLeft, ChevronRight } from '@mui/icons-material';
import React from 'react';
import { Article } from '../types/article';

interface CarouselProps {
  name: string;
  articles: Article[] | null;
}

const Carousel = (props: CarouselProps) => {
  // If no articles are provided, render nothing
  if (!props.articles || props.articles.length === 0) return null;

  const scrollRef = useRef<HTMLDivElement>(null);

  const slide = (dir: 'left' | 'right') => {
    const el = scrollRef.current;
    if (!el) return;
    // Calculate width of one item (includes gap)
    const w = (el.firstElementChild?.clientWidth ?? 360) + 26;
    el.scrollBy({ left: dir === 'left' ? -w : w, behavior: 'smooth' });
  };

  return (
    <section className="relative max-w-7xl mx-auto px-4 py-12">
      <h2 className="mb-6 text-2xl md:text-3xl font-bold text-gray-800">{props.name}</h2>

      <div className="relative">
        <button
          aria-label="Předchozí"
          onClick={() => slide('left')}
          className="absolute -left-12 top-1/2 -translate-y-1/2 z-10 hidden lg:flex items-center justify-center w-12 h-12 rounded-full bg-white shadow-md hover:scale-105 transition"
        >
          <ChevronLeft />
        </button>

        <div
          ref={scrollRef}
          className="flex gap-6 overflow-x-auto scroll-smooth scrollbar-hide px-1 py-6"
        >
          {props.articles.map((article: Article, i) => (
            <div
              key={article?.id ?? i}
              className="flex-shrink-0 w-full sm:w-[60%] lg:w-[32%] px-2"
            >
              {article ? (
                <ArticleCard article={article} />
              ) : (
                <div className="h-60 w-full rounded-lg bg-slate-200 animate-pulse" />
              )}
            </div>
          ))}
        </div>

        <button
          aria-label="Další"
          onClick={() => slide('right')}
          className="absolute -right-12 top-1/2 -translate-y-1/2 z-10 hidden lg:flex items-center justify-center w-12 h-12 rounded-full bg-white shadow-md hover:scale-105 transition"
        >
          <ChevronRight />
        </button>
      </div>
    </section>
  );
};

export default Carousel;