/**
 * 移动端控制中心模块
 * Wi-Fi、蓝牙、亮度、主题等开关控制
 */

(function() {
    'use strict';

    var ControlManager = {
        _elements: {},
        _isOpen: false,
        _state: {
            wifi: false,
            bluetooth: false,
            brightness: 80,
            volume: 70
        },

        /**
         * 初始化控制中心
         */
        init: function() {
            this._elements.container = document.getElementById('controlCenter');
            this._elements.items = this._elements.container ?
                this._elements.container.querySelectorAll('.control-item') : [];

            if (!this._elements.container) {
                console.warn('[Control] 控制中心 DOM 不存在');
                return;
            }

            // 从存储恢复状态
            if (window.MobileStorage) {
                var saved = window.MobileStorage.get('controlState', null);
                if (saved) {
                    this._state = saved;
                }
            }

            this.bindEvents();
            this.updateUI();
            console.log('[Control] 初始化完成');
        },

        /**
         * 绑定事件
         */
        bindEvents: function() {
            var self = this;

            // 点击遮罩关闭
            this._elements.container.addEventListener('click', function(e) {
                if (e.target === self._elements.container) {
                    self.close();
                }
            });

            // 控制项点击
            this._elements.items.forEach(function(item) {
                item.addEventListener('click', function() {
                    var action = this.dataset.action;
                    if (action) {
                        self.handleAction(action);
                    }
                });
            });

            // 监听主题切换事件
            document.addEventListener('theme-changed', function(e) {
                self.updateUI();
            });
        },

        /**
         * 处理控制操作
         */
        handleAction: function(action) {
            switch (action) {
                case 'wifi':
                    this._state.wifi = !this._state.wifi;
                    this.showToast(this._state.wifi ? 'Wi-Fi 已开启' : 'Wi-Fi 已关闭');
                    break;
                case 'bluetooth':
                    this._state.bluetooth = !this._state.bluetooth;
                    this.showToast(this._state.bluetooth ? '蓝牙已开启' : '蓝牙已关闭');
                    break;
                case 'brightness':
                    this._state.brightness = this._state.brightness >= 100 ? 20 : this._state.brightness + 20;
                    this.showToast('亮度: ' + this._state.brightness + '%');
                    break;
                case 'theme':
                    if (window.ThemeManager) {
                        var newTheme = window.ThemeManager.toggle();
                        this.showToast('切换至 ' + (newTheme === 'dark' ? '深色' : '浅色') + ' 主题');
                    }
                    break;
                case 'volume':
                    this._state.volume = this._state.volume >= 100 ? 0 : this._state.volume + 20;
                    this.showToast('音量: ' + this._state.volume + '%');
                    break;
                case 'lock':
                    // 锁定屏幕
                    if (window.MobileApp && window.MobileApp.lock) {
                        window.MobileApp.lock();
                        this.showToast('已锁定');
                        this.close();
                    }
                    break;
                case 'power':
                    this.showToast('关机');
                    // 模拟关机
                    setTimeout(function() {
                        var overlay = document.getElementById('shutdownOverlay');
                        if (overlay) {
                            overlay.style.display = 'flex';
                            setTimeout(function() {
                                document.body.style.opacity = '0';
                                document.body.style.transition = 'opacity 0.5s';
                            }, 1500);
                        }
                    }, 300);
                    break;
                default:
                    console.log('[Control] 未知操作:', action);
            }

            // 保存状态
            if (window.MobileStorage) {
                window.MobileStorage.set('controlState', this._state);
            }

            this.updateUI();
        },

        /**
         * 更新 UI 状态
         */
        updateUI: function() {
            var self = this;
            this._elements.items.forEach(function(item) {
                var action = item.dataset.action;
                var isActive = false;
                var iconEl = item.querySelector('.control-icon');
                var labelEl = item.querySelector('.control-label');

                switch (action) {
                    case 'wifi':
                        isActive = self._state.wifi;
                        break;
                    case 'bluetooth':
                        isActive = self._state.bluetooth;
                        break;
                    case 'brightness':
                        isActive = self._state.brightness > 30;
                        break;
                    case 'theme':
                        isActive = window.ThemeManager ?
                            window.ThemeManager.isDark() : false;
                        break;
                    case 'volume':
                        isActive = self._state.volume > 0;
                        break;
                }

                item.classList.toggle('active', isActive);

                // 更新标签文字
                if (labelEl) {
                    var labels = {
                        'wifi': isActive ? 'Wi-Fi 已开' : 'Wi-Fi',
                        'bluetooth': isActive ? '蓝牙已开' : '蓝牙',
                        'brightness': '亮度 ' + self._state.brightness + '%',
                        'theme': window.ThemeManager ?
                            (window.ThemeManager.isDark() ? '深色' : '浅色') : '主题',
                        'volume': '音量 ' + self._state.volume + '%',
                        'lock': '锁定',
                        'power': '关机'
                    };
                    labelEl.textContent = labels[action] || action;
                }
            });
        },

        /**
         * Toast 提示
         */
        showToast: function(message) {
            var existing = document.querySelector('.android-toast');
            if (existing) existing.remove();

            var toast = document.createElement('div');
            toast.className = 'android-toast';
            toast.textContent = message;
            document.body.appendChild(toast);

            setTimeout(function() {
                toast.style.opacity = '0';
                toast.style.transform = 'translateX(-50%) translateY(20px)';
                toast.style.transition = 'all 0.3s ease';
                setTimeout(function() {
                    if (toast.parentNode) toast.remove();
                }, 300);
            }, 1500);
        },

        /**
         * 打开控制中心
         */
        open: function() {
            if (this._elements.container) {
                this._elements.container.classList.add('active');
                this._isOpen = true;
                this.updateUI();
            }
        },

        /**
         * 关闭控制中心
         */
        close: function() {
            if (this._elements.container) {
                this._elements.container.classList.remove('active');
                this._isOpen = false;
            }
        },

        /**
         * 切换控制中心
         */
        toggle: function() {
            if (this._isOpen) {
                this.close();
            } else {
                this.open();
            }
        },

        /**
         * 获取状态
         */
        getState: function() {
            return this._state;
        }
    };

    window.ControlManager = ControlManager;

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            ControlManager.init();
        });
    } else {
        ControlManager.init();
    }

    console.log('[Control] 模块已加载');

})();