import styled from 'styled-components';
import StartView from './StartView';
import Frame from './Frame';
import { useState, createContext, useMemo, useContext, useEffect } from 'react';
import LoadingView from './LoadingView';
import IntroView from './IntroView';
import Dialog from './Dialog';
import TutorialView from './TutorialView';
import Chapter1 from './Chapter1';
import Chapter1Transition from './Chapter1Transition';
import Chapter2 from './Chapter2';
import Chapter3 from './Chapter3';
import Chapter4 from './Chapter4';
import Chapter4Transition from './Chapter4Transition';
import WipeoutTransition from './WipeoutTransition';
import { DISPATCH_WIPE_OUT_START_EVENT, SPEED } from './WipeoutTransition';
import AudioController from './AudioController';
import LoadResult from './LoadResult';
import Ending from './Ending';
import { ImageWrapper } from '../../components/MediaWrapper';
import { respondTo } from '../../utils/responsive';
import Meter from './Meter';
import CatPawCursor from './CatPawCursor';
import { Navigate } from 'react-router-dom';
import getPathPrefix from '../../utils/getPathPrefix';

const GameContext = createContext();

export const GAME_STATES = {
    START: "start",
    LOADING: "loading",
    INTRO: "intro",
    TUTORIAL: "tutorial",
    CHAPTER1: "CHAPTER_1",
    CHAPTER1_TRANSITION: "chapter1_transition",
    CHAPTER2: "CHAPTER_2",
    CHAPTER3: "CHAPTER_3",
    CHAPTER3_TRANSITION: "chapter3_transition",
    CHAPTER4: "CHAPTER_4",
    CHAPTER4_TRANSITION: "chapter4_transition",
    ENDING: "ending",
    LOAD_RESULT: "load_result",
    RESULT: "result",
};

export const GAME_EVENTS = {
    GAME_START: "game_start",
    GAME_END: "game_end",
}

export const DISPATCH_GAME_START_EVENT = () => {
    window.dispatchEvent(new Event(GAME_EVENTS.GAME_START));
}

export const DISPATCH_GAME_END_EVENT = () => {
    window.dispatchEvent(new Event(GAME_EVENTS.GAME_END));
}


export const useGameContext = () => {
    return useContext(GameContext);
}

const GamePage = () => {
    const [gameState, setGameState] = useState(GAME_STATES.START); 
    const [chapterState, setChapterState] = useState({
        chapter1: null,
        chapter2: null,
        chapter3: null,
        chapter4: null,
    });

    const setGameCurrentState = (state) => {
        setGameState(state);
    }

    const wipeOutAndStartNextChapter = (nextChapter) => {
        const offset = window.innerWidth < 568 ? 1600 : 1200;
        DISPATCH_WIPE_OUT_START_EVENT();
        setTimeout(() => {
            setGameCurrentState(nextChapter);
        }, SPEED - offset);
    };

    const endChapter = (chapter, chapterData, nextChapter, hasWipeout = false) => {
        const newChapterState = {...chapterState};
        newChapterState[chapter] = chapterData;
        setChapterState(newChapterState);

        if (hasWipeout) {
            wipeOutAndStartNextChapter(nextChapter);
        } else {
            setGameCurrentState(nextChapter);
        }
    }

    const saveChaterData = () => {
        // save to local storage
        const chapterData = chapterState;
        localStorage.setItem("CHAPTER_DATA", JSON.stringify(chapterData));
    }

    const getChapterData = () => {
        // load from local storage
        const chapterData = localStorage.getItem("CHAPTER_DATA");
        if (chapterData) {
            return JSON.parse(chapterData);
        }
        return null;
    }


    const view = useMemo(() => {


        switch (gameState) {
            case GAME_STATES.START: return <StartView />;
            case GAME_STATES.LOADING: return <LoadingView />;
            case GAME_STATES.INTRO: return <IntroView />;
            case GAME_STATES.TUTORIAL: return <TutorialView />;
            case GAME_STATES.CHAPTER1: return <Chapter1 />
            case GAME_STATES.CHAPTER1_TRANSITION: return <Chapter1Transition />
            case GAME_STATES.CHAPTER2: return <Chapter2 />
            case GAME_STATES.CHAPTER3: return <Chapter3 />
            case GAME_STATES.CHAPTER4: return <Chapter4 />
            case GAME_STATES.CHAPTER4_TRANSITION: return <Chapter4Transition />;
            case GAME_STATES.ENDING: return <Ending />
            case GAME_STATES.LOAD_RESULT: return <LoadResult/>
            case GAME_STATES.RESULT: return <Navigate to={getPathPrefix('/result')} replace />
            default: return <div><h1>default</h1></div>
        }
    }, [gameState]);


    const pageBG = useMemo(() => {

        const getBgImage = (state) => {
            switch (state) {
                case GAME_STATES.START: return "/images/game/start-bg.jpg";
                case GAME_STATES.LOADING: return "/images/game/loading-bg.jpg";
                default: return "/images/game/start-bg.jpg";
            }
        }
        return getBgImage(gameState);
    }, [gameState]);

    useEffect(() => {
        const videoElements = document.querySelectorAll('video');
        const cleanupVideo = (video) => {
            try {
                video.pause();
                // Safari 對激進重置（src/load/removeChild）較敏感，改為溫和清理
                if (Number.isFinite(video.currentTime)) {
                    video.currentTime = 0;
                }
            } catch (error) {
                console.error('Error cleaning up video:', error);
            }
        };

        return () => {
            videoElements.forEach(cleanupVideo);
        }
    }, [gameState]);

  return (
      <GameContext.Provider
          value={{
              gameState,
              chapterState,
              setGameCurrentState,
              endChapter,
              wipeOutAndStartNextChapter,
              saveChaterData,
              getChapterData,
          }}
      >
          <StyledGamePage $state={gameState}>
              <AudioController />
              <CatPawCursor />

              <BG>
                  <ImageWrapper src={pageBG} alt="page-bg" />
              </BG>
              <Group>
                  <Meter gameState={gameState} className="meter" />
                  <div id="mobile-game-ui-root" />
                  <div className="frame-container" id="frame-container">
                      <Frame>
                          <GameView className="game-view">{view}</GameView>
                          <WipeoutTransition />
                      </Frame>
                      <Dialog />
                  </div>
                  <ButtonGroup>
                      {gameState === GAME_STATES.START && (
                          <StartButton
                              onClick={() => {
                                  setGameCurrentState(GAME_STATES.LOADING);
                              }}
                          >
                              <span>START</span>
                          </StartButton>
                      )}
                  </ButtonGroup>
              </Group>
          </StyledGamePage>
      </GameContext.Provider>
  );
};


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

    display: flex;
    justify-content: center;
    align-items: center;
    cursor: none;

    ${respondTo.sm} {
        align-items: flex-start;
        padding-top: calc(var(--header-height) + 16px);
    }
`;

const BG = styled.div`
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    pointer-events: none;

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

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

    border-radius: 32px;
    overflow: hidden;
`;

const Group = styled.div`
    position: relative;
    // padding-top: 40px;
    padding-top: 40px;

    #mobile-game-ui-root {
        display: none;

        ${respondTo.sm} {
            display: flex;
            
            position: absolute;
            top: 20px;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 2;

            width: 100vw;
        }
    } 
    
    .frame-container {
        position: relative;
        // overflow: hidden;
        border-radius: 32px;
    }

    > .meter {
        margin: 0 auto;
        margin-bottom: 30px;
    }

    ${respondTo.sm} {
        padding-top: 0;

        > .meter {
            display: none;
        }
    }
`;


const ButtonGroup = styled.div`
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;

    min-height: 104px;

    ${respondTo.sm} {
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        min-height: unset;
        padding-bottom: 32px;

    }
`;


const StartButton = styled.button`
    width: 138px;
    height: 56px;
    // flex center
    display: flex;
    justify-content: center;
    align-items: center;

    color: white;
    background: var(--main-color-e);
    border-radius: 8px;
    border: 2px solid var(--main-color-e);

    span {
        font-family: "Bungee", "Noto Sans TC", sans-serif;
        font-size: 20px;
        font-style: normal;
        font-weight: 400;
        line-height: 120%; /* 24px */
        transform: rotate(-2deg);
    }

    &:hover {
        background: var(--main-color-b);
        color: var(--main-color-e);
    }
`;

export default GamePage; 