/**
 * 移动端初始化入口
 * 整合所有移动端模块：存储、主题、通知、控制、应用管理
 */

(function() {
    'use strict';

    var CONFIG = {
        mobileBreakpoint: 768,
        enableNavBar: true,
        enableWindowAdapter: true,
        enableIconAdapter: true,
        forceMobile: false,
        verbose: true
    };

    function isMobile() {
        if (CONFIG.forceMobile) return true;
        return window.innerWidth <= CONFIG.mobileBreakpoint;
    }

    function isTouchDevice() {
        return ('ontouchstart' in window) ||
               (navigator.maxTouchPoints > 0) ||
               (navigator.msMaxTouchPoints > 0);
    }

    function log(message, type) {
        if (!CONFIG.verbose) return;
        var prefix = '[MobileInit]';
        switch (type) {
            case 'info':
                console.log(prefix + ' ' + message);
                break;
            case 'warn':
                console.warn(prefix + ' [WARN] ' + message);
                break;
            case 'error':
                console.error(prefix + ' [ERROR] ' + message);
                break;
            case 'success':
                console.log(prefix + ' [OK] ' + message);
                break;
            default:
                console.log(prefix + ' ' + message);
        }
    }

    var MobileInit = function() {
        this.isMobile = isMobile();
        this.isTouch = isTouchDevice();
        this.initialized = false;
        this.modules = {};
        this.modulesLoaded = false;
        this.startTime = Date.now();

        log('检测到移动端: ' + this.isMobile + ', 触摸设备: ' + this.isTouch);

        if (!this.isMobile) {
            log('桌面端模式，跳过移动端初始化');
            document.documentElement.classList.add('desktop-mode');
            return;
        }

        this.init();
    };

    MobileInit.prototype.init = function() {
        if (this.initialized) return;
        this.initialized = true;
        log('开始移动端初始化...');
        this.addMobileClass();
        this.waitForDependencies();
    };

    MobileInit.prototype.addMobileClass = function() {
        document.documentElement.classList.add('mobile-mode');
        document.documentElement.dataset.mobile = 'true';
        document.documentElement.dataset.touch = String(this.isTouch);

        var vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', vh + 'px');

        var self = this;
        window.addEventListener('resize', function() {
            var newVh = window.innerHeight * 0.01;
            document.documentElement.style.setProperty('--vh', newVh + 'px');
        });

        log('移动端标识已添加');
    };

    MobileInit.prototype.waitForDependencies = function() {
        var self = this;

        var deps = [
            'MobileStorage',
            'ThemeManager',
            'NotificationManager',
            'ControlManager',
            'AppsManager',
            'MobileIconAdapter',
            'MobileWindowAdapter',
            'AndroidNavigation'
        ];

        var allLoaded = function() {
            var loaded = 0;
            deps.forEach(function(name) {
                if (window[name]) loaded++;
            });
            return loaded >= deps.length;
        };

        if (allLoaded()) {
            this.loadModules();
            return;
        }

        log('等待依赖模块加载...');

        var checkInterval = setInterval(function() {
            if (allLoaded()) {
                clearInterval(checkInterval);
                log('所有依赖已加载');
                self.loadModules();
            }
        }, 50);

        setTimeout(function() {
            clearInterval(checkInterval);
            if (!self.modulesLoaded) {
                log('依赖加载超时，强制加载模块', 'warn');
                self.loadModules();
            }
        }, 10000);
    };

    MobileInit.prototype.loadModules = function() {
        if (this.modulesLoaded) return;
        this.modulesLoaded = true;

        log('加载移动端模块...');

        var moduleMap = {
            storage: 'MobileStorage',
            theme: 'ThemeManager',
            notification: 'NotificationManager',
            control: 'ControlManager',
            apps: 'AppsManager',
            icon: 'MobileIconAdapter',
            window: 'MobileWindowAdapter',
            nav: 'AndroidNavigation'
        };

        for (var key in moduleMap) {
            var name = moduleMap[key];
            if (window[name]) {
                this.modules[key] = window[name];
                log('模块已注册: ' + name, 'success');
            } else {
                log('模块未找到: ' + name, 'warn');
            }
        }

        this.onComplete();
    };

    MobileInit.prototype.onComplete = function() {
        var elapsed = Date.now() - this.startTime;

        log('========================================');
        log('移动端初始化完成！', 'success');
        log('   耗时: ' + elapsed + 'ms');
        log('   模块:');
        log('     存储: ' + (this.modules.storage ? '[OK]' : '[FAIL]'));
        log('     主题: ' + (this.modules.theme ? '[OK]' : '[FAIL]'));
        log('     通知: ' + (this.modules.notification ? '[OK]' : '[FAIL]'));
        log('     控制: ' + (this.modules.control ? '[OK]' : '[FAIL]'));
        log('     应用: ' + (this.modules.apps ? '[OK]' : '[FAIL]'));
        log('     图标: ' + (this.modules.icon ? '[OK]' : '[FAIL]'));
        log('     窗口: ' + (this.modules.window ? '[OK]' : '[FAIL]'));
        log('     导航: ' + (this.modules.nav ? '[OK]' : '[FAIL]'));
        log('   设备信息:');
        log('     移动端: ' + this.isMobile);
        log('     触摸设备: ' + this.isTouch);
        log('     窗口宽度: ' + window.innerWidth + 'px');
        log('========================================');

        var event = new CustomEvent('mobile-ready', {
            detail: {
                isMobile: this.isMobile,
                isTouch: this.isTouch,
                modules: this.modules,
                elapsed: elapsed,
                timestamp: Date.now()
            }
        });
        document.dispatchEvent(event);

        log('移动端已就绪', 'success');
    };

    MobileInit.prototype.getState = function() {
        return {
            isMobile: this.isMobile,
            isTouch: this.isTouch,
            initialized: this.initialized,
            modulesLoaded: this.modulesLoaded,
            modules: {
                storage: !!this.modules.storage,
                theme: !!this.modules.theme,
                notification: !!this.modules.notification,
                control: !!this.modules.control,
                apps: !!this.modules.apps,
                icon: !!this.modules.icon,
                window: !!this.modules.window,
                nav: !!this.modules.nav
            },
            elapsed: Date.now() - this.startTime
        };
    };

    MobileInit.prototype.reload = function() {
        log('重新加载移动端模块...');
        this.modulesLoaded = false;
        this.modules = {};
        this.loadModules();
    };

    function createMobileInit() {
        if (window.MobileInit) {
            return window.MobileInit;
        }

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                window.MobileInit = new MobileInit();
            });
        } else {
            window.MobileInit = new MobileInit();
        }

        return window.MobileInit;
    }

    createMobileInit();

    if (typeof module !== 'undefined' && module.exports) {
        module.exports = MobileInit;
    }

    window.MobileUtils = {
        isMobile: isMobile,
        isTouch: isTouchDevice(),

        getDeviceInfo: function() {
            return {
                width: window.innerWidth,
                height: window.innerHeight,
                isMobile: isMobile(),
                isTouch: isTouchDevice(),
                userAgent: navigator.userAgent,
                platform: navigator.platform
            };
        },

        getState: function() {
            return window.MobileInit ? window.MobileInit.getState() : null;
        },

        toggleFullscreen: function() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen().catch(function() {});
            } else {
                document.exitFullscreen().catch(function() {});
            }
        },

        vibrate: function(duration) {
            duration = duration || 50;
            if (navigator.vibrate) {
                navigator.vibrate(duration);
            }
        },

        lockOrientation: function(orientation) {
            orientation = orientation || 'portrait';
            if (screen.orientation && screen.orientation.lock) {
                screen.orientation.lock(orientation).catch(function() {});
            }
        }
    };

    console.log('[MobileInit] 已加载');
    console.log('  - MobileUtils.getDeviceInfo()  查看设备信息');
    console.log('  - MobileUtils.getState()       查看初始化状态');
    console.log('  - MobileUtils.toggleFullscreen() 切换全屏');

})();