import styled, { keyframes } from "styled-components";
import { useGameContext, GAME_STATES } from "../index";
import { useState, useEffect, useMemo } from "react";
import { ImageWrapper } from "../../../components/MediaWrapper";
import getPathPrefix from "../../../utils/getPathPrefix";
import ShadedTitle from '../../../components/ShadedTitle'
import { respondTo } from "../../../utils/responsive";

const VIDEOS = [
    "/images/game/ending.webp",
    "/images/game/intro-bg.webp",
    "/images/game/chapter1/bg.webp",
    "/images/game/chapter1/cover.webp",
    "/images/game/chapter1/transition.webp",
    "/images/game/chapter2/bg.webp",
    "/images/game/chapter2/intro.webp",
    "/images/game/chapter3/bg.webp",
    "/images/game/chapter3/intro.webp",
    "/images/game/chapter4/cover.webp",
    "/images/game/chapter4/bg.webp",
    "/images/game/chapter4/branch-a.webp",
    "/images/game/chapter4/branch-b.webp",
];

const MOBILE_VIDEOS = [
    "/images/game/ending-m.webp",
    "/images/game/intro-bg-m.webp",
    "/images/game/chapter1/bg-m.webp",
    // "/images/game/chapter1/cover-m.webp",
    "/images/game/chapter1/cover-m.webp",
    "/images/game/chapter1/transition-m.webp",
    "/images/game/chapter2/bg-m.webp",
    // "/images/game/chapter2/intro-m.webp",
    "/images/game/chapter2/intro-m.webp",
    "/images/game/chapter3/bg-m.webp",
    // "/images/game/chapter3/intro-m.webp",
    "/images/game/chapter3/intro-m.webp",
    // "/images/game/chapter4/cover-m.webp",
    "/images/game/chapter4/cover-m.webp",
    "/images/game/chapter4/bg-m.webp",
    "/images/game/chapter4/branch-a-m.webp",
    "/images/game/chapter4/branch-b-m.webp",
];


// 添加需要預加載的組件
const PRELOAD_COMPONENTS = {
    Intro: () => import('../IntroView'),
    Tutorial: () => import('../TutorialView'),
    Chapter1: () => import('../Chapter1'),
    Chapter1Transition: () => import('../Chapter1Transition'),
    Chapter2: () => import('../Chapter2'),
    Chapter3: () => import('../Chapter3'),
    Chapter4: () => import('../Chapter4'),
    Chapter4Transition: () => import('../Chapter4Transition'),
    Ending: () => import('../Ending'),
};

const preloadImages = (urls, onProgress) => {
    const imagePromises = urls.map((url) => {
        return new Promise((resolve) => {
            const image = new Image();
            const handleDone = () => {
                onProgress?.();
                resolve();
            };

            image.onload = handleDone;
            image.onerror = handleDone;
            image.src = getPathPrefix(url);
        });
    });

    return Promise.all(imagePromises);
};

function LoadingView() {
    const { setGameCurrentState } = useGameContext();
    const [loadedCount, setLoadedCount] = useState(0);
    const [componentsLoaded, setComponentsLoaded] = useState(0);

    const mediaSource = useMemo(() => {
        if (typeof window === "undefined") {
            return VIDEOS;
        }

        return window.innerWidth < 568 ? MOBILE_VIDEOS : VIDEOS;
    }, []);

    const totalItems = mediaSource.length + Object.keys(PRELOAD_COMPONENTS).length;
    
    const percentage = useMemo(() => {
        // 確保百分比不會超過 100
        const calculatedPercentage = ((loadedCount + componentsLoaded) / totalItems) * 100;
        return Math.min(calculatedPercentage, 100);
    }, [loadedCount, componentsLoaded, totalItems]);

    useEffect(() => {
        // 當所有資源都加載完成時
        if (percentage === 100) {
            setGameCurrentState(GAME_STATES.INTRO);
        }
    }, [percentage, setGameCurrentState]);

    // 預加載組件的函數
    useEffect(() => {
        const preloadComponents = async () => {
            const promises = Object.values(PRELOAD_COMPONENTS).map(importFn => {
                return importFn().catch(() => {
                    // console.error('Error preloading component:', error);
                });
            });

            try {
                await Promise.all(promises);
                setComponentsLoaded(Object.keys(PRELOAD_COMPONENTS).length);
            } catch {
                // console.error('Error in preloading components:', error);
            }
        };

        preloadComponents();
    }, []);

    // 以 Image 物件預先拉取圖片，將章節素材推進瀏覽器快取
    useEffect(() => {
        let isActive = true;
        console.info(`[LoadingView] preloading ${mediaSource.length} images`);

        preloadImages(mediaSource, () => {
            if (!isActive) return;
            setLoadedCount((prev) => prev + 1);
        }).then(() => {
            console.info("[LoadingView] image preloading completed");
        });

        return () => {
            isActive = false;
        };
    }, [mediaSource]);

    return (
        <StyledContainer>
            <Group>
                <ProgressGroup>
                    <ImageWrapper
                        src="/images/game/loading-character.png"
                        alt="loading-character"
                    />
                    <div className="progress-container">
                        <div
                            className="progress-bar"
                            style={{ width: `${percentage}%` }}
                        ></div>
                    </div>
                </ProgressGroup>
                <p>LOADING...</p>
                <ShadedTitle className="loading-text" title="遊戲載入中..." />
            </Group>
        </StyledContainer>
    );
}

const StyledContainer = styled.div`
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url(${getPathPrefix("/images/game/loading-frame-bg.webp")})
        no-repeat center center;
    background-size: cover;
`;

const sparkling = keyframes`
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
`;

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

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    p {
        margin-top: 4px;
        font-family: "Bungee", "Noto Sans TC", sans-serif;
        font-size: 16px;
        font-style: normal;
        font-weight: 400;
        line-height: 120%; /* 19.2px */
        color: var(--neutrals-700);
        text-align: center;
    }

    .loading-text {
        font-size: 32px;
        font-style: normal;
        font-weight: 900;
        line-height: 120%; /* 38.4px */
        animation: ${sparkling} 1s infinite;

        margin-top: 20px;

        ${respondTo.sm} {
            margin-top: 12px;
            font: var(--mobile-headline-4);
        }
    }

`;

const ProgressGroup = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .progress-container {
        width: 270px;
        height: 26px;
        border: 1px solid red;
        border: 1px solid var(--neutrals-700);
        border-radius: 4px;
        padding: 4px;
        background: var(--neutrals-000);

        .progress-bar {
            width: 20%;
            height: 100%;
            background: var(--neutrals-700);
            border-radius: 2px;
        }
    }
`;

export default LoadingView;
