// 主要JavaScript功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化
    init();
});

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

function bindEvents() {
    // 评论表单提交
    const commentForm = document.getElementById('commentForm');
    if (commentForm) {
        commentForm.addEventListener('submit', submitComment);
    }
    
    // 图片点击放大 - 更新选择器以包含所有内容中的图片
    bindImageClickEvents();
}

// 绑定图片点击事件
function bindImageClickEvents() {
    const images = document.querySelectorAll('.moment-content img, .post-content img, .ql-editor img, .moment-image, .post-image');
    images.forEach(img => {
        img.addEventListener('click', function() {
            showImageModal(this.src);
        });
    });
}

// 显示发布动态弹窗
function showPostModal() {
    const modal = document.getElementById('postModal');
    if (modal) {
        modal.classList.add('show');
    }
}

// 隐藏发布动态弹窗
function hidePostModal() {
    const modal = document.getElementById('postModal');
    if (modal) {
        modal.classList.remove('show');
    }
}

// 提交评论
function submitComment(event) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    
    // 检查是否需要验证码
    const email = formData.get('email');
    const verificationCode = formData.get('verification_code');
    
    if (email && !verificationCode) {
        // 显示验证码输入框
        const verificationSection = form.querySelector('.verification-section');
        if (verificationSection) {
            verificationSection.style.display = 'block';
            showNotification('请先获取验证码', 'warning');
            return;
        }
    }
    
    // 显示加载状态
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.textContent;
    submitBtn.textContent = '提交中...';
    submitBtn.disabled = true;
    
    fetch('/api/comment', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('评论提交成功，等待审核', 'success');
            form.reset();
            // 隐藏验证码区域
            const verificationSection = form.querySelector('.verification-section');
            if (verificationSection) {
                verificationSection.style.display = 'none';
            }
        } else {
            showNotification(data.error || '评论提交失败', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误，请稍后重试', 'error');
    })
    .finally(() => {
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
    });
}

// 发送验证码
function sendVerificationCode() {
    const form = document.getElementById('commentForm');
    const email = form.querySelector('input[name="email"]').value;
    
    if (!email) {
        showNotification('请先输入邮箱地址', 'warning');
        return;
    }
    
    const btn = event.target;
    const originalText = btn.textContent;
    btn.textContent = '发送中...';
    btn.disabled = true;
    
    fetch('/api/send-verification', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email: email })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('验证码已发送到您的邮箱', 'success');
            // 开始倒计时
            startCountdown(btn, 60);
        } else {
            showNotification(data.error || '验证码发送失败', 'error');
            btn.textContent = originalText;
            btn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误，请稍后重试', 'error');
        btn.textContent = originalText;
        btn.disabled = false;
    });
}

// 倒计时功能
function startCountdown(btn, seconds) {
    let count = seconds;
    const timer = setInterval(() => {
        btn.textContent = `${count}秒后重发`;
        count--;
        
        if (count < 0) {
            clearInterval(timer);
            btn.textContent = '发送验证码';
            btn.disabled = false;
        }
    }, 1000);
}

// 显示图片弹窗
function showImageModal(src) {
    // 创建弹窗
    const modal = document.createElement('div');
    modal.className = 'image-modal';
    modal.innerHTML = `
        <span class="image-modal-close">&times;</span>
        <img class="image-modal-content" src="${src}" alt="图片">
    `;
    
    // 添加样式 - 使用更简洁的居中方式
    modal.style.cssText = `
        position: fixed;
        z-index: 2000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.9);
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    `;
    
    const img = modal.querySelector('.image-modal-content');
    img.style.cssText = `
        max-width: 90vw;
        max-height: 90vh;
        width: auto;
        height: auto;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.5);
        cursor: default;
    `;
    
    const closeBtn = modal.querySelector('.image-modal-close');
    closeBtn.style.cssText = `
        position: absolute;
        top: 20px;
        right: 30px;
        color: white;
        font-size: 40px;
        font-weight: bold;
        cursor: pointer;
        z-index: 2001;
        text-shadow: 0 2px 4px rgba(0,0,0,0.5);
    `;
    
    // 绑定关闭事件
    closeBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        document.body.removeChild(modal);
    });
    
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    });
    
    // 阻止图片本身的点击事件冒泡
    img.addEventListener('click', (e) => {
        e.stopPropagation();
    });
    
    // 添加ESC键关闭功能
    const handleEscape = (e) => {
        if (e.key === 'Escape') {
            document.body.removeChild(modal);
            document.removeEventListener('keydown', handleEscape);
        }
    };
    document.addEventListener('keydown', handleEscape);
    
    document.body.appendChild(modal);
}

// 显示通知
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);
}

// 点击外部关闭弹窗
window.addEventListener('click', function(event) {
    const modal = document.getElementById('postModal');
    if (event.target === modal) {
        hidePostModal();
    }
});

// ESC键关闭弹窗
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        hidePostModal();
    }
});

// 显示确认对话框
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);
}
