/*
// 功能：前台用户认证脚本文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。
*/

(function () {
    const QKModal = {
        activeModals: {},
        show: function (id, url, options = {}) {
            if (this.activeModals[id]) { this.bringToFront(id); return; }

            if (url.includes('/admin/login.php') && !url.includes('redirect=')) {
                url += (url.includes('?') ? '&' : '?') + 'redirect=' + encodeURIComponent(window.location.href);
            }

            const config = { width: '400px', height: 'auto', top: '50%', left: '50%', draggable: true, ...options };
            const modal = document.createElement('div');
            modal.id = 'qk-modal-' + id;
            modal.className = 'qk-modal';
            modal.style.cssText = `width:${config.width};height:${config.height};top:${config.top};left:${config.left};z-index:${this.getNextZIndex()};transform:translate(-50%,-50%)`;

            const iframe = document.createElement('iframe');
            iframe.src = `${url}${url.includes('?') ? '&' : '?'}is_modal=1`;
            iframe.style.cssText = 'width:100%;height:100%;display:none;border:none;background:transparent';
            iframe.frameBorder = '0';

            modal.innerHTML = `<div class="qk-modal-drag-handle"></div>
        <button class="qk-modal-close-overlay" onclick="window.QKModal.close('${id}')" title="关闭">&times;</button>
        <div class="qk-modal-body">
          <div class="qk-modal-loading"><div class="qk-spinner"></div><p>正在加载...</p></div>
        </div>`;

            const modalBody = modal.querySelector('.qk-modal-body');
            modalBody.appendChild(iframe);

            document.body.appendChild(modal);
            this.activeModals[id] = modal;

            const loading = modal.querySelector('.qk-modal-loading');
            iframe.onload = () => { loading.style.display = 'none'; iframe.style.display = 'block'; };
            modal.onclick = () => this.bringToFront(id);
            if (config.draggable) { this.makeDraggable(modal, modal.querySelector('.qk-modal-drag-handle')); }
            this.preloadStyles();
        },
        close: function (id, callback) {
            const modal = this.activeModals[id];
            if (modal) { document.body.removeChild(modal); delete this.activeModals[id]; if (callback) callback(); }
        },
        bringToFront: function (id) {
            const modal = this.activeModals[id];
            if (modal) { modal.style.zIndex = this.getNextZIndex(); }
        },
        getNextZIndex: function () {
            let maxZ = 1000;
            Object.values(this.activeModals).forEach(m => { const z = parseInt(m.style.zIndex); if (z > maxZ) maxZ = z; });
            return maxZ + 1;
        },
        makeDraggable: function (modal, handle) {
            let pos1, pos2, pos3, pos4;
            handle.onmousedown = function (e) {
                e.preventDefault();
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDrag;
                document.onmousemove = elementDrag;
                modal.querySelector('iframe').style.pointerEvents = 'none';
            };
            function elementDrag(e) {
                e.preventDefault();
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                modal.style.top = (modal.offsetTop - pos2) + 'px';
                modal.style.left = (modal.offsetLeft - pos1) + 'px';
                modal.style.marginLeft = '0';
            }
            function closeDrag() {
                document.onmouseup = null;
                document.onmousemove = null;
                modal.querySelector('iframe').style.pointerEvents = 'auto';
            }
        },
        injectStyles: function () {
            if (document.getElementById('qk-modal-styles')) return;
            const style = document.createElement('style');
            style.id = 'qk-modal-styles';
            style.textContent = `.qk-modal{position:fixed;background:#fff;box-shadow:0 10px 24px rgba(0,0,0,0.18);border-radius:12px;overflow:hidden;display:flex;flex-direction:column;transition:z-index .2s;transform:translate(-50%,-50%)}.qk-modal-drag-handle{position:absolute;top:0;left:0;right:40px;height:50px;z-index:100;cursor:move}.qk-modal-close-overlay{position:absolute;top:15px;right:15px;width:28px;height:28px;background:#dbdbdb;border:none;border-radius:50%;color:transparent;font-size:0;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:101;transition:all .2s}.qk-modal-close-overlay::before,.qk-modal-close-overlay::after{content:'';position:absolute;top:50%;left:50%;width:12px;height:2px;background:#fff;transform:translate(-50%,-50%) rotate(45deg);transition:all .2s}.qk-modal-close-overlay::after{transform:translate(-50%,-50%) rotate(-45deg)}.qk-modal-close-overlay:hover{background:#ff5252;transform:rotate(90deg)}.qk-modal-close-overlay:hover::before,.qk-modal-close-overlay:hover::after{width:14px}.qk-modal-body{flex:1;position:relative;min-height:450px}.qk-modal-loading{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;color:#64748b;width:100%;z-index:1;display:flex;flex-direction:column;align-items:center;justify-content:center}.qk-spinner{width:35px;height:35px;border:3px solid #f1f5f9;border-top:3px solid #428b6a;border-radius:50%;margin-bottom:12px;animation:qk-spin 1s linear infinite}@keyframes qk-spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}`;
            document.head.appendChild(style);
        },

        preloadStyles: function () {
            if (!this.stylesPreloaded) {
                this.injectStyles();
                this.stylesPreloaded = true;
            }
        }
    };
    window.QKModal = QKModal;

    document.addEventListener('DOMContentLoaded', function () {
        window.QKModal.preloadStyles();
    });
})();

function handleLogout() {
    if (window.LoginSync?.triggerLogout) {
        window.LoginSync.triggerLogout();
    } else {
        localStorage.setItem('qkcms_logout_sync', JSON.stringify({ action: 'logout', time: Date.now() }));
    }
    fetch('/login.php?action=logout', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' }
    }).catch(() => { }).finally(() => {
        try {
            document.dispatchEvent(new CustomEvent('qkcms:auth-changed', {
                detail: { loggedIn: false, source: 'logout-complete' }
            }));
        } catch (e) { }
    });
}

document.addEventListener('DOMContentLoaded', function () {
    if (!window.QKModal) return;

    const redirectUrl = window.location.href;
    const modalConfig = { width: '420px', height: '450px' };

    document.querySelectorAll('a[href*="admin/login.php"]').forEach(link => {
        if (link.getAttribute('data-qk-login-bound') === '1') return;
        link.setAttribute('data-qk-login-bound', '1');
        if (link.href.includes('action=logout')) return;

        link.addEventListener('click', function (e) {
            e.preventDefault();
            const isLoggedIn = localStorage.getItem('qkcms_logged_in') === 'true';
            if (isLoggedIn) {
                if (window.LoginSync && typeof window.LoginSync.showToast === 'function') {
                    window.LoginSync.showToast('您已登录，无需重复登录');
                } else {
                    alert('您已登录，无需重复登录');
                }
                return;
            }
            const isRegister = link.href.includes('register=1');
            const url = `/admin/login.php${isRegister ? '?register=1&' : '?'}redirect=${encodeURIComponent(redirectUrl)}`;
            window.QKModal.show('login', url, { ...modalConfig, title: isRegister ? '用户注册' : '用户登录' });
        });
    });
});

(function () {
    window.LoginSync = {
        storageKey: 'qkcms_logout_sync',
        loginStorageKey: 'qkcms_login_sync',
        isLoggedIn: false,
        hasProcessedLogout: false,
        hasProcessedLogin: false,
        currentUserId: 0,
        currentUserName: '',
        currentUserAvatar: '/assets/images/avatar.png',
        currentUserEmail: '未绑定',
        currentUserPoints: 0,
        currentUserCreatedAt: '',
        defaultAvatar: '/assets/images/avatar.png',
        logoutTimer: null,
        loginTimer: null,
        cacheStateTimer: null,

        startPolling: function () {
            var self = this;
            if (!this.isLoggedIn) {
                this.stopPolling();
                return;
            }
            if (!this.logoutTimer) {
                this.logoutTimer = setInterval(function () {
                    self.checkLogout();
                }, 3000);
            }
            if (!this.loginTimer) {
                this.loginTimer = setInterval(function () {
                    self.checkLogout();
                    if (!self.hasProcessedLogin) {
                        self.checkLogin();
                    }
                }, 2000);
            }
            if (!this.cacheStateTimer) {
                var lastLocalStorageState = localStorage.getItem('qkcms_logged_in');
                var lastSessionCookieState = document.cookie.includes('PHPSESSID=');
                this.cacheStateTimer = setInterval(function () {
                    var currentLocalStorageState = localStorage.getItem('qkcms_logged_in');
                    var currentSessionCookieState = document.cookie.includes('PHPSESSID=');

                    if (lastLocalStorageState !== currentLocalStorageState) {
                        lastLocalStorageState = currentLocalStorageState;
                        self.checkLogout();
                        var currentTime = Date.now();
                        var lastCacheTime = localStorage.getItem('qkcms_last_cache_time') || 0;
                        if (currentTime - lastCacheTime > 1000) {
                            localStorage.setItem('qkcms_cache_cleared', currentTime.toString());
                            localStorage.setItem('qkcms_last_cache_time', currentTime.toString());
                        }
                    }

                    if (lastSessionCookieState !== currentSessionCookieState) {
                        lastSessionCookieState = currentSessionCookieState;
                        self.checkLogout();
                        var currentTime = Date.now();
                        var lastCacheTime = localStorage.getItem('qkcms_last_cache_time') || 0;
                        if (currentTime - lastCacheTime > 1000) {
                            localStorage.setItem('qkcms_cache_cleared', currentTime.toString());
                            localStorage.setItem('qkcms_last_cache_time', currentTime.toString());
                        }
                    }
                }, 1000);
            }
        },

        stopPolling: function () {
            if (this.logoutTimer) {
                clearInterval(this.logoutTimer);
                this.logoutTimer = null;
            }
            if (this.loginTimer) {
                clearInterval(this.loginTimer);
                this.loginTimer = null;
            }
            if (this.cacheStateTimer) {
                clearInterval(this.cacheStateTimer);
                this.cacheStateTimer = null;
            }
        },

        init: function () {
            var self = this;
            this.isLoggedIn = localStorage.getItem('qkcms_logged_in') === 'true';
            this.currentUserId = localStorage.getItem('qkcms_user_id') || 0;
            this.currentUserName = localStorage.getItem('qkcms_user_nickname') || '';
            this.currentUserAvatar = localStorage.getItem('qkcms_user_avatar') || this.defaultAvatar;
            this.currentUserEmail = localStorage.getItem('qkcms_user_email') || '未绑定';
            this.hasProcessedLogout = localStorage.getItem('qkcms_has_processed_logout') === 'true';
            this.hasProcessedLogin = false;

            // 如果检测到退出标记，强制设置为退出状态
            if (localStorage.getItem('qkcms_user_logged_out') === 'true') {
                this.hasProcessedLogout = true;
                localStorage.setItem('qkcms_has_processed_logout', 'true');
            }

            var hasSessionCookie = document.cookie.includes('PHPSESSID=');
            var hasLocalStorageData = localStorage.getItem('qkcms_logged_in') === 'true';
            if ((window.QK_SHARED_HOME_CACHE === true || window.QK_SHARED_PAGE_CACHE === true) && hasSessionCookie && !hasLocalStorageData && !this.hasProcessedLogout) {
                this.checkServerLoginStatus();
            }

            if (this.isLoggedIn) {
                this.hasProcessedLogout = false;
                var storedUserInfo = {
                    id: localStorage.getItem('qkcms_user_id'),
                    username: localStorage.getItem('qkcms_user_nickname'),
                    avatar: localStorage.getItem('qkcms_user_avatar'),
                    email: localStorage.getItem('qkcms_user_email') || '未绑定',
                    status: '正常',
                    points: 0,
                    level: localStorage.getItem('qkcms_user_level') || '普通会员'
                };

                var lastSync = localStorage.getItem(this.loginStorageKey);
                if (lastSync) {
                    try {
                        var syncData = JSON.parse(lastSync);
                        if (syncData.action === 'login' && syncData.userInfo) {
                            storedUserInfo = syncData.userInfo;
                        }
                    } catch (e) { }
                }

                // 同步基础字段到内存，避免页面取不到积分与注册时间
                this.isLoggedIn = true;
                this.currentUserId = parseInt(storedUserInfo.id || '0');
                this.currentUserName = storedUserInfo.username || '';
                this.currentUserAvatar = storedUserInfo.avatar || this.defaultAvatar;
                this.currentUserEmail = storedUserInfo.email || '未绑定';
                this.currentUserPoints = storedUserInfo.points || 0;
                this.currentUserCreatedAt = storedUserInfo.created_at || '';

                // 优先更新充值页的账号信息展示（无跳转）
                try {
                    var pointsEl = document.getElementById('userPoints');
                    var createdAtEl = document.getElementById('userCreatedAt');
                    if (pointsEl) pointsEl.textContent = this.currentUserPoints || 0;
                    if (createdAtEl) {
                        var v = this.currentUserCreatedAt || '';
                        if (typeof v === 'string') {
                            var m = v.match(/^(\d{4}-\d{2}-\d{2})/);
                            createdAtEl.textContent = m ? m[1] : v;
                        } else {
                            createdAtEl.textContent = v ? new Date(v).toISOString().slice(0, 10) : '';
                        }
                    }
                } catch (e) { }

                var avatarUrl = storedUserInfo.avatar || localStorage.getItem('qkcms_user_avatar') || this.defaultAvatar;
                var currentAvatarCache = sessionStorage.getItem('qkcms_current_avatar');

                var navAvatarImg = document.getElementById('nav-avatar-img');
                var dropdownAvatarImg = document.getElementById('dropdown-avatar-img');
                var memberAvatar = document.querySelector('.member-avatar');

                if ((currentAvatarCache !== avatarUrl) ||
                    (navAvatarImg && navAvatarImg.getAttribute('src') !== avatarUrl) ||
                    (dropdownAvatarImg && dropdownAvatarImg.getAttribute('src') !== avatarUrl) ||
                    (memberAvatar && memberAvatar.getAttribute('src') !== avatarUrl)) {
                    this.updateUIAfterLogin(storedUserInfo);
                } else {
                    var initUserLevel = storedUserInfo.level || storedUserInfo.level_name || localStorage.getItem('qkcms_user_level') || '';
                    if (storedUserInfo && storedUserInfo.is_admin === true) {
                        initUserLevel = '管理员';
                    }
                    if (!initUserLevel || initUserLevel === '游客' || initUserLevel === '未登录') {
                        initUserLevel = '普通会员';
                    }
                    localStorage.setItem('qkcms_user_level', initUserLevel);

                    var homeUserLevel = document.getElementById('home-user-level');
                    var homeUserWelcome = document.getElementById('home-user-welcome');
                    if (homeUserLevel) {
                        homeUserLevel.textContent = initUserLevel;
                        homeUserLevel.setAttribute('data-synced', 'true');
                    }
                    if (homeUserWelcome) {
                        homeUserWelcome.textContent = '欢迎你，' + (storedUserInfo.username || '用户');
                        homeUserWelcome.setAttribute('data-synced', 'true');
                    }

                    // 即使头像没有变化，也要更新盖章按钮状态
                    try {
                        var stampBtns = document.querySelectorAll('[data-login-action="stamp"]');
                        stampBtns.forEach(function (btn) {
                            if (storedUserInfo.level === '管理员') {
                                btn.style.display = 'inline-block';
                            } else {
                                btn.style.display = 'none';
                            }
                        });
                    } catch (e) { }
                }
            } else {
                // 用户未登录，隐藏盖章按钮
                try {
                    var stampBtns = document.querySelectorAll('[data-login-action="stamp"]');
                    stampBtns.forEach(function (btn) { btn.style.display = 'none'; });
                } catch (e) { }
            }

            window.addEventListener('storage', function (e) {
                if (e.key === self.storageKey) {
                    var data = e.newValue ? JSON.parse(e.newValue) : {};
                    if (data.action === 'logout' && self.isLoggedIn) {
                        self.hasProcessedLogout = true;
                        localStorage.setItem('qkcms_has_processed_logout', 'true');
                        self.updateUIAfterLogout();
                    }
                }
                if (e.key === self.loginStorageKey) {
                    var data = e.newValue ? JSON.parse(e.newValue) : {};
                    if (data.action === 'login' && data.userInfo) {
                        self.hasProcessedLogin = true;
                        self.updateUIAfterLogin(data.userInfo);
                    }
                }
            });

            document.addEventListener('visibilitychange', function () {
                if (!document.hidden) {
                    self.checkLogout();
                    if (!self.hasProcessedLogin) {
                        self.checkLogin();
                    }
                }
            });

            window.addEventListener('pageshow', function () {
                self.checkLogout();
                if (!self.hasProcessedLogin) {
                    self.checkLogin();
                }
            });

            self.checkLogout();
            self.checkLogin();
            self.startPolling();

            // 添加页面交互事件监听，确保清除缓存时能及时响应（减少监听器数量）
            var checkTimeout;
            function debouncedCheckLogout() {
                clearTimeout(checkTimeout);
                checkTimeout = setTimeout(function () {
                    self.checkLogout();
                }, 100); // 防抖处理，减少频繁触发
            }

            document.addEventListener('click', debouncedCheckLogout);

            // 监听其他窗口的清除缓存事件
            window.addEventListener('storage', function (e) {
                if (e.key === 'qkcms_cache_cleared' && e.newValue) {
                    // 其他窗口清除了缓存，立即检查退出状态
                    self.checkLogout();
                }
            });
        },

        checkLogout: function () {
            var hasSessionCookie = document.cookie.includes('PHPSESSID=');
            var hasLocalStorageData = localStorage.getItem('qkcms_logged_in') === 'true';
            var hasLoggedClass = document.documentElement.classList.contains('qk-prelogged') || document.body.classList.contains('logged-in');

            if (!hasLocalStorageData && hasLoggedClass) {
                this.hasProcessedLogout = true;
                localStorage.setItem('qkcms_has_processed_logout', 'true');
                this.updateUIAfterLogout();
                return;
            }

            var data = localStorage.getItem(this.storageKey);
            if (data && this.isLoggedIn) {
                try {
                    var obj = JSON.parse(data);
                    if (obj.action === 'logout' && (Date.now() - obj.time) < 10000) { // 延长到10秒
                        this.hasProcessedLogout = true;
                        localStorage.setItem('qkcms_has_processed_logout', 'true');
                        this.updateUIAfterLogout();
                        return;
                    }
                } catch (e) { }
            }

            // 检查清除浏览器缓存的情况
            if (this.isLoggedIn) {
                // 如果session cookie不存在，但localStorage显示已登录，说明缓存被清除
                if (!hasSessionCookie && hasLocalStorageData) {
                    this.hasProcessedLogout = true;
                    localStorage.setItem('qkcms_has_processed_logout', 'true');
                    this.updateUIAfterLogout();
                    return;
                }

                // 如果session cookie存在，但localStorage显示未登录，也触发退出
                if (hasSessionCookie && !hasLocalStorageData) {
                    this.hasProcessedLogout = true;
                    localStorage.setItem('qkcms_has_processed_logout', 'true');
                    this.updateUIAfterLogout();
                    return;
                }

                // 如果两者都不存在，直接触发退出
                if (!hasSessionCookie && !hasLocalStorageData) {
                    this.hasProcessedLogout = true;
                    localStorage.setItem('qkcms_has_processed_logout', 'true');
                    this.updateUIAfterLogout();
                    return;
                }
            }
        },

        checkLogin: function () {
            // 如果已经处理过退出，不再检查登录状态
            if (this.hasProcessedLogout) {
                return;
            }

            // 检查清除浏览器缓存的情况
            var hasSessionCookie = document.cookie.includes('PHPSESSID=');
            var hasLocalStorageData = localStorage.getItem('qkcms_logged_in') === 'true';

            // localStorage不存在时，不使用session自动回写登录态，避免清缓存后头像又恢复
            if (hasSessionCookie && !hasLocalStorageData) {
                return;
            }

            // localStorage显示已登录但session丢失：交给退出同步流程处理
            if (!hasSessionCookie && hasLocalStorageData) {
                return;
            }

            // 如果两者都不存在，说明缓存被清除，不检查登录
            if (!hasSessionCookie && !hasLocalStorageData) {
                return;
            }

            var data = localStorage.getItem(this.loginStorageKey);
            if (data) {
                try {
                    var obj = JSON.parse(data);
                    if (obj.action === 'login' && (Date.now() - obj.time) < 10000 && obj.userInfo) { // 延长到10秒
                        if (obj.userInfo.id != this.currentUserId) {
                            this.hasProcessedLogin = true;
                            this.updateUIAfterLogin(obj.userInfo);
                        } else if (!this.isLoggedIn) {
                            this.hasProcessedLogin = true;
                            this.updateUIAfterLogin(obj.userInfo);
                        } else {
                            var avatarUrl = obj.userInfo.avatar || localStorage.getItem('qkcms_user_avatar') || this.defaultAvatar;
                            var navAvatarImg = document.getElementById('nav-avatar-img');
                            var dropdownAvatarImg = document.getElementById('dropdown-avatar-img');
                            var memberAvatar = document.querySelector('.member-avatar');

                            if ((navAvatarImg && navAvatarImg.getAttribute('src') !== avatarUrl) ||
                                (dropdownAvatarImg && dropdownAvatarImg.getAttribute('src') !== avatarUrl) ||
                                (memberAvatar && memberAvatar.getAttribute('src') !== avatarUrl)) {
                                this.hasProcessedLogin = true;
                                this.updateUIAfterLogin(obj.userInfo);
                            }
                        }
                    }
                } catch (e) { }
            }

            if (!this.isLoggedIn && !this.hasProcessedLogout) {
                return;
            }
        },

        checkServerLoginStatus: function () {
            var self = this;
            fetch('/login.php?action=check_login', {
                method: 'GET',
                credentials: 'include',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            }).then(function (response) {
                return response.json();
            }).then(function (data) {
                if (data.logged_in && data.user_info) {
                    self.hasProcessedLogin = true;
                    self.updateUIAfterLogin(data.user_info);
                }
            }).catch(function () {
            });
        },

        triggerLogout: function () {
            localStorage.setItem(this.storageKey, JSON.stringify({
                action: 'logout',
                time: Date.now()
            }));
            this.updateUIAfterLogout();
        },

        triggerLogin: function (userInfo) {
            localStorage.setItem(this.loginStorageKey, JSON.stringify({
                action: 'login',
                time: Date.now(),
                userInfo: userInfo
            }));
            this.updateUIAfterLogin(userInfo);
        },

        updateUIAfterLogout: function () {
            var userDropdownMenu = document.getElementById('userDropdownMenu');
            if (userDropdownMenu) {
                userDropdownMenu.classList.remove('show');
            }

            this.stopPolling();

            // 设置明确的退出标记，防止自动重新登录
            this.hasProcessedLogout = true;
            localStorage.setItem('qkcms_has_processed_logout', 'true');
            localStorage.setItem('qkcms_user_logged_out', 'true');

            var LOGIN_KEYS = ['qkcms_logged_in', 'qkcms_user_nickname', 'qkcms_user_id', 'qkcms_user_avatar', 'qkcms_user_email', 'qkcms_user_token'];
            LOGIN_KEYS.forEach(key => localStorage.removeItem(key));
            sessionStorage.removeItem('qkcms_logged_in');
            document.documentElement.classList.remove('qk-prelogged');
            document.body.classList.remove('logged-in');

            var loginRegisterButtons = document.querySelector('.login-register-buttons');
            var navUserAvatar = document.getElementById('userAvatar');
            if (loginRegisterButtons) {
                loginRegisterButtons.classList.remove('hidden');
                loginRegisterButtons.style.display = 'flex';
            }
            if (navUserAvatar) {
                navUserAvatar.classList.remove('has-user');
                navUserAvatar.style.display = 'none';
                navUserAvatar.style.visibility = 'hidden';
                navUserAvatar.style.opacity = '0';
            }

            this.isLoggedIn = false;
            this.currentUserId = 0;
            this.currentUserName = '';
            this.currentUserAvatar = '';
            this.currentUserEmail = '未绑定';

            var userAvatarImgs = document.querySelectorAll('.user-avatar');

            userAvatarImgs.forEach(function (img) {
                img.src = this.defaultAvatar;
                img.setAttribute('src', this.defaultAvatar);
            }.bind(this));

            // 更新评论框左下角头像和用户名
            var commentBoxAvatar = document.getElementById('pinlun-comment-box-avatar') || document.getElementById('comment-box-avatar');
            var commentBoxUsername = document.getElementById('pinlun-comment-box-username') || document.getElementById('comment-box-username');

            if (commentBoxAvatar) {
                commentBoxAvatar.src = this.defaultAvatar;
                commentBoxAvatar.setAttribute('src', this.defaultAvatar);
            }
            if (commentBoxUsername) {
                commentBoxUsername.textContent = '未登录';
            }

            var homeUserLevel = document.getElementById('home-user-level');
            var homeUserWelcome = document.getElementById('home-user-welcome');

            if (homeUserLevel) {
                homeUserLevel.textContent = '未登录';
                homeUserLevel.setAttribute('data-synced', 'true');
            }
            if (homeUserWelcome) {
                homeUserWelcome.textContent = '欢迎你，请先登录';
                homeUserWelcome.setAttribute('data-synced', 'true');
            }

            var userNameElements = document.querySelectorAll('.user-dropdown-menu .user-name, .comment-user-name, .user-profile-name, .member-details h1');
            var userRoleElements = document.querySelectorAll('.user-role');

            userNameElements.forEach(function (el) {
                el.textContent = '未登录';
                el.setAttribute('data-synced', 'true');
            });

            userRoleElements.forEach(function (el) {
                el.textContent = '欢迎你，请先登录';
                el.setAttribute('data-synced', 'true');
            });

            var menuUserId = document.getElementById('menu-user-id');
            var menuUserEmail = document.getElementById('menu-user-email');
            var menuUserPoints = document.getElementById('menu-user-points');
            var menuUserStatus = document.getElementById('menu-user-status');
            var menuUserCreatedAt = document.getElementById('menu-user-created-at');

            if (menuUserId) menuUserId.textContent = '[user_id]';
            if (menuUserEmail) menuUserEmail.textContent = '未绑定';
            if (menuUserPoints) menuUserPoints.textContent = '[user_points]';
            if (menuUserStatus) menuUserStatus.textContent = '未登录';
            if (menuUserCreatedAt) menuUserCreatedAt.textContent = '未登录';

            var userCenterLinks = document.querySelectorAll('.user-center-btn');
            userCenterLinks.forEach(function (link) {
                link.setAttribute('href', '/admin/login.php');
            });

            var userLevelBadges = document.querySelectorAll('.user-level-badge');
            userLevelBadges.forEach(function (badgeDiv) {
                var badgeSpan = badgeDiv.querySelector('span');
                if (badgeSpan) {
                    badgeSpan.textContent = '未登录';
                }
                badgeDiv.classList.remove('管理员', 'VIP会员');
                badgeDiv.classList.add('游客');
            });

            if (window.updateNavbarLoginStatus) window.updateNavbarLoginStatus(false);
            if (window.updateSidebarButtons) window.updateSidebarButtons(false);
            if (window.forceUpdateUI) window.forceUpdateUI();

            var accountInfo = document.getElementById('accountInfo');
            if (accountInfo) {
                accountInfo.style.display = 'none';
                var loginPrompt = document.getElementById('loginPrompt');
                if (loginPrompt) loginPrompt.style.display = 'flex';
            }

            sessionStorage.removeItem('qkcms_current_avatar');

            // 清除地址字段，防止下一个登录用户看到上一个用户的地址
            var userDefaultAddress = document.getElementById('userDefaultAddress');
            if (userDefaultAddress) {
                userDefaultAddress.value = '';
            }

            // 立即清理退出同步状态，防止自动重新登录
            localStorage.removeItem('qkcms_logout_sync');
            this.hasProcessedLogin = false;

            // 同步购物车状态 - 退出后清空购物车显示
            if (window.updateCartCount) {
                window.updateCartCount(0);
            }
            if (window.clearCartItems) {
                window.clearCartItems();
            }

            // 退出后显示评论框（未登录状态可以评论）
            this.updateCommentFormVisibility(false);

            // 隐藏盖章按钮
            try {
                var stampBtns = document.querySelectorAll('[data-login-action="stamp"]');
                stampBtns.forEach(function (btn) { btn.style.display = 'none'; });
            } catch (e) { }

            // 隐藏订单选项卡
            try {
                var orderTab = document.querySelector('button[data-tab="hot"]');
                if (orderTab) {
                    orderTab.style.display = 'none';
                }
            } catch (e) { }

            // 更新window.isLoggedIn状态
            if (typeof window.isLoggedIn !== 'undefined') {
                window.isLoggedIn = false;
            }

            // 更新isLoggedInNow状态（goods.php）
            if (typeof window.isLoggedInNow === 'function') {
                window.isLoggedInNow();
            }

            try {
                document.dispatchEvent(new CustomEvent('qkcms:auth-changed', {
                    detail: { loggedIn: false }
                }));
            } catch (e) { }
        },

        // 更新评论框显示状态
        updateCommentFormVisibility: function (isLoggedIn) {
            // 只在商品详情页执行
            if (!document.querySelector('.product-detail') && !document.getElementById('tab-comments')) {
                return;
            }

            var commentForm = document.querySelector('.pinlun-comment-form-container');
            var purchaseNotice = document.querySelector('.purchase-required-notice');

            if (!isLoggedIn) {
                // 未登录：显示评论框，隐藏购买提示
                if (commentForm) commentForm.style.display = 'block';
                if (purchaseNotice) purchaseNotice.style.display = 'none';
            } else {
                // 已登录：需要检查购买状态
                this.checkPurchaseStatusAndUpdateUI();
            }
        },

        // 检查购买状态并更新UI
        checkPurchaseStatusAndUpdateUI: function () {
            var goodsId = this.getCurrentGoodsId();
            if (!goodsId) return;

            var self = this;
            // 调用 goods.php 检查购买状态
            fetch('/templates/goods.php?action=check_purchase&id=' + goodsId, {
                method: 'GET',
                credentials: 'same-origin',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
                .then(function (response) { return response.json(); })
                .then(function (data) {
                    var commentForm = document.querySelector('.pinlun-comment-form-container');
                    var purchaseNotice = document.querySelector('.purchase-required-notice');

                    if (data.is_admin || data.has_purchased) {
                        // 已购买或管理员：显示评论框
                        if (commentForm) commentForm.style.display = 'block';
                        if (purchaseNotice) purchaseNotice.style.display = 'none';
                    } else {
                        // 未购买且不是管理员：隐藏评论框，显示提示
                        if (commentForm) commentForm.style.display = 'none';
                        if (purchaseNotice) purchaseNotice.style.display = 'block';
                    }
                })
                .catch(function (error) {
                    console.error('检查购买状态失败:', error);
                });
        },

        // 获取当前商品ID
        getCurrentGoodsId: function () {
            // 从URL中获取商品ID
            var urlMatch = window.location.pathname.match(/goods_id(\d+)\.html/);
            if (urlMatch) return urlMatch[1];

            // 从URL参数获取
            var urlParams = new URLSearchParams(window.location.search);
            var id = urlParams.get('id');
            if (id) return id;

            // 从页面元素获取
            var goodsIdEl = document.getElementById('currentGoodsId');
            if (goodsIdEl) return goodsIdEl.value;

            return null;
        },

        updateUIAfterLogin: function (userInfo) {
            var userDropdownMenu = document.getElementById('userDropdownMenu');
            if (userDropdownMenu) {
                userDropdownMenu.classList.remove('show');
            }

            function formatDateOnly(value) {
                if (!value) return '';
                if (typeof value === 'string') {
                    var m = value.match(/^(\d{4}-\d{2}-\d{2})/);
                    if (m) return m[1];
                }
                var d = new Date(value);
                if (!isNaN(d.getTime())) {
                    var y = d.getFullYear();
                    var mm = String(d.getMonth() + 1).padStart(2, '0');
                    var dd = String(d.getDate()).padStart(2, '0');
                    return y + '-' + mm + '-' + dd;
                }
                return String(value);
            }

            // 清除退出标记，确保登录流程正常
            localStorage.removeItem('qkcms_user_logged_out');
            localStorage.removeItem('qkcms_has_processed_logout');
            this.hasProcessedLogout = false;

            localStorage.setItem('qkcms_logged_in', 'true');
            localStorage.setItem('qkcms_user_nickname', userInfo.username || '');
            localStorage.setItem('qkcms_user_id', userInfo.id || '');
            localStorage.setItem('qkcms_user_avatar', userInfo.avatar || '');
            localStorage.setItem('qkcms_user_email', userInfo.email || '未绑定');
            sessionStorage.setItem('qkcms_logged_in', 'true');
            document.documentElement.classList.add('qk-prelogged');
            document.body.classList.add('logged-in');

            var loginRegisterButtons = document.querySelector('.login-register-buttons');
            var navUserAvatar = document.getElementById('userAvatar');
            if (loginRegisterButtons) {
                loginRegisterButtons.classList.add('hidden');
                loginRegisterButtons.style.display = 'none';
            }
            if (navUserAvatar) {
                navUserAvatar.classList.add('has-user');
                navUserAvatar.style.display = 'flex';
                navUserAvatar.style.visibility = 'visible';
                navUserAvatar.style.opacity = '1';
            }

            var avatarUrl = userInfo.avatar || localStorage.getItem('qkcms_user_avatar') || this.defaultAvatar;
            var navAvatarImg = document.getElementById('nav-avatar-img');
            var dropdownAvatarImg = document.getElementById('dropdown-avatar-img');
            var userAvatarImgs = document.querySelectorAll('.user-avatar');

            if (navAvatarImg) {
                navAvatarImg.src = avatarUrl;
                navAvatarImg.setAttribute('src', avatarUrl);
            }
            if (dropdownAvatarImg) dropdownAvatarImg.src = avatarUrl;

            userAvatarImgs.forEach(function (img) {
                img.src = avatarUrl;
                img.setAttribute('src', avatarUrl);
            });

            // 更新评论框左下角头像和用户名
            var commentBoxAvatar = document.getElementById('pinlun-comment-box-avatar') || document.getElementById('comment-box-avatar');
            var commentBoxUsername = document.getElementById('pinlun-comment-box-username') || document.getElementById('comment-box-username');

            if (commentBoxAvatar) {
                commentBoxAvatar.src = avatarUrl;
                commentBoxAvatar.setAttribute('src', avatarUrl);
            }
            if (commentBoxUsername) {
                commentBoxUsername.textContent = userInfo.username || '用户';
            }

            sessionStorage.setItem('qkcms_current_avatar', avatarUrl);

            if (userInfo.id && userInfo.id == 1 && /^\/admin(\/|$)/.test(window.location.pathname)) {
                setTimeout(function () {
                    window.location.href = '/admin/admin.php';
                }, 500);
                return;
            }

            var userLevel = userInfo.level || userInfo.level_name || localStorage.getItem('qkcms_user_level') || '';
            if (userInfo && userInfo.is_admin === true) {
                userLevel = '管理员';
            }
            if (!userLevel || userLevel === '未登录' || userLevel === '游客') {
                userLevel = '普通会员';
            }
            localStorage.setItem('qkcms_user_level', userLevel);

            var userCenterLinks = document.querySelectorAll('.user-center-btn');
            userCenterLinks.forEach(function (link) {
                if (userInfo.id) {
                    link.setAttribute('href', '/Member_id' + String(userInfo.id) + '.html');
                }
            });

            var homeUserLevel = document.getElementById('home-user-level');
            var homeUserWelcome = document.getElementById('home-user-welcome');

            if (homeUserLevel && homeUserLevel.textContent !== userLevel) {
                homeUserLevel.textContent = userLevel;
                homeUserLevel.setAttribute('data-synced', 'true');
            }
            if (homeUserWelcome) {
                var welcomeText = '欢迎你，' + (userInfo.username || '用户');
                if (homeUserWelcome.textContent !== welcomeText) {
                    homeUserWelcome.textContent = welcomeText;
                    homeUserWelcome.setAttribute('data-synced', 'true');
                }
            }

            var userLevelBadges = document.querySelectorAll('.user-level-badge');
            userLevelBadges.forEach(function (badgeDiv) {
                var badgeSpan = badgeDiv.querySelector('span');
                if (badgeSpan) {
                    badgeSpan.textContent = userLevel;
                }
                badgeDiv.classList.remove('管理员', 'VIP会员', '游客');
                if (userLevel === '管理员' || userLevel === 'VIP会员' || userLevel === '游客') {
                    badgeDiv.classList.add(userLevel);
                } else {
                    badgeDiv.classList.add('游客');
                }
            });

            var userNameElements = document.querySelectorAll('.user-dropdown-menu .user-name, .comment-user-name, .user-profile-name, .member-details h1');
            var userRoleElements = document.querySelectorAll('.user-role');

            userNameElements.forEach(function (el) {
                var displayName = (userInfo.username || '用户') + '（id' + (userInfo.id || '') + '）';
                if (el.textContent !== displayName) {
                    el.textContent = displayName;
                    el.setAttribute('data-synced', 'true');
                }
            });

            userRoleElements.forEach(function (el) {
                var newText = '欢迎你，' + (userInfo.username || '用户');
                if (el.textContent !== newText) {
                    el.textContent = newText;
                    el.setAttribute('data-synced', 'true');
                }
            });

            var menuUserId = document.getElementById('menu-user-id');
            var menuUserEmail = document.getElementById('menu-user-email');
            var menuUserPoints = document.getElementById('menu-user-points');
            var menuUserStatus = document.getElementById('menu-user-status');
            var menuUserCreatedAt = document.getElementById('menu-user-created-at');

            if (menuUserId && menuUserId.textContent !== (userInfo.id || '')) {
                menuUserId.textContent = userInfo.id || '';
            }
            var userEmailText = userInfo.email || '未绑定';
            if (menuUserEmail && menuUserEmail.textContent !== userEmailText) {
                menuUserEmail.textContent = userEmailText;
            }
            if (menuUserPoints && menuUserPoints.textContent !== (userInfo.points || 0).toString()) {
                menuUserPoints.textContent = userInfo.points || 0;
            }
            if (menuUserStatus) {
                if (menuUserStatus.textContent !== (userInfo.status || '正常')) {
                    menuUserStatus.textContent = userInfo.status || '正常';
                }
                if ((userInfo.status || '').indexOf('被封禁') !== -1) {
                    if (!menuUserStatus.classList.contains('status-banned')) {
                        menuUserStatus.classList.add('status-banned');
                    }
                } else {
                    if (menuUserStatus.classList.contains('status-banned')) {
                        menuUserStatus.classList.remove('status-banned');
                    }
                }
            }
            var createdAtText = formatDateOnly(userInfo.created_at || '');
            if (menuUserCreatedAt && menuUserCreatedAt.textContent !== createdAtText) {
                menuUserCreatedAt.textContent = createdAtText;
            }

            var memberLevel = document.querySelector('.member-level');
            var memberPoints = document.querySelector('.member-points');
            if (memberLevel) {
                var newLevelText = 'Lv.' + userLevel;
                if (memberLevel.textContent !== newLevelText) {
                    memberLevel.textContent = newLevelText;
                }
            }

            // 显示盖章按钮（仅管理员）
            try {
                var stampBtns = document.querySelectorAll('[data-login-action="stamp"]');
                stampBtns.forEach(function (btn) {
                    if (userLevel === '管理员') {
                        btn.style.display = 'inline-block';
                    } else {
                        btn.style.display = 'none';
                    }
                });
            } catch (e) { }

            // 显示订单选项卡
            try {
                var orderTab = document.querySelector('button[data-tab="hot"]');
                if (orderTab) {
                    orderTab.style.display = 'inline-block';
                }
            } catch (e) { }
            if (memberPoints) {
                var newPointsText = '积分: ' + (userInfo.points || 0);
                if (memberPoints.textContent !== newPointsText) {
                    memberPoints.textContent = newPointsText;
                }
            }

            this.isLoggedIn = true;
            this.currentUserId = parseInt(userInfo.id || '0');
            this.currentUserName = userInfo.username || '';
            this.currentUserAvatar = userInfo.avatar || '';
            this.currentUserEmail = userInfo.email || '未绑定';
            this.currentUserPoints = userInfo.points || 0;
            this.currentUserCreatedAt = userInfo.created_at || '';
            this.startPolling();

            if (window.updateNavbarLoginStatus) window.updateNavbarLoginStatus(true);
            if (window.updateSidebarButtons) window.updateSidebarButtons(true);
            if (window.forceUpdateUI) window.forceUpdateUI();

            var accountInfo = document.getElementById('accountInfo');
            if (accountInfo) {
                accountInfo.style.display = 'block';
                var loginPrompt = document.getElementById('loginPrompt');
                if (loginPrompt) loginPrompt.style.display = 'none';
            }

            // 同步购物车状态 - 登录后从服务器获取购物车数据
            if (window.syncCartAfterLogin) {
                window.syncCartAfterLogin();
            }

            // 登录后检查购买状态并更新评论框显示
            this.updateCommentFormVisibility(true);

            try {
                document.dispatchEvent(new CustomEvent('qkcms:auth-changed', {
                    detail: { loggedIn: true, userInfo: userInfo || null }
                }));
            } catch (e) { }
        }
    };

    window.LoginSync.init();

    (function () {
        function readPointsFromText(v) {
            var n = parseInt(String(v || '').replace(/[^\d-]/g, ''), 10);
            return isFinite(n) ? n : null;
        }

        function syncPointsFromDomOnce() {
            try {
                var n = null;
                var menuEl = document.getElementById('menu-user-points');
                if (menuEl) n = readPointsFromText(menuEl.textContent);
                if (n === null) {
                    var pEl = document.getElementById('userPoints');
                    if (pEl) n = readPointsFromText(pEl.textContent);
                }
                if (n === null) return;

                if (window.LoginSync) {
                    window.LoginSync.currentUserPoints = n;
                }

                var userPointsEl = document.getElementById('userPoints');
                if (userPointsEl) userPointsEl.textContent = String(n);
                var navPointsEl = document.getElementById('navUserPoints');
                if (navPointsEl) navPointsEl.textContent = String(n);
                var menuUserPoints = document.getElementById('menu-user-points');
                if (menuUserPoints) menuUserPoints.textContent = String(n);
                var memberPoints = document.querySelector('.member-points');
                if (memberPoints) memberPoints.textContent = '积分: ' + String(n);
            } catch (e) { }
        }

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function () {
                syncPointsFromDomOnce();
                setTimeout(syncPointsFromDomOnce, 800);
            });
        } else {
            syncPointsFromDomOnce();
            setTimeout(syncPointsFromDomOnce, 800);
        }
    })();

    document.addEventListener('userPointsUpdated', function (e) {
        try {
            var points = e && e.detail ? e.detail.points : null;
            var n = parseInt(points, 10);
            if (!isFinite(n)) return;

            if (window.LoginSync) {
                window.LoginSync.currentUserPoints = n;
            }

            var userPointsEl = document.getElementById('userPoints');
            if (userPointsEl) userPointsEl.textContent = String(n);

            var navPointsEl = document.getElementById('navUserPoints');
            if (navPointsEl) navPointsEl.textContent = String(n);

            var menuUserPoints = document.getElementById('menu-user-points');
            if (menuUserPoints) menuUserPoints.textContent = String(n);

            var memberPoints = document.querySelector('.member-points');
            if (memberPoints) memberPoints.textContent = '积分: ' + String(n);
        } catch (err) { }
    });

    // 监听登录成功消息，优化处理顺序
    window.addEventListener('message', function (event) {
        if (!event || !event.data || event.data.type !== 'close_modal') return;

        var modalId = '';
        if (typeof event.data.modal_id === 'string' && event.data.modal_id) {
            modalId = event.data.modal_id;
        } else {
            modalId = 'login';
        }

        if (window.QKModal && window.QKModal.activeModals && window.QKModal.activeModals[modalId]) {
            window.QKModal.close(modalId);
        }

        setTimeout(function () {
            if (window.LoginSync && window.LoginSync.checkLogin) {
                window.LoginSync.checkLogin();
            }
        }, 100);
    });

    (function () {
        var lastPromptAt = 0;

        function isLoggedInNow() {
            try {
                if (window.LoginSync) {
                    if (typeof window.LoginSync.checkLogout === 'function') window.LoginSync.checkLogout();
                    if (typeof window.LoginSync.checkLogin === 'function') window.LoginSync.checkLogin();
                    return !!window.LoginSync.isLoggedIn;
                }
            } catch (e) { }

            try {
                if (localStorage.getItem('qkcms_user_logged_out') === 'true') return false;
                return localStorage.getItem('qkcms_logged_in') === 'true';
            } catch (e) { }

            return false;
        }

        function isUserBannedNow() {
            try {
                if (typeof window.isUserBanned === 'boolean') return window.isUserBanned;
            } catch (e) { }
            try {
                if (window.pinlunjs && typeof window.pinlunjs.isUserBanned === 'boolean') return window.pinlunjs.isUserBanned;
            } catch (e) { }
            return false;
        }

        function openLogin(actionName) {
            var now = Date.now();
            if (now - lastPromptAt < 1200) return;
            lastPromptAt = now;

            var tip = '请先登录后再操作';
            if (actionName) tip = '请先登录后再' + actionName;
            function openModal() {
                var redirectUrl = window.location.href;
                if (window.QKModal && typeof window.QKModal.show === 'function') {
                    window.QKModal.show('login', '/admin/login.php?redirect=' + encodeURIComponent(redirectUrl), {
                        title: '用户登录',
                        width: '420px',
                        height: '450px'
                    });
                } else {
                    window.location.href = '/admin/login.php?redirect=' + encodeURIComponent(redirectUrl);
                }
            }

            if (typeof window.showToast === 'function') {
                window.showToast(tip, { type: 'error', duration: 1200, callback: openModal });
            } else {
                openModal();
            }
        }

        function openBanned() {
            var now = Date.now();
            if (now - lastPromptAt < 1200) return;
            lastPromptAt = now;
            if (typeof window.showBannedToast === 'function') {
                window.showBannedToast();
                return;
            }
            if (typeof window.showToast === 'function') {
                window.showToast('你的账号已封禁', { type: 'banned', duration: 1200 });
                return;
            }
            alert('你的账号已封禁');
        }

        function mapActionText(v) {
            if (!v) return '';
            if (v === 'like') return '点赞';
            if (v === 'report') return '举报';
            if (v === 'buy') return '购买';
            if (v === 'use_tool') return '使用';
            if (v === 'share') return '分享';
            if (v === 'comment') return '评论';
            if (v === 'reply') return '回复';
            if (v === 'dislike') return '点踩';
            if (v === 'add_to_cart') return '加入购物车';
            if (v === 'cart') return '查看购物车';
            if (v === 'checkout') return '结算';
            if (v === 'recharge') return '充值';
            if (v === 'publish') return '投稿';
            if (v === 'edit_publish') return '编辑';
            if (v === 'delete_publish') return '删除';
            if (v === 'preview_publish') return '预览';
            return '';
        }

        document.addEventListener('click', function (e) {
            try {
                var p = String(window.location.pathname || '');
                if (p.indexOf('/admin/login.php') !== -1 || p === '/login' || p.indexOf('/login') === 0) return;
            } catch (err) { }

            var el = null;
            try {
                el = e.target && e.target.closest ? e.target.closest('[data-require-login="1"]') : null;
            } catch (err) {
                el = null;
            }
            if (!el) return;

            if (isUserBannedNow()) {
                e.preventDefault();
                e.stopPropagation();
                if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
                openBanned();
                return;
            }

            if (isLoggedInNow()) return;

            e.preventDefault();
            e.stopPropagation();
            if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();

            var actionName = '';
            try {
                actionName = mapActionText(el.getAttribute('data-login-action') || '');
            } catch (err) { }
            openLogin(actionName);
        }, true);
    })();

    (function () {
        function execScripts(root) {
            if (!root) return;
            var scripts = root.querySelectorAll('script');
            for (var i = 0; i < scripts.length; i++) {
                var s = scripts[i];
                var ns = document.createElement('script');
                if (s.src) ns.src = s.src;
                else ns.text = s.text || s.textContent || '';
                document.head.appendChild(ns);
                try { s.parentNode.removeChild(s); } catch (e) { }
            }
        }

        function loadStampPlugin() {
            if (window.__qk_stamp_loaded) return Promise.resolve(true);
            if (window.__qk_stamp_loading) return window.__qk_stamp_loading;
            window.__qk_stamp_loading = fetch('/admin/Plugin/40_stamp.php?t=' + Date.now(), {
                method: 'GET',
                credentials: 'include'
            }).then(function (r) {
                if (!r.ok) throw new Error('加载盖章插件失败');
                return r.text();
            }).then(function (html) {
                if (!html) throw new Error('加载盖章插件失败');
                if (!window.__qk_stamp_container) {
                    var c = document.createElement('div');
                    c.style.display = 'none';
                    c.id = 'qkStampPluginContainer';
                    window.__qk_stamp_container = c;
                    document.body.appendChild(c);
                }
                window.__qk_stamp_container.innerHTML = html;
                execScripts(window.__qk_stamp_container);
                window.__qk_stamp_loaded = true;
                return true;
            }).catch(function (err) {
                window.__qk_stamp_loading = null;
                throw err;
            });
            return window.__qk_stamp_loading;
        }

        function ensureTplTag() {
            return fetch('/admin/Plugin/40_stamp.php?plugin=40_stamp&action=ensure_post_tpl_tag&t=' + Date.now(), {
                method: 'GET',
                credentials: 'include',
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            }).then(function (r) { return r.json(); }).catch(function () { return null; });
        }

        document.addEventListener('click', function (e) {
            var t = e.target;
            while (t && t !== document) {
                if (t.id === 'postStampBtn') break;
                if (t.getAttribute && t.getAttribute('data-login-action') === 'stamp') break;
                t = t.parentNode;
            }
            if (!t || t === document) return;
            if (window.__qk_stamp_loaded) return;
            if (window.__qk_stamp_autoloading) {
                e.preventDefault();
                e.stopPropagation();
                if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
                return;
            }
            window.__qk_stamp_autoloading = true;
            e.preventDefault();
            e.stopPropagation();
            if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
            ensureTplTag().then(function () {
                return loadStampPlugin();
            }).then(function () {
                window.__qk_stamp_autoloading = false;
                setTimeout(function () { try { t.click(); } catch (e2) { } }, 0);
            }).catch(function () {
                window.__qk_stamp_autoloading = false;
                try { alert('盖章功能加载失败'); } catch (e3) { }
            });
        }, true);
    })();
})();
