import styled from "styled-components";
import { DISPATCH_PLAY_DIALOG, EVENTS } from "../Dialog";
import { useRef, useEffect, useMemo } from 'react';
import { GAME_STATES, useGameContext } from "..";
import { ImageWrapper } from "../../../components/MediaWrapper";

const DIALOGS_A = [
    `外面風雨越來越大，前往避難中心的路上仍可能遇到不小的風雨，\n因此你選擇留在家中，不冒險外出。`,
    `然而風雨到了半夜越來越強，突然！水從門縫淹了進來，才一個瞬間就淹到膝蓋了！`,
];

const DIALOGS_B = [
    `你揹起提前準備好的防災包，趁雨勢變小的時候，\n趕緊前往活動中心避難。`,
    `「這次颱風好嚴重啊！」看著時強時弱的風雨、偶爾閃爍的電燈，\n你慶幸有聽從里長的指示撤離到活動中心，和大家在一起更放心一些。`,
];

function Chapter4BranchA() {
    const { chapterState, setGameCurrentState } = useGameContext();
    const currentDialogRef = useRef(0);

    const materials = useMemo(() => {
        if (!chapterState?.chapter4) return;
        const branch = chapterState.chapter4.branch
        const dialogs = branch === "a" ? DIALOGS_A : DIALOGS_B;
        const videoBG = `/images/game/chapter4/branch-${branch}${window.innerWidth < 568 ? "-m" : ""}.webp`;
        return {
            videoBG,
            dialogs
        }
    }, [chapterState])


    useEffect(() => {
        if (!materials) return;
        setTimeout(() => {
            DISPATCH_PLAY_DIALOG(materials.dialogs[currentDialogRef.current]);
        }, 400);

        const handleEvent = () => {
            if (currentDialogRef.current < materials.dialogs.length - 1) {
                currentDialogRef.current++;
                DISPATCH_PLAY_DIALOG(
                    materials.dialogs[currentDialogRef.current]
                );
            } else {
                DISPATCH_PLAY_DIALOG(null);
                setGameCurrentState(GAME_STATES.ENDING);
            }
        }

        document.addEventListener(EVENTS.NEXT_DIALOG, handleEvent);

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

    if (!materials) return null;

    return (
        <StyledContainer>
            <ImageWrapper src={materials.videoBG} />
        </StyledContainer>
    );
}

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

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

export default Chapter4BranchA;
