import { _decorator, Component, director, Label, log, Node, tween, UITransform, v3, Vec3, view, WebView } from 'cc';
import { getHistoryUrl, getOddsUrl, getSupportUrl } from '../../../Loading/scripts/comm';
import { NodePoolManager } from '../../../Loading/scripts/manager/NodePoolManager';
import { I18nManager } from '../../../Loading/scripts/manager/I18nManager';
import { AudioManager } from '../../../Loading/scripts/manager/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('webView')
export class webView extends Component {
    @property(WebView)
    webV: WebView = null;

    @property(Node)
    mainNode: Node = null;

    @property(Label)
    title: Label = null;

    @property(Node)
    loadingView: Node = null;

    param: string = null;
    private readonly DURATION = 0.2;
    private OFFSET_Y = -800; // 根据实际UI调整偏移量
    private initPos: Vec3 = v3(0, 0, 0);

    protected onLoad(): void {

    }

    protected start(): void {
        this.webV.node.on(WebView.EventType.LOADED, this.webViewLoaded, this);
        this.webV.node.on(WebView.EventType.ERROR, this.webViewError, this);
        this.webV.node.on(WebView.EventType.LOADING, this.webViewLoading, this);
        const waitForIframe = () => {
            const iframe = document.querySelector('iframe');
            if (iframe) {
                iframe.setAttribute('scrolling', 'no');
                iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts allow-forms allow-top-navigation-by-user-activation allow-popups');
            } else {
                setTimeout(waitForIframe, 100);
            }
        };

        waitForIframe();
    }

    private webViewLoading() {
        this.loadingView.active = true;
    }

    private webViewLoaded() {
        this.scheduleOnce(() => {
            this.loadingView.active = false;
            this.webV.node.active = true;
        }, 0.8);
    }

    private webViewError() {
        console.error('WebView load failed');
        this.loadingView.active = false;
        // 可以显示错误提示
        this.onBtnClose();
    }

    protected onDestroy(): void {

    }

    // 'http://192.168.0.30:5173/#/rp_fortuneRabbit/support?l=en';
    async open(param: string, curBet) {
        try {
            this.loadingView.active = true;
            // 计算初始位置 - 屏幕中心            
            this.param = param;
            this.webV.node.active = false;
            this.OFFSET_Y = -view.getVisibleSize().height;
            let url = '';
            let title = '';
            if (param == 'rule') {
                url = getSupportUrl();
                title = I18nManager.instance.t('AID_MAIN_OPERATE_RULES');
            } else if (param == 'paytable') {
                url = getOddsUrl();
                title = I18nManager.instance.t('AID_MAIN_OPERATE_PAYTABLE');
            } else if (param == 'history') {
                url = getHistoryUrl();
                title = I18nManager.instance.t('AID_MAIN_OPERATE_HISTORY');
            }
            this.title.string = title;

            // url = `http://192.168.0.6:5173/#/history?gid=rp_10002&type=odds&l=th&c=IDR&bet=${curBet}&t=eyJQIjoxMDAwMDEsIkUiOjE3NDE0NDEyMjEsIlMiOjEwMDAsIkQiOiJycF8xMDAwMSJ9.4VEuBbGan0ljnBgLN7AtqLNqcwQa02BdQL3rHinPS3w`
            // let data = {
            //     curBet: curBet,
            // }
            // this.webV.evaluateJS(`receiveDataFromGame(${JSON.stringify(data)})`);
            this.node.setPosition(v3(0, this.OFFSET_Y, 0));
            // 播放进入动画到目标位置
            tween(this.mainNode)
                .to(this.DURATION, {
                    position: this.initPos
                })
                .call(() => {
                    // 先隐藏WebView，等加载完再显示
                    this.webV.url = url;
                })
                .start();
        } catch (error) {
            console.error('WebView open failed:', error);
            this.onBtnClose();
        }
    }

    private isClosing: boolean = false;  // 添加状态标记
    onBtnClose() {
        // 如果正在关闭中，直接返回
        if (this.isClosing) return;
        this.isClosing = true;  // 设置关闭状态

        AudioManager.instance.playSFX('Common_Button_Click');
        // 播放退出动画 - 移动到屏幕下方
        tween(this.node)
            .to(this.DURATION, {
                position: v3(
                    this.initPos.x,
                    this.initPos.y + this.OFFSET_Y,
                    0
                )
            })
            .call(() => {
                // 动画结束后回收节点
                // 清理事件监听
                this.webV.node.off(WebView.EventType.LOADED, this.webViewLoaded, this);
                this.webV.node.off(WebView.EventType.ERROR, this.webViewError, this);
                this.webV.node.off(WebView.EventType.LOADING, this.webViewLoading, this);
                NodePoolManager.instance.clearNodePoolByName(this.param);
                this.node.destroy();
            })
            .start();

    }
}

