import styled from 'styled-components';
import { useGameContext, GAME_STATES } from '..';
import TransitionMask from '../TransitionMask';
import { useRef, useState, useEffect } from 'react';
import BorderShadowButton, { THEMES} from '../../../components/BorderShadowButton';
import { GoArrow } from '../../../components/Icons';
import { DISPATCH_PLAY_MUSIC } from '../AudioController';
import { ImageWrapper } from '../../../components/MediaWrapper';
import { respondTo } from '../../../utils/responsive';

const TIMER = 5000;

function Chapter1Transition() {
    const { wipeOutAndStartNextChapter } = useGameContext();
    const transitionMaskRef = useRef(null);
    const [isClicked, setIsClicked] = useState(false);

    const handleClick = () => {
        if (isClicked) return;
        setIsClicked(true);
        transitionMaskRef.current.play();
    }

    const handleNext = () => {
        wipeOutAndStartNextChapter(GAME_STATES.CHAPTER2);
    }

    useEffect(() => {
        DISPATCH_PLAY_MUSIC("/audios/02.mp3");

        let timer = setTimeout(() => {
            setIsClicked(true);
            transitionMaskRef.current.play();
        }, TIMER);

        return () => clearTimeout(timer);
    }, []);

    return (
        <StyledContainer onClick={handleClick}>
            <ImageWrapper
                className="transition-video"
                src="/images/game/chapter1/transition.webp"
                m_src="/images/game/chapter1/transition-m.webp"
            />
            <TransitionMask
                ref={transitionMaskRef}
                endingView={
                    <FinalText>
                        <p>
                            什麼？？颱風突然說來就來？
                            <br />
                            現在出門採買防災用品吧！
                        </p>
                        <BorderShadowButton
                            text="趕緊出門"
                            icon={<GoArrow />}
                            theme={THEMES.LIGHT}
                            size="s"
                            onClick={handleNext}
                            rotateText={false}
                        />
                    </FinalText>
                }
            />
        </StyledContainer>
    );
}

const StyledContainer = styled.div`
    width: 100%;
    height: 100%;
    background-color: #eee;
    color: #fff;

    .transition-video {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
`;

const FinalText = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 48px;

    width: 100%;
    height: 100%;

    color: #fff;
    font: var(--paragraph-1);
    text-align: center;

    ${respondTo.sm} {
        gap: 24px;
        font: var(--mobile-paragraph-1);
    }
`;

export default Chapter1Transition;
