import { ToastContainer } from 'react-toastify-next';
import { Button } from '../../Button';
import { keyframes, styled } from '../../styled';
import { NOTIFY_HEIGHT, NOTIFY_HEIGHT_MOBILE, NOTIFY_NO_TRANSITION_ATTR, NotificationVariantTypes, notifyClassnames, } from '../constants';
const fade = keyframes `
  from {
    opacity: 0;
  }
  50% {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
`;
const leaveIn = keyframes `
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0px);
  }
`;
const leaveOut = keyframes `
  from {
    transform: translateX(0px);
  }
  to {
    transform: translateX(100%);
    visibility: hidden;
  }
`;
/** Сохраняем scale stacked (--s), иначе при старте exit transform из keyframes затирает scale и карточка визуально «прыгает» вправо */
const leaveOutMobileStacked = keyframes `
  from {
    transform: translateX(0) scale(var(--s, 1));
  }
  to {
    transform: translateX(100%) scale(var(--s, 1));
    visibility: hidden;
  }
`;
// используем дополнительный враппер,
// потому что styled для ToastContainer не умеет работать с theme внутри
// использовать бэм классы для стилизации пришлось,
// потому что react-toastify не предоставляет,
// достаточно контейнеров для стилизации через styled,
// к примеру добраться до прогресс бара можно только через цсс классы
export const Wrapper = styled.div `
  position: fixed;
  z-index: ${({ theme }) => theme.zIndex.snackbar};
  right: 0;
  bottom: 20px;

  width: 432px;

  ${({ theme }) => theme.breakpoints.down('sm')} {
    inset: 0 0 auto;

    width: 100%;
    max-width: 100vw;
    padding: ${({ theme }) => theme.spacing(2, 2, 2, 2)};
    padding-top: max(
      ${({ theme }) => theme.spacing(2)},
      env(safe-area-inset-top, 0px)
    );
  }

  &.${notifyClassnames.container} {
    display: flex;
    flex-direction: column;
    justify-content: end;

    height: 100vh;

    /* Причина игнора: Прогрессивное улучшение */
    /* stylelint-disable plugin/no-unsupported-browser-features */
    @supports (height: 100dvh) {
      height: 100dvh;
    }
    /* stylelint-enable plugin/no-unsupported-browser-features */

    ${({ theme }) => theme.breakpoints.up('sm')} {
      .${notifyClassnames.stackHost} .Toastify {
        overflow: hidden;
      }
    }

    ${({ theme }) => theme.breakpoints.down('sm')} {
      justify-content: flex-start;

      height: auto;

      .${notifyClassnames.stackHost} .Toastify {
        overflow: visible;
      }

      .${notifyClassnames.stack} {
        overflow: hidden auto;
        display: flex;
        flex-direction: column;
        gap: ${({ theme }) => theme.spacing(2)};
        align-items: stretch;

        width: 100%;
        max-width: 100%;
        padding-top: ${({ theme }) => theme.microSpacing(1)};
        padding-bottom: 8px !important;
        padding-bottom: ${({ theme }) => theme.spacing(1)};
        -webkit-overflow-scrolling: touch;
      }

      .${notifyClassnames.stack} .${notifyClassnames.root} {
        pointer-events: auto !important;

        position: relative !important;
        transform: none !important;

        flex-shrink: 0;

        width: 100% !important;
        max-width: 100%;
        height: auto !important;
        min-height: ${NOTIFY_HEIGHT_MOBILE};
        max-height: fit-content !important;
        margin-top: 0 !important;
        margin-right: 0 !important;
        margin-bottom: 0 !important;

        opacity: 1 !important;
      }

      /*
        На мобильных контейнер не получает mouseEnter — toastify оставляет data-collapsed=true
        и скрывает direct children не‑последних тостов (.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0})
      */
      .${notifyClassnames.stack} .Toastify__toast--stacked > * {
        opacity: 1 !important;
      }

      .${notifyClassnames.stack} .${notifyClassnames.root}__content {
        max-height: 400px;
        margin: ${({ theme }) => theme.spacing(2, 0, 0, 8)};
      }

      .${notifyClassnames.stack} .${notifyClassnames.root}__footer {
        margin-bottom: 0;
      }

      .${notifyClassnames.stack} .Toastify__toast--stacked::before {
        display: none;
      }
    }
  }

  .${notifyClassnames.animationIn} {
    animation: ${leaveIn} ease-in-out ${({ theme }) => theme.transitions.duration.standard}ms;
    animation-fill-mode: both;
  }

  .${notifyClassnames.animationOut} {
    animation: ${leaveOut} ease-in-out;
    animation-fill-mode: both;
  }

  .${notifyClassnames.root} {
    overflow: hidden !important;

    width: 400px;
    height: ${NOTIFY_HEIGHT};
    padding: 0;

    box-shadow: ${({ theme }) => theme.elevation[300]};

    transition: ${({ theme }) => theme.transitions.create(['transform', 'margin-bottom'], {
    duration: theme.transitions.duration.short,
    easing: 'ease-in-out',
})};

    &::after {
      content: '';

      position: absolute;
      top: 0;
      left: 0;

      display: none;

      width: 100%;
      height: 3px;
    }
    ${({ theme }) => theme.breakpoints.up('sm')} {
      min-height: ${NOTIFY_HEIGHT};
    }
    ${({ theme }) => theme.breakpoints.down('sm')} {
      min-height: ${NOTIFY_HEIGHT_MOBILE};
    }

    .Toastify__progress-bar--wrp {
      top: 0;

      height: 3px;
    }

    .Toastify__progress-bar {
      opacity: 1;
    }

    &--${NotificationVariantTypes.Info} {
      --toastify-color-progress-light: ${({ theme }) => theme.palette.primary[800]};
    }
    &--${NotificationVariantTypes.Success} {
      --toastify-color-progress-light: ${({ theme }) => theme.palette.success[800]};
    }
    &--${NotificationVariantTypes.Warning} {
      --toastify-color-progress-light: ${({ theme }) => theme.palette.warning[800]};
    }
    &--${NotificationVariantTypes.Error} {
      --toastify-color-progress-light: ${({ theme }) => theme.palette.error[800]};
    }

    &__body {
      margin: 0;
      padding: 0;
    }
  }

  .${notifyClassnames.root}__content {
    overflow: hidden;

    max-height: 0;
    margin-top: 0;
  }

  .${notifyClassnames.root}__footer {
    margin-bottom: ${({ theme }) => theme.spacing(-3)};

    transition: ${({ theme }) => theme.transitions.create(['margin-bottom'], {
    duration: theme.transitions.duration.short,
    easing: theme.transitions.easing.easeInOut,
})};
  }

  /* Стили для уведомлений в стеке */
  ${({ theme }) => theme.breakpoints.up('sm')} { 
    .${notifyClassnames.stack} .${notifyClassnames.root} {
      position: relative;
      transform: scale(var(--s));

      &:not(:last-of-type) {
        margin-bottom: calc(
          ${({ theme }) => theme.spacing(4)} - ${NOTIFY_HEIGHT}
        );
      }

      &:last-of-type {
        height: auto;
        min-height: ${NOTIFY_HEIGHT};

        .${notifyClassnames.root}__content {
          max-height: 400px;
          margin: ${({ theme }) => theme.spacing(2, 0, 0, 8)};
        }
      }

      /* В свернутом виде показываем не более 3-x уведомлений */
      &:not(:nth-last-of-type(-n + 3)) {
        margin-bottom: -${NOTIFY_HEIGHT};

        opacity: 0;
      }

      /* Отключаем анимацию при появлении нового уведомления */
      &[${NOTIFY_NO_TRANSITION_ATTR}='true'] {
        transition-duration: 0s !important;
      }
    }
  }

  /* Мобильный стек в свёрнутом виде: последний в DOM (самый новый) — сверху; остальные без участия в раскладке */
  ${({ theme }) => theme.breakpoints.down('sm')} {
    &:not(.${notifyClassnames.container}) {
      .${notifyClassnames.stack} {
        position: relative;

        overflow: visible;
        display: flex;
        flex-direction: column-reverse;
        gap: 0;
        align-items: stretch;
        justify-content: flex-end;

        max-height: none;
        margin-bottom: ${({ theme }) => theme.spacing(2)};
        -webkit-overflow-scrolling: auto;

        /* Два фейковых слоя — только пока в стеке ≥2 активных тоста (без анимации закрытия) */

        /* Причина игнора: Не критично для отображения */
        /* stylelint-disable-next-line plugin/no-unsupported-browser-features */
        &:has(.${notifyClassnames.root}:not(.${notifyClassnames.animationOut}) ~ .${notifyClassnames.root}:not(.${notifyClassnames.animationOut})) {
          padding-top: ${({ theme }) => theme.spacing(4)};

          &::before,
          &::after {
            pointer-events: none;
            content: '';

            position: absolute;
            z-index: 0;
            right: ${({ theme }) => theme.spacing(2)};
            left: ${({ theme }) => theme.spacing(2)};

            height: ${NOTIFY_HEIGHT_MOBILE};

            background: ${({ theme }) => theme.palette.background.paper};
            border-radius: ${({ theme }) => theme.shape.medium};
            box-shadow: ${({ theme }) => theme.elevation[200]};
          }

          &::before {
            top: 0;
            transform: scaleX(0.92);
          }

          &::after {
            top: ${({ theme }) => theme.spacing(2)};
            transform: scaleX(0.96);
          }
        }
      }

      .${notifyClassnames.stack} .${notifyClassnames.root}:not(:last-of-type) {
        pointer-events: none;

        position: absolute;

        overflow: hidden;

        width: 1px;
        height: 1px;
        margin: -1px;
        padding: 0;

        white-space: nowrap;

        opacity: 0;
        clip: rect(0, 0, 0, 0);
        clip-path: inset(50%);
        border: 0;

        .${notifyClassnames.root}__content {
          max-height: 0 !important;
          margin: 0 !important;
        }
      }

      .${notifyClassnames.stack} .${notifyClassnames.root}:last-of-type {
        position: relative;
        z-index: 1;
        transform: scale(var(--s, 1));

        flex: 0 0 auto;
        align-self: stretch;

        width: 100% !important;
        min-width: 0 !important;
        max-width: 100% !important;
        min-height: ${NOTIFY_HEIGHT_MOBILE};
        margin-bottom: 0 !important;

        opacity: 1;
        border-radius: ${({ theme }) => theme.shape.medium};

        .${notifyClassnames.root}__content {
          max-height: 400px;
          margin: ${({ theme }) => theme.spacing(2, 0, 0, 8)};
        }
      }

      .${notifyClassnames.stackHost} .Toastify,
      .${notifyClassnames.stackHost} .${notifyClassnames.stack} {
        overflow: visible !important;
      }

      .${notifyClassnames.animationOut} {
        animation: ${leaveOutMobileStacked} ease-in-out ${({ theme }) => theme.transitions.duration.standard}ms;
        animation-fill-mode: both;
      }
    }
  }
`;
export const Inner = styled(ToastContainer) `
  position: relative !important;
  right: 0 !important;
  bottom: 0 !important;

  width: 100%;
  min-width: 400px;
  max-width: 432px;
  padding-bottom: 0 !important;
  padding-left: ${({ theme }) => theme.spacing(3)} !important;

  .${notifyClassnames.root} {
    border-radius: ${({ theme }) => theme.shape.medium};
    
    &:last-of-type{
      margin-bottom: ${({ theme }) => theme.spacing(1)} ;
    }
  }

  /* Только устройства с реальным hover и ≥sm — иначе на touch :hover залипает и ломает мобильный стек */
  ${({ theme }) => theme.breakpoints.up('sm')} {
    @media (hover: hover) and (pointer: fine) {
      &:hover {
        overflow: hidden auto;

        height: 100%;

        .${notifyClassnames.root} {
          position: relative;
          transform: unset;

          height: auto;
          min-height: ${NOTIFY_HEIGHT};
          margin-bottom: ${({ theme }) => theme.spacing(1)} !important;

          opacity: 1 !important;
        }

        .${notifyClassnames.root}__content {
          max-height: 400px;
          margin: ${({ theme }) => theme.spacing(2, 0, 0, 8)};
        }

        .${notifyClassnames.root}__footer {
          margin-bottom: 0;
        }

        .Toastify__toast--stacked::before {
          display: none;
        }
      }
    }
  }

  ${({ theme }) => theme.breakpoints.down('sm')} {
    min-width: unset;
    max-width: 100%;
    padding-right: ${({ theme }) => theme.spacing(2)} !important;
    padding-left: ${({ theme }) => theme.spacing(2)} !important;

    .${notifyClassnames.root} {
      width: 100% !important;
      max-width: 100%;
      height: auto !important;
      min-height: ${NOTIFY_HEIGHT_MOBILE};
      margin-bottom: ${({ theme }) => theme.spacing(2)} !important;
    }

    .${notifyClassnames.root}__content {
      max-height: 400px;
      margin: ${({ theme }) => theme.spacing(2, 0, 0, 8)};
    }

    .${notifyClassnames.root}__footer {
      margin-bottom: 0;
    }
  }
`;
export const StaticInner = styled(Inner) `
  margin-top: 0;
  
  .${notifyClassnames.root} {
    margin-bottom: ${({ theme }) => theme.spacing(1)};
  }
`;
export const CloseButton = styled(Button) `
  right: ${({ theme }) => theme.spacing(3)};

  width: 400px;
  margin-left: ${({ theme }) => theme.spacing(6)};

  box-shadow: ${({ theme }) => theme.elevation[300]};

  animation: ${fade} 500ms linear;

  &:hover {
    box-shadow: ${({ theme }) => theme.elevation[300]};
  }

  &.${notifyClassnames.closeButtonAnimationOut} {
    opacity: 0;
  }

  ${({ theme }) => theme.breakpoints.down('sm')} {
    width: calc(100% - ${({ theme }) => theme.spacing(4)});
    margin: ${({ theme }) => theme.spacing(0, 5, 2, 5)};
  }
`;
