'use client';

import { JSX, useEffect, useState } from 'react';

export default function BackToTop(): JSX.Element | null {
  const [isVisible, setIsVisible] = useState<boolean>(false);

  useEffect(() => {
    const toggleVisibility = () => {
      // Show button when page is scrolled down 300px
      if (window.scrollY > 300) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    // Throttled scroll event for better performance
    let timeoutId: NodeJS.Timeout;
    const handleScroll = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(toggleVisibility, 100);
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
      clearTimeout(timeoutId);
    };
  }, []);

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

  if (!isVisible) return null;

  return (
    <button
      id="back-to-top-button"
      onClick={scrollToTop}
      className="border border-white fixed bottom-6 right-6 z-50 bg-mma-blue hover:bg-mma-yellow text-white hover:text-mma-blue p-3 shadow-lg transition-all duration-300 hover:scale-110"
      aria-label="Vissza a tetejére"
    >
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        className="w-6 h-6"
      >
        <path d="M12 4L4 12H8V20H16V12H20L12 4Z" fill="currentColor" />
      </svg>
    </button>
  );
}
