/**
 * 移动端本地存储模块
 * 使用 localStorage 保存设置、PIN码、主题等
 */

(function() {
    'use strict';

    var STORAGE_KEY = 'fluentos_mobile';

    var defaultSettings = {
        pin: '1234',
        theme: 'dark',
        notifications: [],
        wallpaper: 'default',
        apps: {},
        language: 'zh-CN'
    };

    var MobileStorage = {
        _data: null,

        /**
         * 初始化存储
         */
        init: function() {
            try {
                var stored = localStorage.getItem(STORAGE_KEY);
                if (stored) {
                    this._data = JSON.parse(stored);
                    for (var key in defaultSettings) {
                        if (!(key in this._data)) {
                            this._data[key] = defaultSettings[key];
                        }
                    }
                } else {
                    this._data = JSON.parse(JSON.stringify(defaultSettings));
                    this.save();
                }
                console.log('[Storage] 存储初始化成功');
                return true;
            } catch (e) {
                console.error('[Storage] 初始化失败:', e);
                this._data = JSON.parse(JSON.stringify(defaultSettings));
                return false;
            }
        },

        /**
         * 保存数据
         */
        save: function() {
            try {
                localStorage.setItem(STORAGE_KEY, JSON.stringify(this._data));
                return true;
            } catch (e) {
                console.error('[Storage] 保存失败:', e);
                return false;
            }
        },

        /**
         * 获取设置
         */
        get: function(key, defaultValue) {
            if (this._data && key in this._data) {
                return this._data[key];
            }
            return defaultValue;
        },

        /**
         * 设置值
         */
        set: function(key, value) {
            if (!this._data) {
                this.init();
            }
            this._data[key] = value;
            return this.save();
        },

        /**
         * 获取全部数据
         */
        getAll: function() {
            return this._data || JSON.parse(JSON.stringify(defaultSettings));
        },

        /**
         * 重置所有数据
         */
        reset: function() {
            this._data = JSON.parse(JSON.stringify(defaultSettings));
            return this.save();
        },

        /**
         * 添加通知
         */
        addNotification: function(notification) {
            var notifications = this.get('notifications', []);
            notifications.unshift({
                id: Date.now(),
                time: new Date().toLocaleString(),
                read: false,
                title: notification.title || '通知',
                body: notification.body || '',
                icon: notification.icon || ''
            });
            if (notifications.length > 50) {
                notifications = notifications.slice(0, 50);
            }
            this.set('notifications', notifications);
            var event = new CustomEvent('notification-added', {
                detail: { notification: notifications[0] }
            });
            document.dispatchEvent(event);
            return notifications[0];
        },

        /**
         * 标记通知为已读
         */
        markNotificationRead: function(id) {
            var notifications = this.get('notifications', []);
            var found = false;
            notifications.forEach(function(n) {
                if (n.id === id) {
                    n.read = true;
                    found = true;
                }
            });
            if (found) {
                this.set('notifications', notifications);
            }
            return found;
        },

        /**
         * 清除所有通知
         */
        clearNotifications: function() {
            this.set('notifications', []);
            return true;
        },

        /**
         * 获取未读通知数
         */
        getUnreadCount: function() {
            var notifications = this.get('notifications', []);
            var count = 0;
            notifications.forEach(function(n) {
                if (!n.read) count++;
            });
            return count;
        }
    };

    window.MobileStorage = MobileStorage;

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

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

})();