<?php
/**
 * HuSNS - 一款免费开源的社交平台
 * 
 * @author  HYR
 * @QQ      281900864
 * @website https://huyourui.com
 * @license MIT
 * @声明    严禁用于违法违规用途
 */

$siteName = Setting::getSiteName();
$themeUrl = $this->themeUrl();
$themePath = $this->themePath();  // 文件系统路径用于 filemtime()
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo Setting::getTitle($title ?? ''); ?></title>
    <meta name="keywords" content="<?php echo $this->escape(Setting::getKeywords()); ?>">
    <meta name="description" content="<?php echo $this->escape($description ?? Setting::getDescription()); ?>">
    
    <!-- OpenGraph SEO -->
    <meta property="og:title" content="<?php echo Setting::getTitle($title ?? ''); ?>">
    <meta property="og:description" content="<?php echo $this->escape($description ?? Setting::getDescription()); ?>">
    <meta property="og:type" content="website">
    
    <!-- Twitter Card -->
    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="<?php echo Setting::getTitle($title ?? ''); ?>">
    <meta name="twitter:description" content="<?php echo $this->escape($description ?? Setting::getDescription()); ?>">
    
    <!-- Theme CSS (External) -->
    <link rel="stylesheet" href="<?php echo $themeUrl; ?>/static/pc/app.css?v=<?php echo @filemtime($themePath . 'static/pc/app.css') ?: time(); ?>">
    
    <!-- Mobile JS Module -->
    <script src="<?php echo $themeUrl; ?>/static/pc/mobile.js?v=<?php echo @filemtime($themePath . 'static/pc/mobile.js') ?: time(); ?>"></script>
    
    <?php $head = Hook::trigger('head', ''); echo is_string($head) ? $head : ''; ?>
    
    <!-- Theme Initialization (Dark Mode) -->
    <script>
        (function() {
            var theme = localStorage.getItem('theme');
            if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
                document.body.classList.add('dark-mode');
            }
        })();
    </script>
</head>
<body>
    <!-- Accessibility: Skip Link -->
    <a href="#main-content" class="skip-link">跳转到主要内容</a>
    
    <!-- Page Content -->
    <?php echo $content; ?>

    <!-- Popup Overlay -->
    <div class="popup-overlay" id="popupOverlay" onclick="hidePublishPopup()" role="presentation"></div>

    <!-- Mobile Publish Popup -->
    <div class="publish-popup" id="mobilePublishPopup" role="dialog" aria-labelledby="popup-title">
        <div class="popup-header">
            <div class="popup-title" id="popup-title">发布动态</div>
            <div class="popup-close" onclick="hidePublishPopup()" role="button" tabindex="0" aria-label="关闭">×</div>
        </div>
        <form id="mobilePublishForm" action="<?php echo $this->url('post/publish'); ?>" method="post">
            <?php echo $this->csrf(); ?>
            <textarea name="content" placeholder="分享你的新鲜事..." rows="4" class="popup-textarea"></textarea>
            <div class="popup-actions">
                <button type="submit" class="btn btn-primary popup-actions-auto">发布</button>
            </div>
        </form>
    </div>

    <!-- Repost Modal -->
    <div class="repost-modal" id="repostModal" role="dialog" aria-labelledby="repost-title">
        <div class="repost-modal-content">
            <div class="repost-modal-header">
                <h3 id="repost-title">转发动态</h3>
                <span class="repost-modal-close" onclick="closeRepostModal()" role="button" tabindex="0" aria-label="关闭">×</span>
            </div>
            <form id="repostForm">
                <input type="hidden" name="csrf_token" value="<?php echo isset($_SESSION['csrf_token']) ? $_SESSION['csrf_token'] : ''; ?>">
                <input type="hidden" name="post_id" id="repostPostId">
                <textarea name="content" placeholder="说点什么吧..." rows="3" data-max-length="<?php echo Setting::getMaxPostLength(); ?>" class="popup-textarea"></textarea>
                <div class="modal-footer">
                    <label class="also-comment-label">
                        <input type="checkbox" name="also_comment" value="1"> 同时评论
                    </label>
                    <div class="char-counter">
                        <span class="char-count">0</span>/<span><?php echo Setting::getMaxPostLength(); ?></span>
                    </div>
                    <button type="submit" class="btn btn-primary">转发</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Edit Modal -->
    <div id="editModal" class="modal" role="dialog" aria-labelledby="edit-title">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="edit-title">编辑动态</h3>
                <span class="modal-close" onclick="closeEditModal()" role="button" tabindex="0" aria-label="关闭">&times;</span>
            </div>
            <form id="editForm">
                <input type="hidden" name="csrf_token" value="<?php echo isset($_SESSION['csrf_token']) ? $_SESSION['csrf_token'] : ''; ?>">
                <input type="hidden" name="id" id="editPostId">
                <div class="popup-actions">
                    <textarea name="content" id="editContent" rows="5" class="popup-textarea-dark" placeholder="请输入内容..."></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="closeEditModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Theme Customizer Panel -->
    <div class="theme-customizer-overlay" id="themeCustomizerOverlay" onclick="closeThemeCustomizer(event)" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9998; display: none;"></div>
    <div class="theme-customizer-panel" id="themeCustomizerPanel" role="dialog" aria-labelledby="theme-customizer-title" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 90%; max-width: 400px; max-height: 80vh; background: #fff; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.2); z-index: 9999; display: none; flex-direction: column; overflow: hidden;">
        <div class="theme-customizer-header">
            <h3 id="theme-customizer-title">自定义主题</h3>
            <span class="theme-customizer-close" onclick="closeThemeCustomizer()" role="button" tabindex="0" aria-label="关闭">×</span>
        </div>
        <div class="theme-customizer-content">
            <div class="theme-customizer-section">
                <h4>主题颜色</h4>
                <div class="theme-customizer-item">
                    <label for="customPrimaryColor">主题色</label>
                    <div class="color-picker-wrapper">
                        <input type="color" id="customPrimaryColor" value="#1677ff" class="color-picker">
                        <span class="color-value" id="customPrimaryColorValue">#1677ff</span>
                    </div>
                </div>
                <div class="theme-customizer-item">
                    <label for="customSuccessColor">成功色</label>
                    <div class="color-picker-wrapper">
                        <input type="color" id="customSuccessColor" value="#52c41a" class="color-picker">
                        <span class="color-value" id="customSuccessColorValue">#52c41a</span>
                    </div>
                </div>
                <div class="theme-customizer-item">
                    <label for="customErrorColor">错误色</label>
                    <div class="color-picker-wrapper">
                        <input type="color" id="customErrorColor" value="#ff4d4f" class="color-picker">
                        <span class="color-value" id="customErrorColorValue">#ff4d4f</span>
                    </div>
                </div>
            </div>
            <div class="theme-customizer-section">
                <h4>背景颜色</h4>
                <div class="theme-customizer-item">
                    <label for="customBgPage">页面背景</label>
                    <div class="color-picker-wrapper">
                        <input type="color" id="customBgPage" value="#f5f7fa" class="color-picker">
                        <span class="color-value" id="customBgPageValue">#f5f7fa</span>
                    </div>
                </div>
                <div class="theme-customizer-item">
                    <label for="customBgCard">卡片背景</label>
                    <div class="color-picker-wrapper">
                        <input type="color" id="customBgCard" value="#ffffff" class="color-picker">
                        <span class="color-value" id="customBgCardValue">#ffffff</span>
                    </div>
                </div>
            </div>
            <div class="theme-customizer-presets">
                <h4>预设主题</h4>
                <div class="preset-buttons">
                    <button type="button" class="preset-btn active" data-preset="default" onclick="applyThemePreset('default')" style="background:#1677ff;">默认</button>
                    <button type="button" class="preset-btn" data-preset="green" onclick="applyThemePreset('green')" style="background:#07c160;">绿色</button>
                    <button type="button" class="preset-btn" data-preset="purple" onclick="applyThemePreset('purple')" style="background:#722ed1;">紫色</button>
                    <button type="button" class="preset-btn" data-preset="red" onclick="applyThemePreset('red')" style="background:#eb2f96;">红色</button>
                    <button type="button" class="preset-btn" data-preset="orange" onclick="applyThemePreset('orange')" style="background:#fa8c16;">橙色</button>
                    <button type="button" class="preset-btn" data-preset="cyan" onclick="applyThemePreset('cyan')" style="background:#13c2c2;">青色</button>
                </div>
            </div>
        </div>
        <div class="theme-customizer-footer">
            <button type="button" class="btn" onclick="resetThemeColors()">重置</button>
            <button type="button" class="btn btn-primary" onclick="saveThemeColors()">保存</button>
        </div>
    </div>

    <!-- Application Scripts -->
    <script>
        var BASE_URL = '<?php echo Helper::getBaseUrl(); ?>';
        var THEME_URL = '<?php echo $themeUrl; ?>';
        
        // ========== Theme Toggle ==========
        document.addEventListener('DOMContentLoaded', function() {
            var themeToggle = document.getElementById('themeToggle');
            if (themeToggle) {
                themeToggle.addEventListener('click', function() {
                    document.body.style.transition = 'background-color 0.3s ease, color 0.3s ease';
                    document.querySelectorAll('.container, .sidebar, .side-card, .user-card, .post, .comment-box').forEach(function(el) {
                        el.style.transition = 'background-color 0.3s ease, border-color 0.3s ease';
                    });
                    document.body.classList.toggle('dark-mode');
                    var isDark = document.body.classList.contains('dark-mode');
                    localStorage.setItem('theme', isDark ? 'dark' : 'light');
                    this.textContent = isDark ? '☀️' : '🌙';
                    this.setAttribute('aria-label', isDark ? '切换到浅色模式' : '切换到深色模式');
                });
            }
        });
        
        // ========== Mobile Publish Popup ==========
        function showPublishPopup() {
            document.getElementById('popupOverlay').style.display = 'block';
            document.getElementById('mobilePublishPopup').classList.add('show');
            document.getElementById('popupOverlay').setAttribute('aria-hidden', 'false');
        }
        
        function hidePublishPopup() {
            document.getElementById('mobilePublishPopup').classList.remove('show');
            setTimeout(function() {
                document.getElementById('popupOverlay').style.display = 'none';
                document.getElementById('popupOverlay').setAttribute('aria-hidden', 'true');
            }, 300);
        }
        
        // ========== Notification Count Update ==========
        function updateNotificationCount() {
            fetch(BASE_URL + '/?r=notification/getUnreadCount')
                .then(function(response) { return response.json(); })
                .then(function(data) {
                    if (data.code === 0) {
                        var badge = document.getElementById('notificationBadge');
                        if (badge) {
                            if (data.data.count > 0) {
                                badge.textContent = data.data.count > 99 ? '99+' : data.data.count;
                                badge.style.display = 'inline';
                            } else {
                                badge.style.display = 'none';
                            }
                        }
                    }
                });
        }
        
        <?php if (isset($_SESSION['user_id'])): ?>
        updateNotificationCount();
        setInterval(updateNotificationCount, 60000);
        <?php endif; ?>

        // ========== Post Actions ==========
        document.addEventListener('click', function(e) {
            var btn = e.target.closest('.action-btn');
            if (!btn) return;
            
            var postId = btn.dataset.id;
            if (!postId) return;
            
            // Like
            if (btn.classList.contains('like-btn')) {
                likePost(postId, btn);
            }
            // Comment
            else if (btn.classList.contains('comment-btn')) {
                toggleCommentBox(btn);
            }
            // Repost
            else if (btn.classList.contains('repost-btn')) {
                showRepostModal(postId);
            }
            // Favorite
            else if (btn.classList.contains('favorite-btn')) {
                favoritePost(postId, btn);
            }
            // More Menu
            else if (btn.classList.contains('more-btn')) {
                toggleMoreMenu(btn);
            }
        });

        function likePost(postId, btn) {
            var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                           document.querySelector('input[name="csrf_token"]')?.value || '';
            fetch(BASE_URL + '/?r=post/like', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'post_id=' + postId + '&csrf_token=' + csrfToken
            }).then(function(r) { return r.json(); })
              .then(function(data) {
                if (data.code === 0) {
                    var isLiked = data.data.action === 'liked';
                    btn.classList.toggle('liked', isLiked);
                    var countEl = btn.querySelector('.action-count');
                    if (countEl) {
                        var count = parseInt(countEl.textContent) || 0;
                        countEl.textContent = isLiked ? count + 1 : Math.max(0, count - 1);
                    }
                }
            });
        }

        function favoritePost(postId, btn) {
            var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                           document.querySelector('input[name="csrf_token"]')?.value || '';
            fetch(BASE_URL + '/?r=post/favorite', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'post_id=' + postId + '&csrf_token=' + csrfToken
            }).then(function(r) { return r.json(); })
              .then(function(data) {
                if (data.code === 0) {
                    btn.classList.toggle('favorited', data.data.action === 'favorited');
                }
            });
        }

        function toggleCommentBox(btn) {
            var post = btn.closest('.post');
            var commentBox = post.querySelector('.comment-box');
            if (commentBox) {
                var isShow = commentBox.classList.toggle('show');
                if (isShow) {
                    loadComments(post.dataset.id, commentBox);
                    commentBox.querySelector('.comment-input')?.focus();
                }
            }
        }

        function loadComments(postId, commentBox) {
            var listEl = commentBox.querySelector('.comment-list');
            if (listEl.dataset.loaded) return;
            listEl.dataset.loaded = 'true';
            
            fetch(BASE_URL + '/?r=comment/list&post_id=' + postId)
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.code === 0 && data.data) {
                        listEl.innerHTML = data.data.map(function(c) {
                            return '<div class="comment-item">' +
                                '<a href="' + BASE_URL + '/?r=user/profile&id=' + c.user_id + '" class="comment-user">' + c.username + '</a>' +
                                '<span class="comment-text">：' + c.content + '</span>' +
                                '</div>';
                        }).join('');
                    }
                });
        }

        function submitComment(postId, btn) {
            var commentForm = btn.closest('.comment-form');
            var commentBox = btn.closest('.comment-box');
            var input = commentForm ? commentForm.querySelector('textarea[name="content"]') : commentBox.querySelector('textarea');
            var content = input ? input.value.trim() : '';
            if (!content) return;
            
            var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                           document.querySelector('input[name="csrf_token"]')?.value || 
                           commentForm?.querySelector('input[name="csrf_token"]')?.value || '';
            fetch(BASE_URL + '/?r=comment/add', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'post_id=' + postId + '&content=' + encodeURIComponent(content) + '&csrf_token=' + csrfToken
            }).then(function(r) { return r.json(); })
              .then(function(data) {
                if (data.code === 0) {
                    var listEl = commentBox.querySelector('.comment-list');
                    if (listEl) {
                        var item = document.createElement('div');
                        item.className = 'comment-item';
                        item.innerHTML = '<span class="comment-user"><?php echo isset($_SESSION['username']) ? $this->escape($_SESSION['username']) : ''; ?></span><span class="comment-text">：' + content + '</span>';
                        listEl.appendChild(item);
                    }
                    if (input) input.value = '';
                    showToast('评论成功', 'success');
                } else {
                    showToast(data.message || '评论失败', 'error');
                }
            }).catch(function(err) {
                showToast('网络错误，请重试', 'error');
            });
        }

        function showRepostModal(postId) {
            document.getElementById('repostPostId').value = postId;
            document.getElementById('repostModal').style.display = 'flex';
        }

        function closeRepostModal() {
            document.getElementById('repostModal').style.display = 'none';
        }

        function toggleMoreMenu(btn) {
            var menu = btn.nextElementSibling;
            document.querySelectorAll('.action-more-menu.show').forEach(function(m) {
                if (m !== menu) m.classList.remove('show');
            });
            menu.classList.toggle('show');
        }

        // ========== More Menu Actions ==========
        document.addEventListener('click', function(e) {
            var item = e.target.closest('.more-item');
            if (!item) {
                if (!e.target.closest('.more-btn')) {
                    document.querySelectorAll('.action-more-menu.show').forEach(function(m) {
                        m.classList.remove('show');
                    });
                }
                return;
            }
            
            var postId = item.dataset.id;
            var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                           document.querySelector('input[name="csrf_token"]')?.value || '';
            
            if (item.classList.contains('delete-post')) {
                if (confirm('确定删除这条动态？')) {
                    fetch(BASE_URL + '/?r=post/delete', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: 'id=' + postId + '&csrf_token=' + csrfToken
                    }).then(function(r) { return r.json(); })
                      .then(function(data) {
                        if (data.code === 0) {
                            var post = document.querySelector('.post[data-id="' + postId + '"]');
                            if (post) post.remove();
                        } else {
                            alert(data.message || '删除失败');
                        }
                    });
                }
            } else if (item.classList.contains('edit-post')) {
                var post = document.querySelector('.post[data-id="' + postId + '"]');
                var content = post.querySelector('.post-content').textContent.trim();
                document.getElementById('editPostId').value = postId;
                document.getElementById('editContent').value = content;
                document.getElementById('editModal').style.display = 'flex';
            } else if (item.classList.contains('pin-post')) {
                var action = parseInt(item.dataset.pinned) ? 'unpin' : 'pin';
                fetch(BASE_URL + '/?r=admin/post/pin', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: 'id=' + postId + '&action=' + action + '&csrf_token=' + csrfToken
                }).then(function(r) { return r.json(); })
                  .then(function(data) {
                    if (data.code === 0) location.reload();
                });
            } else if (item.classList.contains('feature-post')) {
                var action = parseInt(item.dataset.featured) ? 'unfeature' : 'feature';
                fetch(BASE_URL + '/?r=admin/post/feature', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: 'id=' + postId + '&action=' + action + '&csrf_token=' + csrfToken
                }).then(function(r) { return r.json(); })
                  .then(function(data) {
                    if (data.code === 0) location.reload();
                });
            }
            
            document.querySelectorAll('.action-more-menu.show').forEach(function(m) {
                m.classList.remove('show');
            });
        });

        // ========== Sign In Button ==========
        document.addEventListener('DOMContentLoaded', function() {
            var signInBtn = document.getElementById('signInBtn');
            if (signInBtn) {
                signInBtn.addEventListener('click', function() {
                    var btn = this;
                    if (btn.disabled) return;
                    
                    var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                                   document.querySelector('input[name="csrf_token"]')?.value || '';
                    
                    fetch(BASE_URL + '/?r=user/signIn', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: 'csrf_token=' + csrfToken
                    }).then(function(r) { return r.json(); })
                      .then(function(data) {
                        if (data.code === 0) {
                            showToast('签到成功！获得 ' + (data.data.points || 10) + ' 积分', 'success');
                            btn.disabled = true;
                            btn.textContent = '已签到';
                            var streakCount = document.querySelector('.streak-count');
                            if (streakCount && data.data.continuous_days) {
                                streakCount.textContent = data.data.continuous_days + '天';
                            }
                        } else {
                            showToast(data.message || '签到失败', 'error');
                        }
                    }).catch(function(err) {
                        showToast('网络错误，请重试', 'error');
                    });
                });
            }
        });

        // ========== Repost Form Submit ==========
        document.getElementById('repostForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            var form = e.target;
            var postId = document.getElementById('repostPostId').value;
            var content = form.querySelector('textarea[name="content"]').value;
            var alsoComment = form.querySelector('input[name="also_comment"]').checked;
            
            var csrfToken = form.querySelector('input[name="csrf_token"]')?.value || '';
            
            fetch(BASE_URL + '/?r=post/repost', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'post_id=' + postId + '&content=' + encodeURIComponent(content) + '&also_comment=' + (alsoComment ? 1 : 0) + '&csrf_token=' + csrfToken
            }).then(function(r) { return r.json(); })
              .then(function(data) {
                if (data.code === 0) {
                    showToast('转发成功', 'success');
                    closeRepostModal();
                    location.reload();
                } else {
                    showToast(data.message || '转发失败', 'error');
                }
            }).catch(function(err) {
                showToast('网络错误，请重试', 'error');
            });
        });

        // ========== Comment Submit Button ==========
        document.addEventListener('click', function(e) {
            var btn = e.target.closest('.comment-submit, .comment-form button[type="submit"]');
            if (btn && !btn.disabled) {
                var postId = btn.dataset.postId;
                if (!postId) {
                    var form = btn.closest('.comment-form');
                    if (form) postId = form.dataset.postId;
                }
                if (postId) {
                    submitComment(postId, btn);
                }
            }
        });

        // ========== Comment Enter Key Submit ==========
        document.addEventListener('keypress', function(e) {
            var input = e.target;
            if (input.tagName === 'TEXTAREA' && input.name === 'content' && e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                var commentBox = input.closest('.comment-box');
                var form = input.closest('.comment-form');
                var btn = commentBox.querySelector('button[type="submit"]') || (form ? form.querySelector('button[type="submit"]') : null);
                var postId = form ? form.dataset.postId : input.dataset.postId;
                if (postId) {
                    submitComment(postId, btn);
                }
            }
        });

        // ========== Video Play ==========
        function playVideo(element) {
            var video = element.querySelector('video');
            if (video) {
                if (video.paused) {
                    video.play();
                    element.querySelector('.video-overlay').innerHTML = '⏸';
                } else {
                    video.pause();
                    element.querySelector('.video-overlay').innerHTML = '▶';
                }
            }
        }

        // ========== Edit Modal ==========
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // ========== Theme Customizer Functions ==========
        var themePresets = {
            default: { primary: '#1677ff', primaryHover: '#4096ff', success: '#52c41a', error: '#ff4d4f', bgPage: '#f5f7fa', bgCard: '#ffffff' },
            green: { primary: '#07c160', primaryHover: '#10b263', success: '#52c41a', error: '#ff4d4f', bgPage: '#f5f9f7', bgCard: '#ffffff' },
            purple: { primary: '#722ed1', primaryHover: '#8b3ddb', success: '#52c41a', error: '#ff4d4f', bgPage: '#f9f5ff', bgCard: '#ffffff' },
            red: { primary: '#eb2f96', primaryHover: '#f342a3', success: '#52c41a', error: '#f5222d', bgPage: '#fff1f3', bgCard: '#ffffff' },
            orange: { primary: '#fa8c16', primaryHover: '#ff9a3c', success: '#52c41a', error: '#ff4d4f', bgPage: '#fffbf0', bgCard: '#ffffff' },
            cyan: { primary: '#13c2c2', primaryHover: '#2ebdbc', success: '#52c41a', error: '#ff4d4f', bgPage: '#f0fffe', bgCard: '#ffffff' }
        };

        function loadSavedTheme() {
            var savedTheme = localStorage.getItem('customTheme');
            if (savedTheme) {
                try {
                    var theme = JSON.parse(savedTheme);
                    applyThemeColors(theme);
                } catch (e) {}
            }
        }

        function applyThemeColors(theme) {
            var root = document.documentElement;
            if (theme.primary) root.style.setProperty('--primary-color', theme.primary);
            if (theme.primaryHover) root.style.setProperty('--primary-hover', theme.primaryHover);
            if (theme.success) root.style.setProperty('--success-color', theme.success);
            if (theme.error) root.style.setProperty('--error-color', theme.error);
            if (theme.bgPage) root.style.setProperty('--bg-page', theme.bgPage);
            if (theme.bgCard) root.style.setProperty('--bg-card', theme.bgCard);
            
            if (document.getElementById('customPrimaryColor')) {
                document.getElementById('customPrimaryColor').value = theme.primary || '#1677ff';
                document.getElementById('customPrimaryColorValue').textContent = theme.primary || '#1677ff';
            }
            if (document.getElementById('customSuccessColor')) {
                document.getElementById('customSuccessColor').value = theme.success || '#52c41a';
                document.getElementById('customSuccessColorValue').textContent = theme.success || '#52c41a';
            }
            if (document.getElementById('customErrorColor')) {
                document.getElementById('customErrorColor').value = theme.error || '#ff4d4f';
                document.getElementById('customErrorColorValue').textContent = theme.error || '#ff4d4f';
            }
            if (document.getElementById('customBgPage')) {
                document.getElementById('customBgPage').value = theme.bgPage || '#f5f7fa';
                document.getElementById('customBgPageValue').textContent = theme.bgPage || '#f5f7fa';
            }
            if (document.getElementById('customBgCard')) {
                document.getElementById('customBgCard').value = theme.bgCard || '#ffffff';
                document.getElementById('customBgCardValue').textContent = theme.bgCard || '#ffffff';
            }
        }

        function applyThemePreset(presetName) {
            var preset = themePresets[presetName];
            if (!preset) return;
            applyThemeColors(preset);
            document.querySelectorAll('.preset-btn').forEach(function(btn) {
                btn.classList.toggle('active', btn.dataset.preset === presetName);
            });
        }

        function saveThemeColors() {
            var theme = {
                primary: document.getElementById('customPrimaryColor').value,
                primaryHover: document.getElementById('customPrimaryColor').value,
                success: document.getElementById('customSuccessColor').value,
                error: document.getElementById('customErrorColor').value,
                bgPage: document.getElementById('customBgPage').value,
                bgCard: document.getElementById('customBgCard').value
            };
            localStorage.setItem('customTheme', JSON.stringify(theme));
            closeThemeCustomizer();
        }

        function resetThemeColors() {
            applyThemePreset('default');
        }

        function closeThemeCustomizer(e) {
            if (e && e.target !== document.getElementById('themeCustomizerOverlay')) return;
            document.getElementById('themeCustomizerOverlay').classList.remove('show');
            document.getElementById('themeCustomizerPanel').classList.remove('show');
        }

        document.addEventListener('DOMContentLoaded', function() {
            var customizerBtn = document.getElementById('themeCustomizerBtn');
            if (customizerBtn) {
                customizerBtn.addEventListener('click', function() {
                    document.getElementById('themeCustomizerOverlay').classList.add('show');
                    document.getElementById('themeCustomizerPanel').classList.add('show');
                    var root = document.documentElement;
                    var currentTheme = {
                        primary: getComputedStyle(root).getPropertyValue('--primary-color').trim() || '#1677ff',
                        success: getComputedStyle(root).getPropertyValue('--success-color').trim() || '#52c41a',
                        error: getComputedStyle(root).getPropertyValue('--error-color').trim() || '#ff4d4f',
                        bgPage: getComputedStyle(root).getPropertyValue('--bg-page').trim() || '#f5f7fa',
                        bgCard: getComputedStyle(root).getPropertyValue('--bg-card').trim() || '#ffffff'
                    };
                    applyThemeColors(currentTheme);
                });
            }
            loadSavedTheme();
        });
    </script>
</body>
</html>