import { useEffect, useState } from 'react';
import Button from 'react-bootstrap/Button';
import { FaAngleUp } from 'react-icons/fa';
import styles from './scroll-to-top.module.scss';

function ScrollToTop() {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    document.addEventListener('scroll', handleScrollEvent.bind(null, setIsVisible));
    return document.removeEventListener('scroll', handleScrollEvent.bind(null, setIsVisible));
  }, []);

  if (!isVisible) return null;

  return (
    <Button onClick={scrollToTop} className={styles['scroll-button']}>
      <FaAngleUp />
    </Button>
  );
}

function handleScrollEvent(setIsVisible) {
  setIsVisible(window.pageYOffset > 300);
}

function scrollToTop() {
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

export default ScrollToTop;
