import { _decorator, Node, view, UITransform, Size } from 'cc';
import { BaseModal } from 'db://assets/scripts/core/BaseModal';
const { ccclass, property } = _decorator;

/**
 * WrongModal 回调接口
 */
export interface WrongModalCallbacks {
    /** 点击继续挑战 / 关闭按钮回调 */
    onContinue?: () => void;
}

/**
 * 答案错误弹窗组件
 * 继承 BaseModal，显示答案错误提示，提供"继续挑战"和关闭按钮
 */
@ccclass('WrongModal')
export class WrongModal extends BaseModal {
    /** 静态常量：弹窗层级 */
    public static readonly MODAL_Z_INDEX = 999;

    /** 关闭按钮 */
    @property(Node)
    closeBtn: Node | null = null;

    /** 继续挑战按钮 */
    @property(Node)
    buttonHint: Node | null = null;

    /** 回调函数 */
    private _callbacks: WrongModalCallbacks = {};

    /** 缓存的屏幕尺寸 */
    private _screenSize: Size | null = null;

    /**
     * 设置回调函数
     */
    setCallbacks(callbacks: WrongModalCallbacks): void {
        this._callbacks = callbacks;
    }

    /**
     * 页面首次加载时调用
     */
    onViewLoad(): void {
        console.log('[WrongModal] onViewLoad');
        this._bindButtonEvents();
    }

    /**
     * 页面每次显示时调用
     */
    onViewShow(): void {
        super.onViewShow();
        this._updateWidget();
    }

    /**
     * 页面销毁时调用
     */
    onViewDestroy(): void {
        this._unbindButtonEvents();
    }

    /**
     * 设置弹窗尺寸为全屏
     */
    private _updateWidget(): void {
        if (!this._screenSize) {
            this._screenSize = view.getVisibleSize();
        }

        const uiTransform = this.node.getComponent(UITransform);
        if (uiTransform) {
            uiTransform.setContentSize(this._screenSize.width, this._screenSize.height);
        }
    }

    /**
     * 绑定按钮事件
     */
    private _bindButtonEvents(): void {
        if (this.closeBtn) {
            this.closeBtn.on(Node.EventType.TOUCH_END, this._onContinueClick, this);
        }
        if (this.buttonHint) {
            this.buttonHint.on(Node.EventType.TOUCH_END, this._onContinueClick, this);
        }
    }

    /**
     * 解除按钮事件绑定
     */
    private _unbindButtonEvents(): void {
        if (this.closeBtn && this.closeBtn.isValid) {
            this.closeBtn.off(Node.EventType.TOUCH_END, this._onContinueClick, this);
        }
        if (this.buttonHint && this.buttonHint.isValid) {
            this.buttonHint.off(Node.EventType.TOUCH_END, this._onContinueClick, this);
        }
    }

    /**
     * 继续挑战 / 关闭按钮点击
     */
    private _onContinueClick(): void {
        console.log('[WrongModal] 点击继续挑战');
        this._callbacks.onContinue?.();
    }
}
