
import ChapterCover from "../ChapterCover";
import { useState, useRef, useEffect, useMemo } from "react";
import BorderShadowButton, { GoButton, THEMES } from "../../../components/BorderShadowButton";
import styled, { keyframes } from "styled-components";
import GameObjectModal from "../GameObjectModal";
import { Cart } from "../../../components/Icons";
import CardModal from "./CartModal";
import GAME_OBJECTS from './GAME_OBJECTS'
import { useGameContext, GAME_STATES } from "..";
import DoneModal from "./DoneModal";
import { DISPATCH_STOP_MUSIC } from "../AudioController";
import { ImageWrapper } from "../../../components/MediaWrapper";
import getPathPrefix from '../../../utils/getPathPrefix'
import MobileGameUI from "../MobileGameUI";
import { respondTo, useMediaSelectTo, breakpoints } from "../../../utils/responsive";
import CatPawIntro from "../CatPawIntro";
import GameContentFrame from "../GameContentFrame";
import GameUI from "../GameUI";
import Background from "../Background";


const CHAPTER_STATES = {
    COVER: "cover",
    INTRO: "intro",
    GAME: "game",
    PAUSE: "pause",
}

const COUNTDOWN = 60; // seconds


function Chapter2() {
    const { endChapter } = useGameContext();
    const [currentState, setCurrentState] = useState(CHAPTER_STATES.COVER);
    const [selectedObject, setSelectedObject] = useState(null);
    const [cart, setCart] = useState([]);
    const [isCartModalOpen, setIsCartModalOpen] = useState(false);
    const dropItemRef = useRef(null);
    const backToShelfRef = useRef(null);

    const isMobile = useMediaSelectTo(breakpoints.sm);
    const mobileGameFrameRef = useRef(null);
    const scrollHintRef = useRef(null);
    const isScrollHintShown = useRef(false);

    const [isDone, setIsDone] = useState(false);
    const [isTimerFinished, setIsTimerFinished] = useState(false);
    const [hoveredObjectId, setHoveredObjectId] = useState(null);
    const hiddenObjectIds = useMemo(() => new Set(cart.map((item) => item.id)), [cart]);

    const handleTimerFinished = () => {
        setIsTimerFinished(true);
        showDoneModal();
    }


    const handleObjectSelect = (objectName) => {
        setSelectedObject(GAME_OBJECTS[objectName]);
    };

    const handleAddToCard = () => {
        setCart([...cart, selectedObject]);
        playAddToCardAnimation(selectedObject);
        setSelectedObject(null);
    };

    const playAddToCardAnimation = async (object) => {
        const dropItem = dropItemRef.current;
        const image = getPathPrefix(object?.image);

        dropItem.style.backgroundImage = `url(${image})`;
        dropItem.classList.add("drop-item-active");

        const TIMEOUT = window.innerWidth > breakpoints.sm ? 980 : 580;

        return new Promise(resolve => {
            setTimeout(() => {
                dropItem.classList.remove("drop-item-active");
                dropItem.style.backgroundImage = `none`;
                resolve();
            }, TIMEOUT);
        });
    }

    const playAddBackToShopAnimation = (items) => {
        return new Promise(resolve => {
            const backToShelf = backToShelfRef.current;

            items.forEach((item, index) => {
                const img = document.createElement("img");
                img.src = getPathPrefix(item.image);
                img.alt = item.title;
                // rotate random deg, from -20~20 using crypto (但其實 Math.random() 就夠用了)
                const array = new Uint32Array(1);
                window.crypto.getRandomValues(array);
                // 將亂數轉換到 0 ~ 1，再乘 40 就得到 0~40，再減20變成 -20~20
                const randomDegree = (array[0] / 0xFFFFFFFF) * 40 - 20;
                img.style.transform = `rotate(${randomDegree}deg)`;
                img.style.transitionDelay = `${index * 0.2}s`;
                backToShelf.appendChild(img);
            })

            backToShelf.classList.add("back-to-shelf-active");

            const totalDelay = items.length * (0.3 - 0.1);

            setTimeout(() => {
                backToShelf.classList.remove("back-to-shelf-active");
            }, 200)

            setTimeout(() => {
                backToShelf.innerHTML = "";
                resolve();
            }, totalDelay * 1000 + 100);
        });
    }

    const openCartModal = () => {
        setIsCartModalOpen(true);

        setCurrentState(CHAPTER_STATES.PAUSE);
    }

    const handleObjectMouseEnter = (objectName) => {
        setHoveredObjectId(objectName);
    };

    const handleObjectMouseLeave = () => {
        setHoveredObjectId(null);
    };

    const handleCartClose = (updatedCart) => {
        if (updatedCart.length !== cart.length) {
            let removedItems = [];
            cart.forEach((item) => {
                // if is not in updatedCart, add to removedItems
                if (!updatedCart.includes(item)) {
                    removedItems.push(item);
                }
            })
            playAddBackToShopAnimation(removedItems);

            setCart(updatedCart);
        }
        setIsCartModalOpen(false);
        setCurrentState(CHAPTER_STATES.GAME);
    }

    const showDoneModal = () => {
        setCurrentState(CHAPTER_STATES.PAUSE);
        setIsDone(true);
    };

    const handleEndGame = () => {
        endChapter("chapter2", cart, GAME_STATES.CHAPTER3, true);
        DISPATCH_STOP_MUSIC();
    };


    const showScrollHintAndHide = () => {
        if (isScrollHintShown.current) return;
        isScrollHintShown.current = true;
        scrollHintRef.current.classList.add("is--in");

        const hideScrollHint = () => {
            if (!scrollHintRef.current) return;
            if (scrollHintRef.current.classList.contains("is--in")) {
                scrollHintRef.current.classList.remove("is--in");
            }
        };

        setTimeout(() => {
            hideScrollHint();
        }, 2000);

        const frameWrapper =
            mobileGameFrameRef.current.querySelector(".frame-wrapper");
        frameWrapper.addEventListener("touchstart", hideScrollHint);
    };


    useEffect(() => {
        const gameFrame = mobileGameFrameRef.current;

        if (typeof isMobile === "boolean" && isMobile) {
            const gameWidth = window.innerWidth - 32;
            const gameLayer = document.querySelector(".frame-wrapper");
            const gameLayerWidth = gameLayer.clientWidth;
            const scrollLeft = (gameLayerWidth - gameWidth) / 2;

            // set gameFrame scrollLeft to center, not use scrollTo
            gameFrame.scrollLeft = scrollLeft;
        }
    }, [isMobile]);

    
    return (
        <>
            {/* <CatPawCursor /> */}
            <GameObjectModal
                onClose={() => {
                    setSelectedObject(null);
                    setCurrentState(CHAPTER_STATES.GAME);
                }}
                isOpen={selectedObject !== null}
                number={selectedObject?.number}
                image={selectedObject?.image}
                title={selectedObject?.title}
                description={selectedObject?.description}
                button={
                    <BorderShadowButton
                        onClick={handleAddToCard}
                        text="加入購物車"
                        size="s"
                        theme={THEMES.DARK}
                    />
                }
            />
            <CardModal
                isOpen={isCartModalOpen}
                onClose={handleCartClose}
                items={cart}
            />
            <DoneModal
                isOpen={isDone}
                onClose={() => {
                    setCurrentState(CHAPTER_STATES.GAME);
                    setIsDone(false);
                }}
                onNext={handleEndGame}
                canClose={isTimerFinished === false}
            />
            <StyledContainer>
                {currentState === CHAPTER_STATES.COVER && (
                    <ChapterCover
                        cover="/images/game/chapter2/intro.webp"
                        cover_m="/images/game/chapter2/intro-m.webp"
                        chapterIndex={2}
                        mainTitle="災前購物"
                        subTitle="趁現在雨勢還小，得趕緊去超市採買防災用品"
                        className="chapter-cover"
                        btnText="開始採購"
                        onNextClick={() =>
                            setCurrentState(CHAPTER_STATES.INTRO)
                        }
                    />
                )}
                <CatPawIntro
                    image="/images/game/chapter2/intro.png"
                    className="cat-paw-intro"
                    isIn={currentState === CHAPTER_STATES.INTRO}
                    onClick={() => {
                        setCurrentState(CHAPTER_STATES.GAME);
                        if (window.innerWidth <= breakpoints.sm) {
                            showScrollHintAndHide();
                        }
                    }}
                />
                {isMobile && (
                    <MobileGameUI
                        isShow={currentState !== CHAPTER_STATES.COVER}
                        isTutorialModalOpen={currentState === CHAPTER_STATES.INTRO}
                        timerShouldStart={currentState === CHAPTER_STATES.GAME}
                        onTimerFinished={handleTimerFinished}
                        timerSeconds={COUNTDOWN}
                        openTutorial={() =>
                            setCurrentState(CHAPTER_STATES.INTRO)
                        }
                    />
                )}
                <GameView ref={mobileGameFrameRef}>
                    <GameContentFrame>
                        <Background
                            className="bg"
                            bg="/images/game/chapter2/bg.webp"
                            bg_m="/images/game/chapter2/bg.webp"
                        />
                        {Object.entries(GAME_OBJECTS).map(([objectKey, object]) => (
                            <button
                                key={objectKey}
                                type="button"
                                className={`layer layer-${object.id} object-layer${hoveredObjectId === object.id ? " hover" : ""}${hiddenObjectIds.has(object.id) ? " hide" : ""}`}
                                style={{
                                    left: `${(object.position.x / 1920) * 100}%`,
                                    top: `${(object.position.y / 1080) * 100}%`,
                                    width: `${(object.size?.width / 1920) * 100}%`,
                                    height: `${(object.size?.height / 1080) * 100}%`,
                                }}
                                onClick={() => handleObjectSelect(object.id)}
                                onMouseEnter={() => handleObjectMouseEnter(object.id)}
                                onMouseLeave={handleObjectMouseLeave}
                            >
                                <img
                                    className="default"
                                    src={getPathPrefix(object.status?.default ?? object.image)}
                                    alt=""
                                />
                            </button>
                        ))}
                        <div className="scroll-hint" ref={scrollHintRef}>
                            <ImageWrapper src="/images/game/scroll-hint.png" />
                        </div>
                    </GameContentFrame>
                    <GameUI
                        gameState={currentState}
                        isMobile={isMobile}
                        COUNTDOWN={COUNTDOWN}
                        CHAPTER_STATES={CHAPTER_STATES}
                        handleTimerFinished={handleTimerFinished}
                        openTutorial={() =>
                            setCurrentState(CHAPTER_STATES.INTRO)
                        }
                    />
                    <BorderShadowButton
                        className="cart-button"
                        text="查看購物車"
                        size="s"
                        theme={THEMES.WHITE}
                        icon={<Cart />}
                        onClick={openCartModal}
                    />
                    <DropItem ref={dropItemRef}></DropItem>
                    <BackToShelf ref={backToShelfRef} />
                    <BasketImage
                        src={getPathPrefix("/images/game/chapter2/basket.png")}
                    />
                    <GoButton
                        className="finish-button"
                        text="確定結帳"
                        size="s"
                        theme={THEMES.DARK}
                        onClick={showDoneModal}
                    />
                </GameView>
            </StyledContainer>
        </>
    );
}

const StyledContainer = styled.div`
    width: 100%;
    height: 100%;
    cursor: none;

    .chapter-cover {
        z-index: 2;
    }
`;

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

    .game-bg {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    .scroll-hint {
        display: block;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 10;

        opacity: 0;
        pointer-events: none;
        z-index: 10;

        transition: opacity 0.2s ease-out;

        width: 100%;
        height: 100%;

        display: flex;
        justify-content: center;
        align-items: center;
        backdrop-filter: blur(2px);

        img {
            width: 268px;
            height: 34px;
        }

        &.is--in {
            opacity: 1;
            pointer-events: auto;
        }
    }

    .cart-button {
        cursor: none;
        position: absolute;
        bottom: 28px;
        left: 28px;
        z-index: 1;

        ${respondTo.sm} {
            left: 24px;
        }
    }

    .finish-button {
        cursor: none;
        position: absolute;
        bottom: 28px;
        right: 28px;

        ${respondTo.sm} {
            right: 24px;
        }
    }

    .layer {
        position: absolute;

        pointer-events: none;
        transition: opacity 0.2s ease-out;
        z-index: 2;

        .default {
            pointer-events: none;
        }

        .button {
            pointer-events: auto;
        }

        &.hover {
            .default,
            .done {
                filter: drop-shadow(1px 2px 0px #4d4d4d)
                    drop-shadow(7px 7px 0px #ff7424)
                    drop-shadow(-5px -2px 0px #ffd45c);
            }

            ${respondTo.sm} {
                .default,
                .done {
                    filter: none;
                }
            }
        }

        &.hide {
            opacity: 0;
            pointer-events: none;

            .button {
                pointer-events: none;
            }
        }
    }

    .object-layer {
        pointer-events: auto;
        border: 0;
        background: transparent;
        padding: 0;
        cursor: none;

        img {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: fill;
            pointer-events: none;
        }
    }
`;

const BasketImage = styled.img`
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    pointer-events: none;

    ${respondTo.sm} {
        left: 50%;
        top: 50%;
        transform: translate(-50%, -54%);

        width: 816px;
        height: 460px;
    }

    
`;

const dropItemAnimation = keyframes`
    from {
         transform: translate(-50%, 0) rotate(10deg);
    }

    60% {
        transform: translate(-50%, 0) rotate(10deg);
    }

    to {
         transform: translate(-50%, 200%) rotate(10deg);
    }

`;

const dropItemAnimationMobile = keyframes`
    from {
         transform: translate(-50%, 0) rotate(10deg);
    }

    60% {
        transform: translate(-50%, 0) rotate(10deg);
    }

    to {
         transform: translate(-50%, 80px) rotate(10deg);
    }


`;

const DropItem = styled.div`
    position: absolute;
    left: 50%;
    bottom: 30%;
    transform: translateX(-50%);

    --size: 160px;
    width: var(--size);
    height: var(--size);
    z-index: 2;

    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;

    pointer-events: none;
    opacity: 0;
    transition: opacity 0.2s ease-out;


    &.drop-item-active {
        opacity: 1;
        animation: ${dropItemAnimation} 1s ease-out 1;

        ${respondTo.sm} {
            animation: ${dropItemAnimationMobile} 0.6s ease-out 1;
        }
    }
`;


const BackToShelf = styled.div`
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 2;

    pointer-events: none;

    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    width: 320px;
    gap: 0;

    img {
        --size: 140px;
        width: var(--size);
        height: var(--size);
        object-fit: cover;

        opacity: 0;
        transform: scale(0);
        transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        margin: -40px;
    }

    &.back-to-shelf-active {
        img {
            opacity: 1;
            transform: scale(1);        }
    }
`;

export default Chapter2;
