import styled from "styled-components";
import { useState, useEffect, useRef } from 'react';
import ChapterCover from "../ChapterCover";
import GameObjectModal from "../GameObjectModal";
import GAME_OBJECTS from "./GAME_OBJECTS";
import BorderShadowButton, { THEMES } from "../../../components/BorderShadowButton";
import { GoArrow } from "../../../components/Icons";
import DoneModal from "./DoneModal";
import { useGameContext, GAME_STATES } from "..";
import { ImageWrapper } from "../../../components/MediaWrapper";
import { breakpoints, respondTo, useMediaSelectTo } from "../../../utils/responsive";
import CatPawIntro from "../CatPawIntro";
import MobileGameUI from "../MobileGameUI";
import GameContentFrame from "../GameContentFrame";
import GameUI from "../GameUI";
import Background from "../Background";
import GameObjectLayers from "../GameObjectLayers";
import useGameObjectState from "../useGameObjectState";

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

const COUNTDOWN = 60; // seconds

function Chapter1() {
    const { endChapter } = useGameContext();
    const [currentState, setCurrentState] = useState(CHAPTER_STATES.COVER);
    const [isDone, setIsDone] = useState(false);
    const [isTimerFinished, setIsTimerFinished] = useState(false);
    const isMobile = useMediaSelectTo(breakpoints.sm);
    const mobileGameFrameRef = useRef(null);
    const scrollHintRef = useRef(null);
    const isScrollHintShown = useRef(false);
    const scrollHintTimeoutRef = useRef(null);
    const scrollHintTouchTargetRef = useRef(null);
    const scrollHintHideHandlerRef = useRef(null);
    const {
        selectedObject,
        setSelectedObject,
        readyObjects,
        hoveredObjectId,
        doneObjectIds,
        handleObjectSelect,
        handleObjectMouseEnter,
        handleObjectMouseLeave,
        handleReadyButtonClick,
        cancelObject,
        isPrepared,
    } = useGameObjectState(GAME_OBJECTS);

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

    const handleEndGame = () => {
        endChapter("chapter1", readyObjects, GAME_STATES.CHAPTER1_TRANSITION);
    }

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

        const hideScrollHint = () => {
            if (scrollHintTimeoutRef.current != null) {
                clearTimeout(scrollHintTimeoutRef.current);
                scrollHintTimeoutRef.current = null;
            }
            const touchTarget = scrollHintTouchTargetRef.current;
            if (touchTarget) {
                touchTarget.removeEventListener("touchstart", hideScrollHint);
                scrollHintTouchTargetRef.current = null;
            }
            scrollHintHideHandlerRef.current = null;

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

        scrollHintHideHandlerRef.current = hideScrollHint;

        scrollHintTimeoutRef.current = setTimeout(() => {
            hideScrollHint();
        }, 2000);

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

    useEffect(() => {
        return () => {
            if (scrollHintTimeoutRef.current != null) {
                clearTimeout(scrollHintTimeoutRef.current);
                scrollHintTimeoutRef.current = null;
            }
            const target = scrollHintTouchTargetRef.current;
            const handler = scrollHintHideHandlerRef.current;
            if (target && handler) {
                target.removeEventListener("touchstart", handler);
            }
            scrollHintTouchTargetRef.current = null;
            scrollHintHideHandlerRef.current = null;
        };
    }, []);



    return (
        <>
            <GameObjectModal
                onClose={() => {
                    setSelectedObject(null);
                    setCurrentState(CHAPTER_STATES.GAME);
                }}
                isOpen={selectedObject !== null}
                number={selectedObject?.number}
                image={selectedObject?.image}
                title={selectedObject?.title}
                description={selectedObject?.description}
                button={
                    selectedObject?.requiresPreparation === false ? null : !isPrepared(selectedObject?.id) ? (
                        <ReadyButton onClick={handleReadyButtonClick}>
                            確定準備
                        </ReadyButton>
                    ) : (
                        <CancelButton onClick={cancelObject}>
                            取消準備
                        </CancelButton>
                    )
                }
            />
            <DoneModal
                isOpen={isDone}
                onClose={() => {
                    setCurrentState(CHAPTER_STATES.GAME);
                    setIsDone(false);
                }}
                onNext={handleEndGame}
                canClose={isTimerFinished === false}
            />
            {/* <CatPawCursor /> */}
            <StyledContainer>
                {currentState === CHAPTER_STATES.COVER && (
                    <ChapterCover
                        className="chapter-title"
                        mainTitle="日常準備"
                        chapterIndex={1}
                        subTitle="今天天氣真不錯， 趁現在做一些平日的防災準備吧..."
                        btnText="開始準備"
                        onNextClick={() => {
                            setCurrentState(CHAPTER_STATES.INTRO);
                        }}
                        cover="/images/game/chapter1/cover.webp"
                        cover_m="/images/game/chapter1/cover-m.webp"
                    />
                )}
                <CatPawIntro
                    image="/images/game/chapter1/intro.webp"
                    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/chapter1/bg.webp"
                            bg_m="/images/game/chapter1/bg.webp"
                        />
                        <GameObjectLayers
                            gameObjects={GAME_OBJECTS}
                            doneObjectIds={doneObjectIds}
                            hoveredObjectId={hoveredObjectId}
                            onSelect={handleObjectSelect}
                            onMouseEnter={handleObjectMouseEnter}
                            onMouseLeave={handleObjectMouseLeave}
                        />
                        <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="next-button"
                        onClick={showDoneModal}
                        icon={<GoArrow />}
                        text="準備完成"
                        theme={THEMES.DARK}
                        size="s"
                    />
                </GameView>
            </StyledContainer>
        </>
    );
}

const StyledContainer = styled.div`
    width: 100%;
    height: 100%;
    background-color: #eee;
    color: #fff;
    // hide cursor
    cursor: none;

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


const GameView = styled.div`
    position: absolute;
    inset: 0;
    background-color: #eee;
    color: #fff;


    .next-button {
        position: absolute;
        right: 32px;
        bottom: 32px;

        cursor: none;

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

    .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;
        }
    }


    .layer {
        position: absolute;
        border: 0;
        background: transparent;
        padding: 0;
        cursor: none;
        
        .done,
        .default {
            pointer-events: none;
        }

        .button {
            pointer-events: auto;
        }

        .default {
        }

        .done {
            opacity: 0;
        }
        &.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;
                }
            }
        }
    }

    .object-layer {
        z-index: 3;
        pointer-events: auto;

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

    .decor-layer {
        position: absolute;
        z-index: 2;
        pointer-events: none;

        img {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: fill;
        }
    }
    .layer.done {
        .default {
            opacity: 0;
        }

        .done {
            opacity: 1;
        }
    }
`;

const Button = styled.button`
    color: #fff;
    border-radius: 8px;
    padding: 10px 20px;

    font: var(--headline-6);
`;

const ReadyButton = styled(Button)`
    background: var(--neutrals-700);

`;

const CancelButton = styled(Button)`
    background: #ff6f2c;
`;

export default Chapter1;
