import styled from 'styled-components';
import TutorialModal from './TutorialModal';
import { useState, useEffect, useRef } from 'react';
import { EVENTS } from '../WipeoutTransition';
import getPathPrefix from '../../../utils/getPathPrefix';
import { useGameContext, GAME_STATES } from '../index';

function TutorialView() {

    const [isOpen, setIsOpen] = useState(false);
    const { wipeOutAndStartNextChapter } = useGameContext();
    const openModalTimeoutRef = useRef(null);

    const clearOpenModalTimeout = () => {
        if (openModalTimeoutRef.current != null) {
            clearTimeout(openModalTimeoutRef.current);
            openModalTimeoutRef.current = null;
        }
    };

    useEffect(() => {

        const start = () => {
            clearOpenModalTimeout();
            openModalTimeoutRef.current = setTimeout(() => {
                openModalTimeoutRef.current = null;
                setIsOpen(true);
            }, 1000);
        };

        start();


        window.addEventListener(EVENTS.COMPLETED, start);

        return () => {
            clearOpenModalTimeout();
            window.removeEventListener(EVENTS.COMPLETED, start);
        }
    }, []);

    const handleClose = () => {
        clearOpenModalTimeout();
        setIsOpen(false);
        wipeOutAndStartNextChapter(GAME_STATES.CHAPTER1);
    }

    return (
        <StyledContainer>
            <TutorialModal isOpen={isOpen} onClose={handleClose} />
        </StyledContainer>
    );
}

const StyledContainer = styled.div`
    width: 100%;
    height: 100%;
    background: url(${getPathPrefix("/images/game/tutorial-bg.jpg")}) no-repeat
        center center;
    background-size: cover;
`;

export default TutorialView; 