import styled, { keyframes, css } from "styled-components";
import ChapterCover from "../ChapterCover";
import { useState, useEffect, useRef } from "react";
import { useGameContext, GAME_STATES } from "..";
import { ImageWrapper } from "../../../components/MediaWrapper";
import getPathPrefix from "../../../utils/getPathPrefix";
import { respondTo } from "../../../utils/responsive";
import CatPawCursor from "../CatPawCursor";
import Background from "../Background";

const CHAPTER_STATES = {
    COVER: "cover",
    GAME: "game",
}

const STICKERS = [
    {
        value: "非常",
        src: "/images/game/chapter4/stickers/1.gif",
    },
    {
        value: "小怕",
        src: "/images/game/chapter4/stickers/2.gif",
    },
    {
        value: "有點",
        src: "/images/game/chapter4/stickers/3.gif",
    },
    {
        value: "完全不",
        src: "/images/game/chapter4/stickers/4.gif",
    },
]

const DIALOG_OPTIONS = [
    {
        value: "A. 我想留在家不撤離",
    },
    {
        value: "B. 感覺有點危險，撤離！！！",
    },
];

function Chapter4() {
    const { endChapter } = useGameContext();
    const [gameCurrentState, setGameCurrentState] = useState(CHAPTER_STATES.COVER);
    const [currentLayerState, setCurrentLayerState] = useState(null);
    const [currentHoveringSticker, setCurrentHoveringSticker] = useState(null);
    const [currentSelectedSticker, setCurrentSelectedSticker] = useState(null);
    const [currentSelectedOption, setCurrentSelectedOption] = useState(null);
    const userStickerRef = useRef(null);

    useEffect(() => {

        if (currentLayerState === 0) {
            setTimeout(() => {
                setCurrentLayerState(1);
            }, 1000);
        }

        if (currentLayerState === 1) {
            setTimeout(() => {
                setCurrentLayerState(2);
            }, 1000);
        }

        if (currentLayerState === 3) {
            setTimeout(() => {
                setCurrentLayerState(4);
            }, 1000);
        }

        if (currentLayerState === 4) {
            setTimeout(() => {
                setCurrentLayerState(5);
            }, 2000);
        }

    }, [currentLayerState]);

    useEffect(() => {
        if (gameCurrentState !== CHAPTER_STATES.GAME) return;
        setCurrentLayerState(0);
    }, [gameCurrentState])

    const handleStickerClick = (sticker) => {
        const stickerImg = document.createElement("img");
        stickerImg.src = getPathPrefix(sticker.src);
        userStickerRef.current.appendChild(stickerImg);

        setCurrentLayerState(3);
        setCurrentSelectedSticker(sticker);
    }

    const selectOption = (index) => {
        setCurrentSelectedOption(index);  
        endChapter('chapter4', {
            sticker: currentSelectedSticker,
            option: DIALOG_OPTIONS[index].value,
            branch: index === 0 ? "a" : "b",
        }, GAME_STATES.CHAPTER4_TRANSITION)
    }

    return (
        <StyledContainer>
            {/* <CatPawCursor /> */}
            {gameCurrentState === CHAPTER_STATES.COVER && (
                <ChapterCover
                    className="chapter-cover"
                    cover="/images/game/chapter4/cover.webp"
                    cover_m="/images/game/chapter4/cover-m.webp"
                    mainTitle={`災害意識\n與撤離行為`}
                    chapterIndex={4}
                    subTitle="在家裡滑手機，收到朋友訊息， 和來自村里長通知！？"
                    btnText="趕緊查看"
                    onNextClick={() => setGameCurrentState(CHAPTER_STATES.GAME)}
                />
            )}
            <Background className="bg" bg="/images/game/chapter4/bg.webp" bg_m="/images/game/chapter4/bg.jpg" />
            {gameCurrentState === CHAPTER_STATES.GAME && (
                <GameView $state={currentLayerState}>
                    <div className="frame">
                        <Layers>
                            <ImageWrapper
                                className="layer layer-mobile"
                                src="/images/game/chapter4/mobile.png"
                                alt=""
                            />
                            <ImageWrapper
                                className="layer layer-message"
                                src="/images/game/chapter4/friend-message.png"
                                alt=""
                            />
                            <ImageWrapper
                                className="layer layer-white-bg"
                                src="/images/game/chapter4/white-bg.png"
                                alt=""
                            />
                            <ImageWrapper
                                className="layer layer-alert"
                                src="/images/game/chapter4/alert.png"
                                alt=""
                            />
                            <div className="hint">
                                <p>
                                    選擇想要傳
                                    <br />
                                    送的貼圖
                                </p>
                            </div>
                        </Layers>
                        <UserInput>
                            <ImageWrapper
                                className="user-bg"
                                src={`/images/game/chapter4/user-input.png`}
                                alt=""
                            />
                            <div
                                className={`panel ${
                                    currentHoveringSticker ? "hover" : ""
                                }`}
                            >
                                <div
                                    className="user-sticker"
                                    ref={userStickerRef}
                                ></div>
                                {STICKERS.map((sticker) => (
                                    <button
                                        key={sticker.value}
                                        onClick={() =>
                                            handleStickerClick(sticker)
                                        }
                                        onMouseEnter={() =>
                                            setCurrentHoveringSticker(sticker)
                                        }
                                        onMouseLeave={() =>
                                            setCurrentHoveringSticker(null)
                                        }
                                        className={`${
                                            currentHoveringSticker?.value ===
                                            sticker.value
                                                ? "current"
                                                : ""
                                        } ${
                                            currentSelectedSticker?.value ===
                                            sticker.value
                                                ? "selected"
                                                : ""
                                        }`}
                                    >
                                        <ImageWrapper
                                            src={sticker.src}
                                            alt={sticker.value}
                                        />
                                    </button>
                                ))}
                            </div>
                        </UserInput>
                    </div>
                    <Dialog className="dialog">
                        <div className="dialog-content">
                            <ImageWrapper
                                className="avatar"
                                src="/images/game/chapter4/dialog-avatar.png"
                                m_src="/images/game/chapter4/dialog-avatar-m.png"
                                alt=""
                            />
                            <p>村里長的撤離通知發布得好緊急，我該去嗎？</p>
                            <div className="options">
                                {DIALOG_OPTIONS.map((option, index) => (
                                    <button
                                        key={option.value}
                                        className={
                                            currentSelectedOption === index
                                                ? "selected"
                                                : ""
                                        }
                                        onClick={() => selectOption(index)}
                                    >
                                        {option.value}
                                    </button>
                                ))}
                            </div>
                        </div>
                    </Dialog>
                </GameView>
            )}
        </StyledContainer>
    );
}

const StyledContainer = styled.div`
    width: 100%;
    height: 100%;
    position: relative;
    background: white;

    * {
        cursor: none;
    }

    .chapter-cover {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1;
    }

    .bg {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;

        opacity: 0.4;
    }
`;

const slideIn = keyframes`
    from {
        transform: translateY(10%);
    }
    to {
        transform: translateY(0);
    }
`;

const getStateStyle = (state) => {
    switch (state) {
        case 0:
            return css``;
        case 1:
            return css`
                .layer-message {
                    opacity: 1;
                }
            `;
        case 2:
            return css`
                .layer-message {
                    opacity: 1;
                }

                .hint {
                    opacity: 1;
                }

                .panel {
                    opacity: 1;
                    pointer-events: auto;

                    &.hover {
                        button {
                            opacity: 0.5;

                            &.current {
                                opacity: 1;
                            }
                        }
                    }
                }
            `;
        case 3:
            return css`
                .layer-message {
                    opacity: 1;
                    transform: translateY(-60px);

                    ${respondTo.sm} {
                        transform: translate(-50%, calc(-50% - 30px)) !important;
                    }
                }

                .hint {
                    opacity: 0;
                }

                .panel {
                    opacity: 1;

                    button {
                        opacity: 0.5;
                        pointer-events: none;

                        &.selected {
                            opacity: 1;
                        }
                    }
                }
            `;
        case 4:
            return css`
                .layer-message {
                    opacity: 1;
                    transform: translateY(-60px);

                    ${respondTo.sm} {
                        transform: translate(
                            -50%,
                            calc(-50% - 30px)
                        ) !important;
                    }
                }

                .layer-alert {
                    opacity: 1;
                    animation: ${alertSlideIn} 0.5s ease-in-out;
                }

                .panel {
                    opacity: 1;

                    button {
                        opacity: 0.5;
                        pointer-events: none;

                        &.selected {
                            opacity: 1;
                        }
                    }
                }
            `;
        case 5:
            return css`
                .layer-message {
                    opacity: 1;
                    transform: translateY(-60px);

                    ${respondTo.sm} {
                        transform: translate(-50%, calc(-50% - 30px)) !important;
                    }
                }

                .layer-alert {
                    opacity: 1;
                    animation: ${alertSlideIn} 0.5s ease-in-out;
                }

                .panel {
                    opacity: 1;

                    button {
                        opacity: 0.5;
                        pointer-events: none;

                        &.selected {
                            opacity: 1;
                        }
                    }
                }

                .dialog {
                    opacity: 1;
                    pointer-events: auto;

                    .dialog-content {
                        opacity: 1;
                        transition-delay: 0.2s;
                        transition: all 0.2s ease-out;
                        transform: translate(-50%, 0%);
                    }
                }
            `;
        default:
            return;
    }
}

const GameView = styled.div`
    width: 100%;
    height: 100%;

    position: absolute;
    left: 0;
    top: 0;

    animation: ${slideIn} 0.5s ease-in-out;

    .layer-message {
        opacity: 0;
    }

    .layer-alert {
        opacity: 0;
    }

    .hint {
        opacity: 0;
    }

    .panel {
        opacity: 0.5;
        pointer-events: none;

    }

    .dialog {
        opacity: 0;
        pointer-events: none;

        .dialog-content {
            opacity: 0;
            transform: translate(-50%, 4%);
        }
    }

    ${({ $state }) => getStateStyle($state)}

    ${respondTo.sm} {
        .frame {
            width: 610px;
            height: 310px;

            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
    }
`;


const arrowBounce = keyframes`
  0%,
  20%,
  50%,
  80%,
  100% {
    -webkit-transform: translateX(0);
    transform: translateX(0);
  }
  40% {
    -webkit-transform: translateX(-20px);
    transform: translateX(-20px);
  }
  60% {
    -webkit-transform: translateX(-10px);
    transform: translateX(-10px);
  }
`;

const arrowBounceSm = keyframes`
    0%,
  20%,
  50%,
  80%,
  100% {
    -webkit-transform: rotate(90deg) translateX(0);
    transform: rotate(90deg) translateX(0);
  }
  40% {
    -webkit-transform: rotate(90deg) translateX(-10px);
    transform: rotate(90deg) translateX(-10px);
  }
  60% {
    -webkit-transform: rotate(90deg) translateX(-4px);
    transform: rotate(90deg) translateX(-4px);
  }
`;

const alertSlideIn = keyframes`
    from {
        opacity: 0;
        transform: translateY(-4px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
`;

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

    .layer {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;

        ${respondTo.sm} {
            width: 606px;
            height: 310px;
            

            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
    }

    .hint {
        position: absolute;
        right: 32px;
        bottom: 32px;

        display: flex;
        gap: 8px;
        align-items: center;
        font: var(--headline-6);
        color: var(--neutrals-700);

        img {
            animation: ${arrowBounce} 2s infinite;
        }

        ${respondTo.sm} {

            right: unset;
            left: 50%;
            bottom: -40px;

            transform: translate(-50%, 100%);

            flex-direction: column;
            gap: 12px;
            font: var(--mobile-headline-6);

            br {
                display: none;
            }

            img {
                animation: ${arrowBounceSm} 2s infinite;
            }
        }
    }




`;

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

    .user-bg {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;

    }

    .panel {
        position: absolute;
        width: 410px;
        height: 110px;

        left: 50%;
        bottom: 10px;
        transform: translateX(-50%);

        display: grid;
        grid-template-columns: repeat(4, 1fr);

        ${respondTo.sm} {
            bottom: 0;
            width: 50%;
            padding: 0 16px;

            height: unset;
        }

        button {
            display: flex;
            justify-content: center;
            align-items: center;

            // opacity: 0.5;

            img {
                width: 100%;
                height: 100%;
                object-fit: contain;

                ${respondTo.sm} {
                    --size: 54px;
                    width: var(--size);
                    height: var(--size);
                }
            }

            &:hover {
                opacity: 1;
            }
        }
    }

    .user-sticker {
        position: absolute;
        right: 20px;
        top: -140px;

        --size: 100px;
        width: var(--size);
        height: var(--size);

        ${respondTo.sm} {
            --size: 54px;
            top: -94px;
        }

        img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
    }
`;

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

    z-index: 2;

    background: rgba(0, 0, 0, 0.2);
    backdrop-filter: blur(2px);

    .dialog-content {
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translate(-50%, 0);

        background-image: url(${getPathPrefix("/images/game/dialog-bg.png")});
        background-size: 100% 100%;
        box-shadow: 6px 6px 0px 0px #2b3247;
        border: 6px solid vaR(--neutrals-700);
        border-radius: 20px 20px 0 0;

        width: 744px;
        padding: 44px 56px;

        font: var(--headline-6);
        color: var(--neutrals-700);

        ${respondTo.sm} {
            width: calc(100% - 32px);
            padding: 40px 32px;

            font: var(--mobile-headline-6);
        }
    }

    .avatar {
        position: absolute;
        left: 20px;
        top: -74px;

        ${respondTo.sm} {
            top: -54px;

            width: 122px;
            height: 68px;
        }

    }

    .options {
        display: flex;
        flex-direction: column;
        gap: 12px;
        margin-top: 16px;

        button {
            border-radius: 12px;
            border: 2px solid var(--neutrals-700);
            background: white;
            font: var(--paragraph-2);
            font-weight: 700;

            padding: 8px 24px;

            ${respondTo.sm} {
                font-size: 14px;
            }

            &:hover,
            &.selected {
                background: var(--main-color-b);
            }
        }
    }
`;

export default Chapter4;

