<div class="modal fade" id="restartModal" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
  <div class="modal-content">
    <div class="modal-header bg-warning">
      <h5 class="modal-title">系统维护提示</h5>
    </div>
    <div class="modal-body text-center py-4">
      <div class="spinner-border text-primary mb-3"></div>
      <p id="restartStatus">服务正在重启，请勿关闭页面...</p>
    </div>
  </div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const modal = new bootstrap.Modal('#restartModal');
    const statusEl = document.getElementById('restartStatus');
    
    // 立即检查现有消息
    checkExistingMessages();
    
    // 监听后续消息变化
    const observer = new MutationObserver(function(mutations) {
        checkExistingMessages();
    });

    function checkExistingMessages() {
        const successMsg = document.querySelector('.messagelist .success');
        if (successMsg && /自动重启/.test(successMsg.textContent)) {
            modal.show();
            startHealthCheck();
        }
    }

    function startHealthCheck() {
        let attempts = 0;
        const maxAttempts = 20;
        
        const checkInterval = setInterval(() => {
            fetch('/api/health-check/?code={{security_code}}')
                .then(res => res.ok ? res.json() : Promise.reject())
                .then(data => {
                    attempts++;
                    statusEl.textContent = `状态检测中 (${attempts}/${maxAttempts})`;
                    
                    if (data.status === 'ready' || attempts >= maxAttempts) {
                        clearInterval(checkInterval);
                        statusEl.textContent = '服务已恢复';
                        setTimeout(() => {
                            modal.hide();
                            window.location.reload();
                        }, 1500);
                    }
                })
                .catch(() => {
                    statusEl.textContent = `连接失败 (${attempts}/${maxAttempts})`;
                });
        }, 3000);
    }

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});


</script>