import styled from 'styled-components'
import { DISPATCH_PLAY_DIALOG, EVENTS } from '../Dialog';
import { useEffect, useRef } from 'react'
import { useGameContext, GAME_STATES } from '..';
import { DISPATCH_STOP_MUSIC } from '../AudioController';
import { DISPATCH_GAME_END_EVENT } from '../index';
import { ImageWrapper } from '../../../components/MediaWrapper';

const DIALOGS = [
    `經過一夜狂風暴雨，風雨終於在天快亮的時候減緩了。平日的溫馨小鎮，在颱風的侵襲下滿目瘡痍。`,
    `這時你才意識到，\n防颱準備如此重要，絕對是不能忽略的⋯⋯`,
];

function Ending() {
    const currentDialogRef = useRef(0);
    const { setGameCurrentState, saveChaterData } = useGameContext();

    useEffect(() => {
        DISPATCH_GAME_END_EVENT();

        setTimeout(() => {
            DISPATCH_PLAY_DIALOG(DIALOGS[currentDialogRef.current]);
        }, 400);

        const handleEvent = () => {
            if (currentDialogRef.current < DIALOGS.length - 1) {
                currentDialogRef.current++;
                DISPATCH_PLAY_DIALOG(DIALOGS[currentDialogRef.current]);
            } else {
                DISPATCH_PLAY_DIALOG(null);
                saveChaterData();
                DISPATCH_STOP_MUSIC();
                setGameCurrentState(GAME_STATES.LOAD_RESULT);
            }
        }

        document.addEventListener(EVENTS.NEXT_DIALOG, handleEvent);

        return () => {
            document.removeEventListener(EVENTS.NEXT_DIALOG, handleEvent)
        }
    }, []);

    return (
        <StyledContainer>
            <ImageWrapper src="/images/game/ending.webp" m_src="/images/game/ending-m.webp" />
        </StyledContainer>
    );
}

const StyledContainer = styled.div`
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;

    img {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
`;

export default Ending;