import { useEffect, useRef, useState } from "react";
import ScrollToTopIcon from "../icons/ScrollToTopIcon";

const ScrollToTopButton = () => {
  const [isVisible, setIsVisible] = useState<boolean>(true);
  const buttonRef = useRef<HTMLButtonElement>(null);

  const handleOnScroll = () => {
    if (window.scrollY > 1000) {
      setIsVisible(true);
    } else {
      setIsVisible(false);
    }
  };

  const handleOnClick = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  };

  useEffect(() => {
    window.addEventListener("scroll", handleOnScroll);

    return () => {
      window.removeEventListener("scroll", handleOnScroll);
    };
  }, []);

  return (
    <button
      ref={buttonRef}
      className={`fixed bottom-5 right-5 ${isVisible ? "" : "hidden"}`}
      onClick={handleOnClick}
    >
      <ScrollToTopIcon />
    </button>
  );
};

// const contentRef = useRef<HTMLDivElement>(null);
//   const divRef = useRef<HTMLDivElement>(null);

//   function handleClick() {
//     onClick();

//     setTimeout(() => {
//       window.scrollTo({
//         top: divRef.current?.offsetTop,
//         behavior: "smooth",
//       });
//     }, 200);
//   }

//   return (
//     <div ref={divRef} className="w-[300px] flex flex-col">
//       <button onClick={handleClick} className="p-4 bg-red-300">
//         {title}
//       </button>
//       <div
//         ref={contentRef}
//         className={`bg-blue-300 ${
//           selected
//             ? `${contentRef.current} opacity-100 h-[1500px]`
//             : "h-0 opaci

export default ScrollToTopButton;
