import styled, { keyframes, css } from "styled-components";
import { useEffect, useState, useRef } from 'react'

export const EVENTS = {
    START: 'start',
    HALF_PASSED: 'half-passed',
    COMPLETED: 'completed',
}

export const DISPATCH_WIPE_OUT_START_EVENT = () => {
    window.dispatchEvent(new Event(EVENTS.START));
}

export const SPEED = 3000;

function WipeoutTransition() {
    const [isAnimating, setIsAnimating] = useState(false);
    const maskRef = useRef(null);
    
    useEffect(() => {
        window.addEventListener(EVENTS.START, () => {
            setIsAnimating(true);

            setTimeout(() => {
                window.dispatchEvent(new Event(EVENTS.HALF_PASSED));
            }, SPEED - 1000);

            setTimeout(() => {
                window.dispatchEvent(new Event(EVENTS.COMPLETED));
                setIsAnimating(false);
            }, SPEED);
        });
    }, [])

    return (
        <StyledContainer $isAnimating={isAnimating}>
            <div className="mask" ref={maskRef} />
        </StyledContainer>
    );
}

const wipeoutAnimation = keyframes`
    0% {
        transform: translateX(100%);
    }
    100% {
        transform: translateX(-100%);
    }
`;


const StyledContainer = styled.div`
    position: absolute;
    inset: 0;
    z-index: 1000;

    opacity: 0;
    pointer-events: none;
    overflow: hidden;
    border-radius: 32px;


    ${({ $isAnimating }) =>
        $isAnimating &&
        css`
            opacity: 1;

            .mask {
                animation: ${wipeoutAnimation} ${SPEED}ms linear infinite;
            }
        `}

    .mask {
        position: absolute;
        left: 0%;
        width: 240%;
        height: 100%;
        background-image: linear-gradient(
            to right,
            transparent 0%,
            rgba(255, 223, 90, 1) 10%,
            rgba(255, 223, 90, 1) 90%,
            transparent
        );

        transform: translateX(100%);
    }
`;

export default WipeoutTransition;