import { _decorator, Component, ProgressBar, Label, assetManager } from 'cc';
import type { AssetManager } from 'cc';
import { ViewManager } from './scripts/core/ViewManager';
import { LevelDataManager } from './scripts/utils/LevelDataManager';
import { AuthManager } from './scripts/utils/AuthManager';
import { ShareManager } from './scripts/utils/ShareManager';
import { WxSDK } from './scripts/utils/WxSDK';
const { ccclass, property } = _decorator;

/**
 * 页面加载组件
 * 负责用户登录、预加载资源并显示加载进度
 * 流程：登录 + game-data → 拿到 nextLevel → 加载首关图片 → 进入首页
 */
@ccclass('PageLoading')
export class PageLoading extends Component {
    private static readonly FONT_BUNDLE_NAME = 'fonts';

    @property(ProgressBar)
    progressBar: ProgressBar | null = null;

    @property(Label)
    statusLabel: Label | null = null;

    start() {
        this._startPreload();
    }

    private async _startPreload(): Promise<void> {
        if (this.progressBar) {
            this.progressBar.progress = 0;
        }

        this._updateStatusLabel('正在加载...');

        // 阶段1: 登录 + 获取 game-data（含 nextLevel）
        this._updateProgress(0);
        this._updateStatusLabel('正在连接服务器...');

        const loginSuccess = await AuthManager.instance.initialize();

        if (loginSuccess) {
            console.log('[PageLoading] 用户登录成功');
        } else {
            console.warn('[PageLoading] 登录失败，继续离线模式');
        }

        this._updateProgress(0.2);

        // 阶段2: 加载首关图片（如果有 nextLevel）
        const nextLevel = AuthManager.instance.nextLevel;
        let levelSuccess = false;

        if (nextLevel) {
            levelSuccess = await LevelDataManager.instance.initialize(nextLevel, (progress, message) => {
                // 关卡图片加载占 20%-80% 进度
                this._updateProgress(0.2 + progress * 0.6);
                this._updateStatusLabel(message);
            });

            if (!levelSuccess) {
                this._updateStatusLabel('资源加载失败，请重新打开游戏');
                return;
            }
        } else if (loginSuccess) {
            // nextLevel 为 null → 全部通关（或服务端无关卡）
            console.log('[PageLoading] 全部通关或无可用关卡');
            this._updateProgress(0.8);
        } else {
            // 登录失败且没有 nextLevel
            this._updateStatusLabel('加载失败，请重新打开游戏');
            return;
        }

        // 阶段3: 加载字体分包
        const fontSuccess = await this._loadFontBundle();
        if (!fontSuccess) {
            this._updateStatusLabel('字体资源加载失败，请重新打开游戏');
            return;
        }

        // 检测分享码：从微信启动参数中获取
        const shareCode = WxSDK.getShareCodeFromLaunch();
        if (shareCode && loginSuccess) {
            this._updateStatusLabel('正在加载挑战关卡...');
            const joinSuccess = await ShareManager.instance.joinShare(shareCode);
            if (joinSuccess) {
                this._updateProgress(1);
                this._updateStatusLabel('加载完成');
                // 跳过首页，直接进入分享挑战关卡
                ViewManager.instance.open('PageLevel', {
                    params: { shareMode: true },
                    onComplete: () => {
                        this.node.destroy();
                    },
                });
                return;
            }
            console.warn('[PageLoading] 加入分享失败，进入正常模式');
        }

        // 正常流程：预加载 PageHome (82-100%)
        ViewManager.instance.preload('PageHome',
            (progress) => {
                this._updateProgress(0.82 + progress * 0.18);
                this._updateStatusLabel('正在加载界面资源...');
            },
            () => {
                this._onPreloadComplete();
            }
        );
    }

    private _updateProgress(progress: number): void {
        if (this.progressBar) {
            this.progressBar.progress = progress;
        }
    }

    private _updateStatusLabel(message: string): void {
        if (this.statusLabel) {
            this.statusLabel.string = message;
        }
    }

    private _onPreloadComplete(): void {
        this._updateProgress(1);
        this._updateStatusLabel('加载完成');

        ViewManager.instance.open('PageHome', {
            onComplete: () => {
                this.node.destroy();
            }
        });
    }

    /**
     * 加载字体分包，避免字体资源进入小游戏主包
     */
    private _loadFontBundle(): Promise<boolean> {
        const bundleName = PageLoading.FONT_BUNDLE_NAME;
        const cachedBundle = assetManager.getBundle(bundleName);
        if (cachedBundle) {
            console.log(`[PageLoading] 字体分包已加载: ${bundleName}`);
            this._updateProgress(0.82);
            return Promise.resolve(true);
        }

        this._updateStatusLabel('正在加载字体资源...');
        this._updateProgress(0.8);

        return new Promise((resolve) => {
            assetManager.loadBundle(bundleName, (err: Error | null, bundle: AssetManager.Bundle | null) => {
                if (err || !bundle) {
                    console.error(`[PageLoading] 字体分包加载失败: ${bundleName}`, err);
                    resolve(false);
                    return;
                }

                console.log(`[PageLoading] 字体分包加载完成: ${bundleName}`);
                this._updateProgress(0.82);
                resolve(true);
            });
        });
    }
}
