import 'src/global.css';

import { useEffect, useState } from 'react';

import Fab from '@mui/material/Fab';
import KeyboardArrowUpRoundedIcon from '@mui/icons-material/KeyboardArrowUpRounded';

import { usePathname } from 'src/routes/hooks';

import { ThemeProvider } from 'src/theme/theme-provider';

// ----------------------------------------------------------------------

type AppProps = {
  children: React.ReactNode;
};

export default function App({ children }: AppProps) {
  useScrollToTop();

  const [showScrollTop, setShowScrollTop] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setShowScrollTop(window.scrollY > 160);
    };

    handleScroll();
    window.addEventListener('scroll', handleScroll, { passive: true });

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

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

  const ddButton = () => (
    <Fab
      size="medium"
      aria-label="Scroll to top"
      onClick={handleScrollTop}
      sx={{
        zIndex: 9,
        right: 20,
        bottom: 20,
        width: 48,
        height: 48,
        position: 'fixed',
        color: 'common.white',
        bgcolor: '#a52431',
        boxShadow: (theme) => theme.shadows[6],
        opacity: showScrollTop ? 1 : 0,
        pointerEvents: showScrollTop ? 'auto' : 'none',
        transform: showScrollTop ? 'translateY(0)' : 'translateY(12px)',
        transition: 'opacity 0.24s ease, transform 0.24s ease',
        '&:hover': {
          bgcolor: '#8c1e2a',
          boxShadow: (theme) => theme.shadows[8],
        },
      }}
    >
      <KeyboardArrowUpRoundedIcon fontSize="medium" />
    </Fab>
  );

  return (
    <ThemeProvider>
      {children}
      {ddButton()}
    </ThemeProvider>
  );
}

// ----------------------------------------------------------------------

function useScrollToTop() {
  const pathname = usePathname();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}