import React, { useEffect, useState, useCallback } from 'react';
import { useLocation } from 'react-router-dom';
import { useSmoothScroll } from '../../hooks/useSmoothScroll';
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts';
import { FiArrowUp } from 'react-icons/fi';

/**
 * PageEnhancer - Adds universal functionality to all pages
 * - Back to top button
 * - Keyboard shortcuts
 * - Scroll to top on route change
 * - Skip to content link
 */

interface PageEnhancerProps {
  children: React.ReactNode;
}

const PageEnhancer: React.FC<PageEnhancerProps> = ({ children }) => {
  const [showBackToTop, setShowBackToTop] = useState(false);
  const { scrollToTop, scrollToElement } = useSmoothScroll();
  const location = useLocation();

  // Scroll to top when route changes
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [location.pathname]);

  // Show/hide back to top button
  useEffect(() => {
    const handleScroll = () => {
      setShowBackToTop(window.scrollY > 300);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Handle back to top click
  const handleBackToTop = useCallback(() => {
    scrollToTop();
  }, [scrollToTop]);

  // Global keyboard shortcuts
  useKeyboardShortcuts([
    {
      key: 'Home',
      callback: scrollToTop,
      description: 'Scroll to top',
    },
    {
      key: 'End',
      callback: () => {
        window.scrollTo({
          top: document.body.scrollHeight,
          behavior: 'smooth',
        });
      },
      description: 'Scroll to bottom',
    },
    {
      key: 'Escape',
      callback: () => {
        // Close any open modals (implement based on your modal system)
        const event = new CustomEvent('closeAllModals');
        window.dispatchEvent(event);
      },
      description: 'Close modals',
    },
  ]);

  return (
    <>
      {/* Skip to main content link for accessibility */}
      <a href="#main-content" className="skip-to-content">
        Přeskočit na hlavní obsah
      </a>

      {/* Main content with ID for skip link */}
      <div id="main-content">
        {children}
      </div>

      {/* Back to top button */}
      <button
        className={`back-to-top ${showBackToTop ? 'visible' : ''}`}
        onClick={handleBackToTop}
        aria-label="Zpět nahoru"
        title="Zpět nahoru"
      >
        <FiArrowUp size={24} />
      </button>
    </>
  );
};

export default PageEnhancer;
