import { useState, useEffect } from 'react';
import { ChevronUp } from 'lucide-react';
import { useAppSettings } from '../context/AppSettingsContext';

export default function ScrollToTopButton() {
  const { settings } = useAppSettings();
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const toggleVisibility = () => {
      // Show button when scrolled past configured threshold
      if (window.scrollY > window.innerHeight * settings.scrollToTopThreshold) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    window.addEventListener('scroll', toggleVisibility);
    return () => window.removeEventListener('scroll', toggleVisibility);
  }, [settings.scrollToTopThreshold]);

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

  if (!isVisible) return null;

  return (
    <button
      onClick={scrollToTop}
      className="fixed bottom-6 right-6 p-3 bg-gray-200 hover:bg-gray-300 text-gray-600 rounded-full shadow-md transition-all duration-300 opacity-70 hover:opacity-100 z-50"
      aria-label="Nach oben scrollen"
      title="Nach oben"
    >
      <ChevronUp className="w-5 h-5" />
    </button>
  );
}
