---
import type { SiteConfig } from "@/types/config";
import ImageWrapper from "@components/common/imageWrapper.astro";


interface Props {
    config: SiteConfig["wallpaper"];
    class?: string;
}

const { config, class: className  } = Astro.props;

// 获取当前设备类型的图片源
const getImageSources = () => {
    const toArray = (src: any) => [src || []].flat();
    const { src } = config;
    const isObj = src && typeof src === "object" && !Array.isArray(src);
    const desktop = toArray(isObj ? (src as any).desktop : src);
    const mobile = toArray(isObj ? (src as any).mobile : src);
    return {
        desktop: desktop.length > 0 ? desktop : mobile,
        mobile: mobile.length > 0 ? mobile : desktop,
    };
}

const imageSources = getImageSources();

// 轮播配置
const carouselConfig = config.carousel;
const isCarouselEnabled = imageSources.desktop.length > 1 || imageSources.mobile.length > 1;
const carouselInterval = carouselConfig?.interval || 5;

// 样式配置
const zIndex = config.fullscreen?.zIndex || -1;
const opacity = config.fullscreen?.opacity || 0.8;
const blur = config.fullscreen?.blur || 0;
---

<div
    id="fullscreen-wallpaper-wrapper"
    class:list={[
        "fixed inset-0 w-full h-full overflow-hidden pointer-events-none transition-opacity duration-600",
        className
    ]}
    style={`z-index: ${zIndex}; opacity: ${opacity};`}
    data-fullscreen-wallpaper
>
    {isCarouselEnabled ? (
        <div id="fullscreen-wallpaper-carousel" class="relative h-full w-full" data-carousel-config={JSON.stringify(carouselConfig)}>
            <ul class="carousel-list h-full w-full">
                {imageSources.desktop.map((src, index) => (
                    <li class:list={[
                        "carousel-item desktop-item hidden md:block absolute inset-0 transition-opacity duration-1200",
                        index === 0 ? 'opacity-100' : 'opacity-0',
                        carouselConfig?.kenBurns !== false ? 'ken-burns-enabled' : ''
                    ]}>
                        <ImageWrapper
                            alt={`Desktop wallpaper ${index + 1}`}
                            class:list={["object-cover h-full w-full"]}
                            src={src}
                            position={config.position}
                            style={blur > 0 ? `filter: blur(${blur}px);` : undefined}
                            loading={index === 0 ? "eager" : "lazy"}
                        />
                    </li>
                ))}
                {imageSources.mobile.map((src, index) => (
                    <li class:list={[
                        "carousel-item mobile-item block md:hidden absolute inset-0 transition-opacity duration-1200",
                        index === 0 ? 'opacity-100' : 'opacity-0',
                        carouselConfig?.kenBurns !== false ? 'ken-burns-enabled' : ''
                    ]}>
                        <ImageWrapper
                            alt={`Mobile wallpaper ${index + 1}`}
                            class:list={["object-cover h-full w-full"]}
                            src={src}
                            position={config.position}
                            style={blur > 0 ? `filter: blur(${blur}px);` : undefined}
                            loading={index === 0 ? "eager" : "lazy"}
                        />
                    </li>
                ))}
            </ul>
        </div>
    ) : (
        <div class="relative h-full w-full">
            <ImageWrapper
                alt="Mobile wallpaper"
                class:list={["block md:hidden object-cover h-full w-full transition duration-600 opacity-100"]}
                src={imageSources.mobile[0] || imageSources.desktop[0] || ''}
                position={config.position}
                style={blur > 0 ? `filter: blur(${blur}px);` : undefined}
                loading="eager"
            />
            <ImageWrapper
                id="fullscreen-wallpaper"
                alt="Desktop wallpaper"
                class:list={["hidden md:block object-cover h-full w-full transition duration-600 opacity-100"]}
                src={imageSources.desktop[0] || imageSources.mobile[0] || ''}
                position={config.position}
                style={blur > 0 ? `filter: blur(${blur}px);` : undefined}
                loading="eager"
            />
        </div>
    )}
</div>

<script define:vars={{ carouselInterval }}>
    // 全屏壁纸轮播图初始化函数
    window.initFullscreenWallpaperCarousel = function() {
        const carousel = document.getElementById('fullscreen-wallpaper-carousel');
        if (!carousel) return;

        // 检查是否是同一个 DOM 元素且定时器正在运行，避免重复初始化导致动画重置
        if (window.fullscreenWallpaperTimer && window.currentFullscreenWallpaperCarousel === carousel) {
            return;
        }
        window.currentFullscreenWallpaperCarousel = carousel;

        // 初始化全局状态
        if (!window.fullscreenWallpaperState) {
            window.fullscreenWallpaperState = {
                currentIndex: 0,
                lastSwitchTime: Date.now()
            };
        }

        // 清理旧的定时器，防止重复初始化导致的闪烁
        if (window.fullscreenWallpaperTimer) {
            clearTimeout(window.fullscreenWallpaperTimer);
            window.fullscreenWallpaperTimer = null;
        }

        const carouselConfigData = carousel.getAttribute('data-carousel-config');
        const carouselConfig = carouselConfigData ? JSON.parse(carouselConfigData) : {};

        const desktopItems = carousel.querySelectorAll('.carousel-item.desktop-item');
        const mobileItems = carousel.querySelectorAll('.carousel-item.mobile-item');

        function setupCarousel(items, isEnabled) {
            if (items.length === 0) return null;

            // 如果禁用了轮播但有多张图，则随机显示一张
            if (items.length > 1 && !isEnabled) {
                items.forEach(item => {
                    item.classList.add('opacity-0');
                    item.classList.remove('opacity-100');
                });
                const randomIndex = Math.floor(Math.random() * items.length);
                const randomItem = items[randomIndex];
                randomItem.classList.add('opacity-100');
                randomItem.classList.remove('opacity-0');
                return null;
            }

            if (items.length > 1 && isEnabled) {
                // 使用全局状态中的索引
                let currentIndex = window.fullscreenWallpaperState.currentIndex;
                // 确保索引有效
                if (currentIndex >= items.length) {
                    currentIndex = 0;
                    window.fullscreenWallpaperState.currentIndex = 0;
                }
                
                function switchToSlide(index) {
                    const currentItem = items[currentIndex];
                    currentItem.classList.remove('opacity-100');
                    currentItem.classList.add('opacity-0');
                    currentIndex = index;
                    // 更新全局状态
                    window.fullscreenWallpaperState.currentIndex = index;
                    window.fullscreenWallpaperState.lastSwitchTime = Date.now();

                    const nextItem = items[currentIndex];
                    nextItem.classList.add('opacity-100');
                    nextItem.classList.remove('opacity-0');
                    // 通过切换 is-animating 类来重置下一张图片的动画
                    if (nextItem.classList.contains('ken-burns-enabled')) {
                        nextItem.classList.remove('is-animating');
                        nextItem.offsetHeight; // 强制重绘
                        nextItem.classList.add('is-animating');
                    }
                }

                // 初始化：根据当前索引显示图片
                items.forEach((item, index) => {
                    if (index === currentIndex) {
                        item.classList.add('opacity-100');
                        item.classList.remove('opacity-0');
                        // 初始图片开启动画
                        if (item.classList.contains('ken-burns-enabled')) {
                            item.classList.add('is-animating');
                        }
                    } else {
                        item.classList.add('opacity-0');
                        item.classList.remove('opacity-100');
                        item.classList.remove('is-animating');
                    }
                });

                return {
                    next: () => switchToSlide((currentIndex + 1) % items.length),
                    prev: () => switchToSlide((currentIndex - 1 + items.length) % items.length),
                };
            }
            return null;
        }

        const desktopCtrl = setupCarousel(desktopItems, carouselConfig?.enable);
        const mobileCtrl = setupCarousel(mobileItems, carouselConfig?.enable);

        if (carouselConfig?.enable && (desktopCtrl || mobileCtrl)) {
            function startCarousel() {
                if (window.fullscreenWallpaperTimer) clearTimeout(window.fullscreenWallpaperTimer);
                
                const runLoop = () => {
                    const now = Date.now();
                    const intervalMs = carouselInterval * 1000;
                    const elapsed = now - window.fullscreenWallpaperState.lastSwitchTime;
                    let delay = intervalMs - elapsed;
                    
                    if (delay < 0) delay = 0;

                    window.fullscreenWallpaperTimer = setTimeout(() => {
                        desktopCtrl?.next();
                        mobileCtrl?.next();
                        runLoop();
                    }, delay);
                };

                runLoop();
            }

            startCarousel();
        }
    }

    // 壁纸显示控制函数
    function showFullscreenWallpaper() {
        requestAnimationFrame(() => {
            const wallpaper = document.getElementById('fullscreen-wallpaper');
            if (wallpaper) {
                wallpaper.classList.remove('opacity-0');
            }
            const mobileWallpaper = document.querySelector('.block.md\\:hidden[alt="Mobile wallpaper"]');
            if (mobileWallpaper && !document.getElementById('fullscreen-wallpaper-carousel')) {
                mobileWallpaper.classList.remove('opacity-0');
                mobileWallpaper.classList.add('opacity-100');
            }
            const carousel = document.getElementById('fullscreen-wallpaper-carousel');
            if (carousel) {
                window.initFullscreenWallpaperCarousel();
            }
        });
    }

    // 监听 Astro 页面切换事件
    document.addEventListener('astro:after-swap', () => {
        showFullscreenWallpaper();
    });

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', showFullscreenWallpaper);
    } else {
        showFullscreenWallpaper();
    }
</script>