import { useState, useEffect, useCallback, useRef } from 'react';
import PropTypes from 'prop-types';
import cx from "../../../utils/css/cx.js";
import Card from './Card';
import DotWell from './DotWell';
import classes from './styles.module.scss';
const cls = cx.merge(classes);
const HomepageChatter = function HomepageChatter(props) {
  const {
    cards
  } = props;
  const [selectedCardIndex, setSelectedCardIndex] = useState(0);
  const rotateInterval = useRef();
  const clearAutoRotate = useCallback(() => {
    if (rotateInterval.current) {
      clearInterval(rotateInterval.current);
    }
  }, []);
  useEffect(() => {
    const interval = setInterval(() => {
      setSelectedCardIndex(prevIndex => {
        const nextIdx = prevIndex + 1;
        if (nextIdx >= cards.length) {
          return 0;
        }
        return nextIdx;
      });
    }, 5000);
    rotateInterval.current = interval;
    return () => {
      clearAutoRotate();
    };
  }, [cards.length]);
  const cardContainerGap = 8;
  const transformCardContainer = `calc(${-100 * selectedCardIndex}% - ${cardContainerGap * selectedCardIndex}px)`;
  return <div className={cls('main')}>
      <div className={cls('well')}>
        <div className={classes['cards-container']} style={{
        gap: `${cardContainerGap}px`,
        transform: `translate(${transformCardContainer}, 0)`
      }}>
          {cards.map(card => <Card key={card.id} reporterName={card.reporterName} comment={card.comment} headshot={card.headshot} link={card.link} selectedCardIndex={selectedCardIndex} total={cards.length} />)}
        </div>
      </div>
      <DotWell count={cards.length} selectedCardIndex={selectedCardIndex} setSelectedCardIndex={setSelectedCardIndex} clearAutoRotate={clearAutoRotate} />
    </div>;
};
HomepageChatter.defaultProps = {
  cards: []
};
HomepageChatter.propTypes = {
  cards: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.string,
    reporterName: PropTypes.string,
    comment: PropTypes.string,
    headshot: PropTypes.string,
    link: PropTypes.string
  }))
};
export default HomepageChatter;