import "../styles/globals.css"
import type {AppProps} from "next/app"
import Layout from "../components/Layout/Layout";
import {AuthProvider} from "../components/AuthProvider/AuthProvider";
import {SnackbarProvider} from "notistack";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
import {LocalizationProvider} from "@mui/x-date-pickers";
import {ruRU} from "@mui/material/locale";
import {SnackbarUtilsConfigurator} from "../components/SnackbarUtilsConfigurator/SnackbarUtilsConfigurator";
import {CartProvider} from "../components/CartProvider/CartProvider";
import dayjs from "dayjs";
import ru from "dayjs/locale/ru";
import utc from "dayjs/plugin/utc";
import Head from "next/head";
import "../public/css/input-mono.woff2.css";
import "../public/css/mont.woff2.css";
import {NotificationProvider} from "../components/NotificationProvider/NotificationProvider";
import {IntlProvider} from "react-intl";
import ReferralProvider from "../components/ReferralProvider/ReferralProvider";
import DemoCodeProvider from "../components/DemoCodeProvider/DemoCodeProvider";
import Script from "next/script";
import {useRouter} from "next/router";
import {ApiKeyProvider} from "../providers/ApiKeyProvider/ApiKeyProvider";
import {useEffect} from "react";

dayjs.locale(ru);
dayjs.extend(utc);

function MyApp({ Component, pageProps }: AppProps) {
  const router = useRouter();
  const { isFallback, events } = useRouter();
  const googleTranslateElementInit = () => {
    // @ts-ignore
    new window.google.translate.TranslateElement({ pageLanguage: "ru" }, "google_translate_element");
  }

  useEffect(() => {
    const id = "google-translate-script";

    const addScript = () => {
      const s = document.createElement("script");
      s.setAttribute("src", "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit");
      s.setAttribute("id", id);
      const q = document.getElementById(id);

      if (!q) {
        document.body.appendChild(s);
        // @ts-ignore
        window.googleTranslateElementInit = googleTranslateElementInit;
      }
    }

    const removeScript = () => {
      const q = document.getElementById(id);
      if (q) q.remove();
      const w = document.getElementById("google_translate_element");
      if (w) w.innerHTML = "";
    }

    isFallback || addScript();

    events.on("routeChangeStart", removeScript);
    events.on("routeChangeComplete", addScript);

    document.cookie = "=googtrans";

    return () => {
      events.off("routeChangeStart", removeScript);
      events.off("routeChangeComplete", addScript);
    };
  }, []);

  const routeParts = router.route.split("/");
  const hideAmoCrm = Array.isArray(routeParts)
    && routeParts.length >= 3
    && "cabinet" === routeParts[1]
    && ["trading", "algo-trading"].includes(routeParts[2]);

  return (
    <>
      <Head>
        <meta
          name="viewport"
          content="minimum-scale=1, initial-scale=1, width=device-width"
          key="viewport-meta"
        />
        {
          hideAmoCrm ? (<style id="hide-amo-button">.amo-button {`{display: none !important}`}</style>) : (<></>)
        }
      </Head>
      <IntlProvider locale="ru">
        <AuthProvider>
          <ApiKeyProvider>
            <CartProvider>
              <NotificationProvider>
                <ReferralProvider>
                  <DemoCodeProvider>
                    <LocalizationProvider adapterLocale={ruRU} dateAdapter={AdapterDayjs}>
                      <SnackbarProvider className="snackbar-styles" anchorOrigin={{ vertical: "bottom", horizontal: "right" }} maxSnack={4}>    <SnackbarUtilsConfigurator />
                        <Layout>
                          <Component {...pageProps} />
                        </Layout>
                      </SnackbarProvider>
                    </LocalizationProvider>
                  </DemoCodeProvider>
                </ReferralProvider>
              </NotificationProvider>
            </CartProvider>
          </ApiKeyProvider>
        </AuthProvider>
      </IntlProvider>
      <Script
        id="amo-chat"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            (function(a,m,o,c,r,m){a[m]={id:"364435",hash:"beafc0edab607fa31241320b7af9026be29401f0634595fbf1660c11303896cf",locale:"ru",inline:false,setMeta:function(p){this.params=(this.params||[]).concat([p])}};a[o]=a[o]||function(){(a[o].q=a[o].q||[]).push(arguments)};var d=a.document,s=d.createElement("script");s.async=true;s.id=m+"_script";s.src="https://gso.amocrm.ru/js/button.js?1669713416";d.head&&d.head.appendChild(s)}(window,0,"amoSocialButton",0,0,"amo_social_button"));
          `
        }}
      />
    </>
  )
}

export default MyApp

import {LayoutProps} from "./Layout.props";
import {createTheme, ThemeProvider} from "@mui/material/styles";
import {
  AppBar,
  Badge,
  Box,
  Button,
  Container,
  CssBaseline, Dialog, DialogContent, DialogTitle,
  Divider,
  Drawer,
  Grid,
  Icon,
  IconButton,
  Link as MLink,
  List,
  ListItem,
  ListItemAvatar,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  responsiveFontSizes,
  Stack,
  Toolbar,
  Typography,
} from "@mui/material";
import {useRouter} from "next/router";
import {RouteGuard} from "../RouteGuard/RouteGuard";
import {useAuthContext} from "../AuthProvider/AuthProvider";
import {Fragment, MouseEventHandler, useEffect, useState} from "react";
import MenuIcon from "@mui/icons-material/Menu";
import {
  CameraAlt,
  NotificationsRounded,
  ShoppingBagRounded,
  Telegram,
  Twitter,
  YouTube
} from "@mui/icons-material";
import {sideMenu} from "./_side.menu";
import {mobileMenu} from "./_mobile.menu";
import Link from "next/link";
import {CicapLogo, DiscordIcon, DzenIcon, FakeFacebookIcon, VkIcon} from "../icons";
import {useCartContext} from "../CartProvider/CartProvider";
import Script from "next/script";
import BinanceLive from "../BinanceLive/BinanceLive";
import Image from "next/image";
import {useNotificationContext} from "../NotificationProvider/NotificationProvider";
import dayjs from "dayjs";
import {Notification, notificationSetAsRead, notificationUnreadCollection} from "../../actions/notification";
import NotificationBlock from "../NotificationBlock/NotificationBlock";
import NotificationAvatar from "../NotificationAvatar/NotificationAvatar";
import {useDemoCodeContext} from "../DemoCodeProvider/DemoCodeProvider";
import {checkDemoCode} from "../../actions/demo-code";
import PermIdentityIcon from "@mui/icons-material/PermIdentity";
import LanguageSwitcher from "../LanguageSwitcher/LanguageSwitcher";

declare module "@mui/material/Alert" {
  interface AlertPropsColorOverrides {
    black: true;
    white: true;
    green: true;
    discordInvite: true;
  }
}

declare module "@mui/material/Button" {
  interface ButtonPropsColorOverrides {
    black: true;
    white: true;
    green: true;
    discordInvite: true;
  }
}

declare module "@mui/material/Radio" {
  interface RadioPropsColorOverrides {
    black: true;
    white: true;
    green: true;
  }
}

declare module "@mui/material/Checkbox" {
  interface CheckboxPropsColorOverrides {
    black: true;
    white: true;
    green: true;
  }
}

declare module "@mui/material/styles" {
  interface Palette {
    black: Palette["primary"];
    white: Palette["primary"];
    green: Palette["primary"];
    discordInvite: Palette["primary"];
  }

  interface PaletteOptions {
    black: PaletteOptions["primary"];
    white: PaletteOptions["primary"];
    green: PaletteOptions["primary"];
    discordInvite: PaletteOptions["primary"];
  }

  interface PaletteColor {
    black?: string;
    white?: string;
    green?: string;
    discordInvite?: string;
  }
}

let theme = createTheme({
  palette: {
    primary: {
      main: "#cb0000",
    },
    secondary: {
      main: "#0d0d0d",
    },
    success: {
      main: "#30C23A",
      contrastText: "#ffffff",
    },
    error: {
      main: "#D73A3A",
      contrastText: "#ffffff",
    },
    white: {
      main: "#ffffff",
      contrastText: "#000000"
    },
    black: {
      main: "#000000",
      contrastText: "#ffffff",
    },
    green: {
      main: "#286d43",
      contrastText: "#ffffff",
    },
    discordInvite: {
      main: "#e74c3c",
      contrastText: "#ffffff",
    }
  },
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          textTransform: "none",
          fontSize: "1rem",
          paddingTop: ".5rem",
          paddingBottom: ".5rem",
          paddingLeft: "2.75rem",
          paddingRight: "2.75rem",
          borderRadius: ".5rem",
          boxShadow: "none"
        }
      }
    },
    MuiTypography: {
      styleOverrides: {
        gutterBottom: {
          marginBottom: "1rem",
        }
      }
    },
    MuiChip: {
      styleOverrides: {
        root: {
          borderRadius: "3px",
          height: "18px",
        },
        label: {
          paddingLeft: "4px",
          paddingRight: "4px"
        }
      }
    }
  },
  typography: {
    fontSize: 14,
    fontFamily: [
      "Mont",
      "-apple-system",
      "BlinkMacSystemFont",
      "Segoe UI",
      "Roboto",
      "Helvetica Neue",
      "Arial",
      "sans-serif",
      "Apple Color Emoji",
      "Segoe UI Emoji",
      "Segoe UI Symbol",
    ].join(","),
    body1: {
      lineHeight: 1.618,
    },
    h1: {
      fontWeight: 800,
      fontSize: "3.7rem",
      lineHeight: 1.25,
      letterSpacing: "0em",
    },
    h2: {
      fontSize: "3rem",
      fontWeight: 800,
      lineHeight: 1.25,
      letterSpacing: "0em",
    },
    h3: {
      fontSize: "2.2rem",
      fontWeight: 800,
      lineHeight: 1.25,
    },
    h4: {
      fontSize: "1.8rem",
      fontWeight: 800,
      lineHeight: 1.25,
      letterSpacing: "0em",
    },
    h5: {
      fontWeight: 800,
      lineHeight: 1.25,
    },
    h6: {
      fontWeight: 800,
      lineHeight: 1.25,
      letterSpacing: "0em",
    },
  },
  shape: {
    borderRadius: 6,
  },
});
theme = responsiveFontSizes(theme, {
  breakpoints: ["xs", "md"],
  variants: ["h1", "h2", "h3", "h4", "h5", "h6", "subtitle1", "subtitle2", "body1", "body2", "button", "caption", "overline"],
});

export default function Layout({children}: LayoutProps) {
  const [drawerWidth, setDrawerWidth] = useState(60);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [asUser, setAsUser] = useState<string|null>(null);
  const router = useRouter();
  const {user, bearer} = useAuthContext();
  const {carts} = useCartContext();
  const {notifications, setNotifications} = useNotificationContext();
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const [open, setOpen] = useState(false);
  const [notification, setNotification] = useState<Notification|undefined>(undefined);
  const [notificationsCount, setNotificationsCount] = useState(0);
  const [showSocial, setShowSocial] = useState(false);
  const [showed, setShowed] = useState(false);
  const [showDemoModal, setShowDemoModal] = useState(false);
  const {demoCode, setDemoCode} = useDemoCodeContext();

  const handleClick: MouseEventHandler = event => {
    // @ts-ignore
    setAnchorEl(event.currentTarget);
    setOpen(true);
  };

  const handleClose = () => {
    setAnchorEl(null);
    setOpen(false);
  };

  const hideNotification = (notification_id: number) => {
    notificationSetAsRead(notification_id, bearer)
      .then(data => {
        if (!data) return;

        notificationUnreadCollection(bearer)
          .then(data => {
            if (!data) return;

            setNotifications(data.data);
          })
      })
  }

  useEffect(() => {
    if ("undefined" !== typeof window) {
      setAsUser(window.localStorage.getItem("as_user"));
    }
  })

  useEffect(() => {
    if (notificationsCount < notifications.length && notifications.length > 0) {
      setNotification(notifications[0]);
    }

    setNotificationsCount(notifications.length);
  }, [notifications]);

  useEffect(() => {
    document.addEventListener("mouseout", (event) => {
      // @ts-ignore
      const from = event.relatedTarget || event?.toElement;

      if ( (!from || from.nodeName == "HTML") && event.clientY <= 100 ) {
        setShowSocial(true);
      }
    });
  }, []);

  useEffect(() => {
    if (undefined === demoCode || "undefined" === demoCode) {
      return;
    }

    checkDemoCode(demoCode)
      .then(data => {
        if (!data) {
          return;
        }

        if (!data.result) {
          window.localStorage.removeItem("demo_code");
          return;
        }

        setShowDemoModal(true);
      });
  }, [demoCode]);
  
  interface ActiveLink {
    href: string
    children: string
  }
  const ActiveLink = ({ href, children }: ActiveLink) => {
    const router = useRouter();
    const isActive = router.pathname === href;
  
    return (
      <Typography sx={{ fontWeight: isActive ? 400 : 200 }}>
        <Link href={href}>{children}</Link>
      </Typography>
    );
  }

  return (
    <ThemeProvider theme={theme}>
      {
        null !== asUser ? (
          <Box
            sx={{
              position: "fixed",
              left: 0,
              right: 0,
              bottom: 0,
              height: "40px",
              lineHeight: "40px",
              zIndex: 10,
              textAlign: "center",
              backgroundColor: theme => theme.palette.primary.main,
              color: theme => theme.palette.primary.contrastText,
            }}
          >
            Вы авторизованы под пользователем с ID {asUser}&nbsp;
            <button
              style={{ marginLeft: "7px", cursor: "pointer", border: "1px solid #fff", color: "#f00", background: "white", fontWeight: "bold", borderRadius: "3px"}}
              onClick={() => { window.localStorage.removeItem("as_user"); window.location.reload() }}
            >
              Выйти
            </button>
          </Box>
        ) : (<></>)
      }
      <RouteGuard>
        {
          "/_error" === router.pathname ? children : (
            <>
              <Box sx={{ display: "flex", background: "#f5f5f5" }}>
                <CssBaseline />
                <AppBar position="fixed" sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }} color="secondary">
                  <Toolbar>
                    <Box sx={{display: "flex",width: "100%",}}>
                      <Grid sx={{display: "flex", width: "100%", flexDirection: "row", alignItems: "center", ml: {xs: 0, md: -2}, pr: {xs: 0, md: 3}}}>
                        <Stack direction="row" className="header-menu" alignItems="center" justifyContent="center" spacing={2}
                         sx={{display: {xs: "none", md: "flex"}, whiteSpace: "nowrap"}}>
                        <Typography width={130} >
                          <Link href="/">
                            <MLink href="/"  className="logo">
                              <Icon component={CicapLogo} sx={{transform: {xs: "none", md: "translateX(-12px)"}}} />
                            </MLink>
                          </Link>
                        </Typography>
                            <ActiveLink  href="/shop">Курсы</ActiveLink>
                            <ActiveLink href="/about">О компании</ActiveLink>
      <ActiveLink href="/subscriptions">Подписки</ActiveLink>
      <ActiveLink href="/soft">Софт</ActiveLink>
      <ActiveLink href="/faq">FAQ</ActiveLink>
      <ActiveLink href="/contacts">Контакты</ActiveLink>
                          {
                            user && (
                              <Badge badgeContent={user.courses_count} color="primary" sx={{display: {xs: "none", md: "none", lg: "block"}}}>
                                <Typography sx={{fontWeight: 200}}>
                                  <Link href="/cabinet/learning">Мои курсы</Link>
                                </Typography>
                              </Badge>
                            )
                          }

                        </Stack>                          
                        <Box sx={{ flex: 3, display: "flex", alignItems: "center", justifyContent: "end" }}>
                          <LanguageSwitcher />
                            </Box>
                        <Box sx={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "end" }}>
                          {
                            bearer && notifications.length > 0 && (
                              <>
                                <Button sx={{px: "0", color: "#fff"}} onClick={handleClick}>
                                  <Badge
                                    badgeContent={notifications.length > 9 ? "9+" : notifications.length}
                                    color="primary"
                                  >
                                    <NotificationsRounded />
                                  </Badge>
                                </Button>
                                <Popover
                                  open={open}
                                  anchorEl={anchorEl}
                                  onClose={handleClose}
                                  anchorOrigin={{
                                    vertical: "bottom",
                                    horizontal: "right",
                                  }}
                                  sx={{transform: {md: "translateX(-250px)"}}}
                                >
                                  <List sx={{width: "500px", maxWidth: "80vw"}}>
                                    {
                                      notifications.map((notification, index) => (
                                        <Fragment key={index}>
                                          <ListItem>
                                            <ListItemAvatar>
                                              <NotificationAvatar notification={notification} />
                                            </ListItemAvatar>
                                            <ListItemText
                                              primary={notification.title}
                                              primaryTypographyProps={{
                                                sx: {lineHeight: 1.3, cursor: "pointer"},
                                                onClick: () => {
                                                  setNotification(notification)
                                                }
                                              }}
                                              secondary={<>
                                                <Typography fontSize="small" sx={{opacity: .75}}>{dayjs(notification.created_at).format("DD MMM, HH:mm")}</Typography>
                                                {
                                                  !notification.read && (
                                                    <Button
                                                      variant="outlined"
                                                      sx={{px: "12px !important", mt: 1, py: "0 !important", fontSize: "12px"}}
                                                      onClick={e => {
                                                        e.preventDefault();
                                                        hideNotification(notification.id);
                                                      }}
                                                    >
                                                      Скрыть
                                                    </Button>
                                                  )
                                                }
                                              </>}
                                            />
                                          </ListItem>
                                          <Divider />
                                        </Fragment>
                                      ))
                                    }
                                    <ListItem>
                                      <Link href={"/cabinet/notifications"}>
                                        <MLink href={"/cabinet/notifications"} onClick={() => {setOpen(false)}}>Все уведомления</MLink>
                                      </Link>
                                    </ListItem>
                                  </List>
                                </Popover>
                              </>
                            )
                          }
                          {
                            bearer && notifications.length === 0 ? (
                              <Link href={"/cabinet/notifications"}>
                                <IconButton
                                  size="large"
                                  color="inherit"
                                  href="/cabinet/notifications"
                                  sx={{p: 0, mr: 2}}
                                >
                                  <NotificationsRounded />
                                </IconButton>
                              </Link>
                            ) : (<></>)
                          }
                          <Link href={"/cart"}>
                            {
                              carts.length > 0 ? (
                                <Badge badgeContent={carts.length} color="primary">
                                  <IconButton
                                    size="large"
                                    color="inherit"
                                    href="/cart"
                                    sx={{p: 0, mr: 2}}
                                  >
                                    <ShoppingBagRounded />
                                  </IconButton>
                                </Badge>
                              ) : (
                                <IconButton
                                  size="large"
                                  color="inherit"
                                  href="/cart"
                                  sx={{p: 0}}
                                >
                                  <ShoppingBagRounded />
                                </IconButton>
                              )
                            }
                          </Link>
                          {
                            bearer ? (
                              <Link href="/cabinet">
                                <IconButton
                                  size="large"
                                  color="inherit"
                                  sx={{p: 0}}
                                >
                                <PermIdentityIcon sx={{mr: 0.5}} /> 
                                  <Typography fontWeight={300} pt={0.5} >
                                    {user?.name}
                                  </Typography>
                                </IconButton>
                              </Link>
                            ) : (
                              <>
                                <Link href="/login">
                                  <Button
                                    size="small"
                                    href="/login"
                                    sx={{whiteSpace: "nowrap", borderRadius: "6px", lineHeight: 1.25, px: 2, height: "38px", mr: 1, ml: 2, display: {xs: "none", md: "block"}}}
                                    // @ts-ignore
                                    color="white"
                                    variant="outlined"
                                  >Вход</Button>
                                </Link>

                                <Link href="/registration">
                                  <Button
                                    size="small"
                                    sx={{whiteSpace: "nowrap", borderRadius: "6px", lineHeight: 1.25, px: 2, height: "38px", display: {xs: "none", md: "block"}}}
                                    // @ts-ignore
                                    color="white"
                                    variant="contained"
                                  >Регистрация</Button>
                                </Link>
                              </>
                            )
                          }
                                              <IconButton
                      size="large"
                      edge="start"
                      color="inherit"
                      aria-label="menu"
                      sx={{ ml: 2, mr: -7, mt: 1, display: {xs: "none", md: "block"} }}
                      onClick={() => {
                        setDrawerWidth(drawerWidth === 60 ? 250 : 60)
                      }}
                    >
                      <MenuIcon />
                    </IconButton>
                          <IconButton
                            size="large"
                            edge="start"
                            color="inherit"
                            aria-label="menu"
                            sx={{ ml: 2, display: {xs: "block", md: "none"}, lineHeight: 0 }}
                            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                          >
                            <MenuIcon />
                          </IconButton>
                        </Box>
                      </Grid>
                    </Box>
                  </Toolbar>
                </AppBar>
                <Drawer
                  anchor="right"
                  variant="permanent"
                  sx={{
                    display: {xs: "none", md: "flex"},
                    width: drawerWidth,
                    flexShrink: 2,
                    [`& .MuiDrawer-paper`]: {
                      width: drawerWidth,
                      boxSizing: "border-box",
                      background: "#0d0d0d",
                      color: "#fff",
                    },
                  }}
                  onMouseOver={() => {
                    setDrawerWidth(250)
                  }}
                  onMouseOut={() => {
                    setDrawerWidth(60)
                  }}
                >
                  <Toolbar sx={{backgroundColor: "#0d0d0d", color: "#fff"}} />
                  <Stack
                    direction="column"
                    alignItems="flex-start"
                    justifyContent="space-between"
                    sx={{
                      overflowX: "hidden",
                      backgroundColor: "#0d0d0d",
                      color: "#fff",
                      height: "100vh",
                    }}
                  >
                    {
                      sideMenu.map((group, index) => (
                        <Box key={index}>
                          <List>
                            {
                              group.map(({ label, url, icon }) => (
                                <ListItem key={label} disablePadding sx={{ width: "300px", }}>
                                  <Link href={url}>
                                    <ListItemButton sx={{["&:hover"]: {background: "rgba(255,255,255,.2)", lineHeight: "36px"}}}>
                                      <ListItemIcon sx={{color: "#fff", minWidth: drawerWidth > 60 ? "48px" : "32px", height: "36px", pt: .5}}>
                                        <Icon component={icon} />
                                      </ListItemIcon>
                                      {
                                        drawerWidth > 60 ? (
                                          <ListItemText primary={label} />
                                        ) : (<></>)
                                      }
                                    </ListItemButton>
                                  </Link>
                                </ListItem>
                              ))
                            }
                          </List>
                          <Divider />
                        </Box>
                      ))
                    }
                  </Stack>
                </Drawer>
              </Box>
      </RouteGuard>
    </ThemeProvider>
  );
}

NotFoundError :  Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. 
переключаюсь в компоненте и показывает такую ошибку. как исправить?  почему может возникать такая проблема? next react