import React, { useEffect, useState, useRef } from "react";
import styled from "styled-components";

const CustomCarousel = ({
  items = [],
  autoPlay = true,
  interval = 3000,
  renderItem,
  dotColor = "",
  largeDot = false,
}) => {
  const [index, setIndex] = useState(0);
  const timeoutRef = useRef(null);

  // autoplay
  useEffect(() => {
    if (!autoPlay || items.length <= 1) return;

    const next = () => {
      setIndex((prev) => (prev + 1) % items.length);
    };

    timeoutRef.current = setTimeout(next, interval);

    return () => clearTimeout(timeoutRef.current);
  }, [index, items, autoPlay]);

  const goTo = (i) => setIndex(i);

  //   const nextSlide = () => setIndex((prev) => (prev + 1) % items.length);

  //   const prevSlide = () =>
  //     setIndex((prev) => (prev - 1 + items.length) % items.length);

  return (
    <Wrapper>
      <SlideContainer>
        <Slides index={index}>
          {items.map((item, i) => (
            <Slide key={i}>{renderItem(item)}</Slide>
          ))}
        </Slides>
      </SlideContainer>

      {/* {items.length > 1 && (
        <>
          <Arrow className="left" onClick={prevSlide}>
            ‹
          </Arrow>
          <Arrow className="right" onClick={nextSlide}>
            ›
          </Arrow>
        </>
      )} */}

      {/* Dots */}
      <Dots>
        {items.map((_, i) => (
          <Dot
            key={i}
            color={dotColor}
            large={largeDot}
            className={i === index ? "active" : ""}
            onClick={() => goTo(i)}
          />
        ))}
      </Dots>
    </Wrapper>
  );
};

export default CustomCarousel;

// styles
const Wrapper = styled.div`
  width: 100%;
  position: relative;
`;

const SlideContainer = styled.div`
  overflow: hidden;
  width: 100%;
  border-radius: 20px;
`;

const Slides = styled.div`
  display: flex;
  transition: transform 0.5s ease;
  transform: ${({ index }) => `translateX(-${index * 100}%)`};
`;

const Slide = styled.div`
  min-width: 100%;
`;

// const Arrow = styled.div`
//   position: absolute;
//   top: 45%;
//   transform: translateY(-50%);
//   font-size: 24px;
//   cursor: pointer;
//   padding: 6px;
//   z-index: 5;
//   user-select: none;
//   color: #333;

//   &.left {
//     left: 5px;
//   }
//   &.right {
//     right: 5px;
//   }
// `;

const Dots = styled.div`
  display: flex;
  gap: 8px;
  justify-content: center;
  margin-top: 10px;
`;

const Dot = styled.div`
  width: ${({ large }) => (large ? "12px" : "8px")};
  height: ${({ large }) => (large ? "8px" : "4px")};

  border-radius: 3px;
  background: #dfe5e5;
  cursor: pointer;

  &.active {
    width: ${({ large }) => (large ? "32px" : "20px")};
    background: ${({ color }) => color || "#00c2c2"};
    transition: width 0.3s;
  }
`;
