/**
 * 移动端通知中心模块
 * 真实通知列表和管理
 */

(function() {
    'use strict';

    var NotificationManager = {
        _elements: {},
        _isOpen: false,

        /**
         * 初始化通知中心
         */
        init: function() {
            this._elements.container = document.getElementById('notificationCenter');
            this._elements.list = document.getElementById('notificationList');
            this._elements.clearBtn = document.querySelector('.notification-clear');
            this._elements.badge = document.getElementById('notificationBadge');

            if (!this._elements.container) {
                console.warn('[Notification] 通知中心 DOM 不存在');
                return;
            }

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

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

            if (this._elements.clearBtn) {
                this._elements.clearBtn.addEventListener('click', function() {
                    self.clearAll();
                });
            }

            this._elements.container.addEventListener('click', function(e) {
                if (e.target === self._elements.container) {
                    self.close();
                }
            });

            document.addEventListener('notification-added', function(e) {
                self.render();
                self.updateBadge();
            });
        },

        /**
         * 渲染通知列表
         */
        render: function() {
            if (!this._elements.list) return;

            var notifications = [];
            if (window.MobileStorage) {
                notifications = window.MobileStorage.get('notifications', []);
            } else {
                try {
                    var stored = localStorage.getItem('fluentos_mobile');
                    if (stored) {
                        var data = JSON.parse(stored);
                        notifications = data.notifications || [];
                    }
                } catch (e) {
                    // 忽略
                }
            }

            if (notifications.length === 0) {
                this._elements.list.innerHTML =
                    '<div class="notification-empty">暂无通知</div>';
                return;
            }

            var html = '';
            var self = this;
            notifications.forEach(function(n) {
                var unreadClass = n.read ? '' : 'unread';
                var iconText = n.icon || '[Info]';
                html += `
                    <div class="notification-item ${unreadClass}" data-id="${n.id}">
                        <div class="notification-icon">${iconText}</div>
                        <div class="notification-content">
                            <div class="notification-title">${n.title || '通知'}</div>
                            <div class="notification-body">${n.body || ''}</div>
                            <div class="notification-time">${n.time || ''}</div>
                        </div>
                        ${n.read ? '' : '<button class="notification-mark-read">标记已读</button>'}
                    </div>
                `;
            });

            this._elements.list.innerHTML = html;

            var items = this._elements.list.querySelectorAll('.notification-item');
            items.forEach(function(item) {
                var markBtn = item.querySelector('.notification-mark-read');
                if (markBtn) {
                    markBtn.addEventListener('click', function(e) {
                        e.stopPropagation();
                        var id = parseInt(item.dataset.id);
                        self.markRead(id);
                    });
                }
            });

            this.updateBadge();
        },

        /**
         * 标记通知为已读
         */
        markRead: function(id) {
            if (window.MobileStorage) {
                window.MobileStorage.markNotificationRead(id);
                this.render();
            }
        },

        /**
         * 清除所有通知
         */
        clearAll: function() {
            if (window.MobileStorage) {
                window.MobileStorage.clearNotifications();
            } else {
                try {
                    var stored = localStorage.getItem('fluentos_mobile');
                    if (stored) {
                        var data = JSON.parse(stored);
                        data.notifications = [];
                        localStorage.setItem('fluentos_mobile', JSON.stringify(data));
                    }
                } catch (e) {
                    // 忽略
                }
            }
            this.render();
            this.updateBadge();
        },

        /**
         * 更新未读角标
         */
        updateBadge: function() {
            var count = 0;
            if (window.MobileStorage) {
                count = window.MobileStorage.getUnreadCount();
            } else {
                try {
                    var stored = localStorage.getItem('fluentos_mobile');
                    if (stored) {
                        var data = JSON.parse(stored);
                        var notifications = data.notifications || [];
                        notifications.forEach(function(n) {
                            if (!n.read) count++;
                        });
                    }
                } catch (e) {
                    // 忽略
                }
            }

            if (this._elements.badge) {
                if (count > 0) {
                    this._elements.badge.textContent = count > 99 ? '99+' : count;
                    this._elements.badge.style.display = 'block';
                } else {
                    this._elements.badge.style.display = 'none';
                }
            }

            var event = new CustomEvent('badge-updated', {
                detail: { count: count }
            });
            document.dispatchEvent(event);
        },

        /**
         * 添加通知（外部调用）
         */
        add: function(title, body, icon) {
            if (window.MobileStorage) {
                return window.MobileStorage.addNotification({
                    title: title || '新通知',
                    body: body || '',
                    icon: icon || '[Info]'
                });
            }
            return null;
        },

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

        /**
         * 关闭通知中心
         */
        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();
            }
        },

        /**
         * 获取通知数量
         */
        getCount: function() {
            if (window.MobileStorage) {
                return window.MobileStorage.get('notifications', []).length;
            }
            return 0;
        },

        /**
         * 获取未读数量
         */
        getUnreadCount: function() {
            if (window.MobileStorage) {
                return window.MobileStorage.getUnreadCount();
            }
            return 0;
        }
    };

    window.NotificationManager = NotificationManager;

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

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

})();