/**
 * 弹窗控制器
 */

(function() {
    'use strict';

    /**
     * 打开弹窗
     */
    window.openModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) return;

        // 关闭其他弹窗
        closeAllModals();

        // 设置当前弹窗
        MOBILE_APP.currentModal = modalId;

        // 添加活动类
        modal.classList.add('active');

        // 阻止页面滚动
        document.body.style.overflow = 'hidden';

        // 添加点击外部关闭事件
        modal.addEventListener('click', handleModalOverlayClick);

        // 添加键盘事件
        document.addEventListener('keydown', handleModalKeydown);

        // 触发自定义事件
        const event = new CustomEvent('modalOpen', { detail: { modalId } });
        document.dispatchEvent(event);
    };

    /**
     * 关闭弹窗
     */
    window.closeModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) return;

        // 移除活动类
        modal.classList.remove('active');

        // 恢复页面滚动
        document.body.style.overflow = '';

        // 移除事件监听
        modal.removeEventListener('click', handleModalOverlayClick);
        document.removeEventListener('keydown', handleModalKeydown);

        // 清除当前弹窗
        if (MOBILE_APP.currentModal === modalId) {
            MOBILE_APP.currentModal = null;
        }

        // 触发自定义事件
        const event = new CustomEvent('modalClose', { detail: { modalId } });
        document.dispatchEvent(event);
    };

    /**
     * 关闭所有弹窗
     */
    function closeAllModals() {
        const modals = document.querySelectorAll('.modal-overlay');
        modals.forEach(modal => {
            modal.classList.remove('active');
        });
        document.body.style.overflow = '';
        MOBILE_APP.currentModal = null;
    }

    /**
     * 处理弹窗遮罩点击
     */
    function handleModalOverlayClick(e) {
        if (e.target === e.currentTarget) {
            closeModal(e.currentTarget.id);
        }
    }

    /**
     * 处理键盘事件
     */
    function handleModalKeydown(e) {
        if (e.key === 'Escape') {
            if (MOBILE_APP.currentModal) {
                closeModal(MOBILE_APP.currentModal);
            }
        }
    }

    /**
     * 切换弹窗显示/隐藏
     */
    window.toggleModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) return;

        if (modal.classList.contains('active')) {
            closeModal(modalId);
        } else {
            openModal(modalId);
        }
    };

    /**
     * 显示确认对话框
     */
    window.showConfirm = function(options) {
        const defaults = {
            title: '确认操作',
            message: '确定要执行此操作吗？',
            confirmText: '确认',
            cancelText: '取消',
            onConfirm: null,
            onCancel: null
        };

        const opts = { ...defaults, ...options };

        // 设置内容
        const confirmModal = document.getElementById('confirmModal');
        if (!confirmModal) return;

        const modalTitle = confirmModal.querySelector('.modal-title');
        const confirmMessage = confirmModal.querySelector('#confirmMessage');
        const confirmOK = confirmModal.querySelector('#confirmOK');
        const confirmCancel = confirmModal.querySelector('#confirmCancel');

        if (modalTitle) modalTitle.textContent = opts.title;
        if (confirmMessage) confirmMessage.textContent = opts.message;
        if (confirmOK) {
            confirmOK.textContent = opts.confirmText;
            confirmOK.onclick = function() {
                closeModal('confirmModal');
                if (typeof opts.onConfirm === 'function') {
                    opts.onConfirm();
                }
            };
        }
        if (confirmCancel) {
            confirmCancel.textContent = opts.cancelText;
            confirmCancel.onclick = function() {
                closeModal('confirmModal');
                if (typeof opts.onCancel === 'function') {
                    opts.onCancel();
                }
            };
        }

        openModal('confirmModal');
    };

    /**
     * 显示提示对话框
     */
    window.showAlert = function(message, title = '提示') {
        showConfirm({
            title: title,
            message: message,
            confirmText: '确定',
            cancelText: null
        });
    };

    /**
     * 初始化弹窗
     */
    function initModals() {
        // 为所有弹窗添加关闭按钮事件
        const closeButtons = document.querySelectorAll('.modal-close');
        closeButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                const modal = this.closest('.modal-overlay');
                if (modal) {
                    closeModal(modal.id);
                }
            });
        });

        // 监听弹窗打开事件
        document.addEventListener('modalOpen', function(e) {
            console.log('Modal opened:', e.detail.modalId);
        });

        // 监听弹窗关闭事件
        document.addEventListener('modalClose', function(e) {
            console.log('Modal closed:', e.detail.modalId);
        });
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', initModals);
})();
