// 管理后台JavaScript功能
document.addEventListener('DOMContentLoaded', function() {
    init();
});

function init() {
    // 初始化功能
    bindEvents();
    autoHideAlerts();
}

function bindEvents() {
    // 绑定事件
}

// 自动隐藏PHP生成的消息提示
function autoHideAlerts() {
    const alerts = document.querySelectorAll('.alert-success, .alert-error');
    alerts.forEach(alert => {
        // 3秒后自动隐藏
        setTimeout(() => {
            alert.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            alert.style.opacity = '0';
            alert.style.transform = 'translateY(-10px)';
            
            // 动画完成后移除元素
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.parentNode.removeChild(alert);
                }
            }, 300);
        }, 3000);
    });
}

// 审核评论
function approveComment(postId, commentId) {
    showConfirmDialog('确定要通过这条评论吗？', () => {
        const formData = new FormData();
        formData.append('action', 'approve');
        formData.append('post_id', postId);
        formData.append('comment_id', commentId);
        
        fetch('/admin/comment-action.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('评论已通过', 'success');
                // 刷新页面或移除元素
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } else {
                showNotification(data.error || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('网络错误', 'error');
        });
    });
}

// 删除评论
function deleteComment(postId, commentId) {
    showConfirmDialog('确定要删除这条评论吗？此操作不可恢复。', () => {
        const formData = new FormData();
        formData.append('action', 'delete');
        formData.append('post_id', postId);
        formData.append('comment_id', commentId);
        
        fetch('/admin/comment-action.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('评论已删除', 'success');
                // 刷新页面或移除元素
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } else {
                showNotification(data.error || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('网络错误', 'error');
        });
    });
}

// 删除文章
function deletePost(year, month, day, slug) {
    showConfirmDialog('确定要删除这篇文章吗？此操作不可恢复。', () => {
        const formData = new FormData();
        formData.append('action', 'delete');
        formData.append('year', year);
        formData.append('month', month);
        formData.append('day', day);
        formData.append('slug', slug);
        
        fetch('/admin/post-action.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('文章已删除', 'success');
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } else {
                showNotification(data.error || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('网络错误', 'error');
        });
    });
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // 样式
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 6px;
        color: white;
        font-size: 14px;
        z-index: 3000;
        max-width: 300px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        transform: translateX(100%);
        transition: transform 0.3s ease;
    `;
    
    // 根据类型设置颜色
    switch (type) {
        case 'success':
            notification.style.backgroundColor = '#52c41a';
            break;
        case 'error':
            notification.style.backgroundColor = '#ff4d4f';
            break;
        case 'warning':
            notification.style.backgroundColor = '#faad14';
            break;
        default:
            notification.style.backgroundColor = '#1890ff';
    }
    
    document.body.appendChild(notification);
    
    // 动画显示
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 表单验证
function validateForm(form) {
    const requiredFields = form.querySelectorAll('[required]');
    let isValid = true;
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            field.style.borderColor = '#ff4d4f';
            isValid = false;
        } else {
            field.style.borderColor = '#d9d9d9';
        }
    });
    
    return isValid;
}

// 文件上传预览
function previewImages(input) {
    const preview = document.getElementById('imagePreview');
    if (!preview) return;
    
    preview.innerHTML = '';
    
    if (input.files) {
        Array.from(input.files).forEach(file => {
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.style.cssText = `
                        width: 100px;
                        height: 100px;
                        object-fit: cover;
                        border-radius: 6px;
                        margin: 5px;
                    `;
                    preview.appendChild(img);
                };
                reader.readAsDataURL(file);
            }
        });
    }
}

// 应用历史图片
function applyHistoryImage(type, filename) {
    if (!confirm('确定要应用这个' + (type === 'background' ? '背景图' : '头像') + '吗？')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('type', type);
    formData.append('filename', filename);
    
    fetch('/admin/apply-history-image.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            // 刷新页面以显示更新后的图片
            setTimeout(() => {
                location.reload();
            }, 1000);
        } else {
            showNotification(data.error || '应用失败', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误', 'error');
    });
}

// 显示确认对话框
function showConfirmDialog(message, onConfirm, onCancel = null) {
    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.className = 'confirm-overlay';
    overlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 10000;
        display: flex;
        align-items: center;
        justify-content: center;
    `;
    
    // 创建对话框
    const dialog = document.createElement('div');
    dialog.className = 'confirm-dialog';
    dialog.style.cssText = `
        background: white;
        border-radius: 8px;
        padding: 24px;
        max-width: 400px;
        width: 90%;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        text-align: center;
    `;
    
    // 创建消息
    const messageEl = document.createElement('p');
    messageEl.textContent = message;
    messageEl.style.cssText = `
        margin: 0 0 20px 0;
        font-size: 16px;
        line-height: 1.5;
        color: #333;
    `;
    
    // 创建按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.style.cssText = `
        display: flex;
        gap: 12px;
        justify-content: center;
    `;
    
    // 创建取消按钮
    const cancelBtn = document.createElement('button');
    cancelBtn.textContent = '取消';
    cancelBtn.style.cssText = `
        padding: 8px 20px;
        border: 1px solid #ddd;
        background: white;
        color: #666;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    `;
    
    // 创建确认按钮
    const confirmBtn = document.createElement('button');
    confirmBtn.textContent = '确认';
    confirmBtn.style.cssText = `
        padding: 8px 20px;
        border: none;
        background: #dc3545;
        color: white;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    `;
    
    // 关闭对话框函数
    const closeDialog = () => {
        document.body.removeChild(overlay);
    };
    
    // 绑定事件
    cancelBtn.addEventListener('click', () => {
        closeDialog();
        if (onCancel) onCancel();
    });
    
    confirmBtn.addEventListener('click', () => {
        closeDialog();
        if (onConfirm) onConfirm();
    });
    
    // 点击遮罩层关闭
    overlay.addEventListener('click', (e) => {
        if (e.target === overlay) {
            closeDialog();
            if (onCancel) onCancel();
        }
    });
    
    // 组装对话框
    buttonContainer.appendChild(cancelBtn);
    buttonContainer.appendChild(confirmBtn);
    dialog.appendChild(messageEl);
    dialog.appendChild(buttonContainer);
    overlay.appendChild(dialog);
    
    // 显示对话框
    document.body.appendChild(overlay);
    
    // 聚焦到确认按钮
    setTimeout(() => confirmBtn.focus(), 100);
}
