import { Box, Container, IconButton } from '@chakra-ui/react';
import { ReactNode, useEffect, useState } from 'react';
import { FiChevronUp } from 'react-icons/fi';
import Navbar from '../Navbar';
import Footer from './Footer';

interface MainLayoutProps {
  children: ReactNode;
}

export const MainLayout: React.FC<MainLayoutProps> = ({ children }) => {
  const [showTop, setShowTop] = useState(false);

  useEffect(() => {
    const onScroll = () => {
      try {
        setShowTop(window.scrollY > 400);
      } catch {}
    };
    window.addEventListener('scroll', onScroll, { passive: true } as any);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll as any);
  }, []);

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

  return (
    <Box minH="100vh" bg="bg.app" overflowX="hidden">
      <Box id="top" position="absolute" top={0} left={0} />
      <Navbar />
      <Container maxW="container.xl" py={8}>
        {children}
      </Container>
      <Footer />
      {showTop && (
        <IconButton
          aria-label="Zpět nahoru"
          icon={<FiChevronUp />}
          position="fixed"
          right={{ base: 4, md: 6 }}
          bottom={{ base: 4, md: 6 }}
          zIndex={1000}
          colorScheme="blue"
          onClick={scrollToTop}
          borderRadius="full"
          shadow="md"
        />
      )}
    </Box>
  );
};

export default MainLayout;
