// 发布页面配置
const MAX_IMAGE_WIDTH = 1280;
const MAX_IMAGE_HEIGHT = 1280;
const COMPRESSION_QUALITY = 0.5;
const MAX_VIDEO_SIZE = 50 * 1024 * 1024;

let uploadedImages = [];
let uploadedVideo = null;
let selectedCircleId = 0;
let selectedCircleName = '';

// 图片压缩函数
async function compressImage(file) {
    return new Promise((resolve) => {
        if (!file.type.startsWith('image/')) {
            resolve(file);
            return;
        }
        
        const img = new Image();
        img.onload = function() {
            try {
                const MAX_WIDTH = 800;
                const MAX_HEIGHT = 800;
                
                let width = img.width;
                let height = img.height;
                
                if (width > MAX_WIDTH) {
                    height = (height * MAX_WIDTH) / width;
                    width = MAX_WIDTH;
                }
                if (height > MAX_HEIGHT) {
                    width = (width * MAX_HEIGHT) / height;
                    height = MAX_HEIGHT;
                }
                
                let quality = 0.6;
                const originalSizeKB = file.size / 1024;
                
                if (originalSizeKB > 2048) {
                    quality = 0.45;
                } else if (originalSizeKB > 1024) {
                    quality = 0.5;
                } else if (originalSizeKB > 512) {
                    quality = 0.55;
                } else if (originalSizeKB > 256) {
                    quality = 0.6;
                } else {
                    quality = 0.7;
                }
                
                const canvas = document.createElement('canvas');
                canvas.width = Math.round(width);
                canvas.height = Math.round(height);
                
                const ctx = canvas.getContext('2d');
                if (!ctx) {
                    resolve(file);
                    return;
                }
                
                ctx.imageSmoothingEnabled = true;
                ctx.imageSmoothingQuality = 'high';
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                
                function tryCompress(attemptQuality) {
                    canvas.toBlob(function(blob) {
                        if (blob) {
                            const compressedSizeKB = blob.size / 1024;
                            const targetSizeKB = originalSizeKB * 0.6;
                            
                            if (compressedSizeKB > targetSizeKB && attemptQuality > 0.3) {
                                tryCompress(attemptQuality - 0.05);
                                return;
                            }
                            
                            const compressedFile = new File([blob], file.name.replace(/\.[^.]+$/, '.jpg'), {
                                type: 'image/jpeg',
                                lastModified: Date.now()
                            });
                            resolve(compressedFile);
                        } else {
                            resolve(file);
                        }
                    }, 'image/jpeg', attemptQuality);
                }
                
                tryCompress(quality);
            } catch (error) {
                resolve(file);
            }
        };
        
        img.onerror = function() {
            resolve(file);
        };
        
        img.src = URL.createObjectURL(file);
    });
}

// 视频处理函数
async function processVideo(file) {
    return new Promise((resolve) => {
        const infoEl = document.getElementById('compressionInfo');
        infoEl.textContent = '正在处理视频...';
        
        const video = document.createElement('video');
        video.preload = 'metadata';
        video.muted = true;
        video.playsInline = true;
        
        video.onloadedmetadata = async function() {
            const duration = video.duration;
            const originalWidth = video.videoWidth;
            const originalHeight = video.videoHeight;
            const originalSize = file.size;
            
            // 限制视频时长（最长30秒）
            if (duration > 30) {
                infoEl.textContent = '视频时长不能超过30秒';
                URL.revokeObjectURL(video.src);
                resolve({ success: false, message: '视频时长不能超过30秒' });
                return;
            }
            
            const MAX_WIDTH = 640;
            const MAX_HEIGHT = 960;
            
            let targetWidth = originalWidth;
            let targetHeight = originalHeight;
            
            if (targetWidth > MAX_WIDTH) {
                targetHeight = Math.round((targetHeight * MAX_WIDTH) / targetWidth);
                targetWidth = MAX_WIDTH;
            }
            if (targetHeight > MAX_HEIGHT) {
                targetWidth = Math.round((targetWidth * MAX_HEIGHT) / targetHeight);
                targetHeight = MAX_HEIGHT;
            }
            
            let targetBitrate;
            if (targetWidth >= 640) {
                targetBitrate = 400000;
            } else if (targetWidth >= 480) {
                targetBitrate = 250000;
            } else if (targetWidth >= 320) {
                targetBitrate = 150000;
            } else {
                targetBitrate = 100000;
            }
            
            if (duration < 10) {
                targetBitrate = Math.round(targetBitrate * 0.7);
            } else if (duration < 20) {
                targetBitrate = Math.round(targetBitrate * 0.85);
            }
            
            infoEl.textContent = `正在压缩视频...`;
            
            try {
                const tempVideo = document.createElement('video');
                tempVideo.src = video.src;
                tempVideo.muted = true;
                tempVideo.playsInline = true;
                
                const canvas = document.createElement('canvas');
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                const ctx = canvas.getContext('2d');
                
                const audioContext = new AudioContext();
                const audioSource = audioContext.createMediaElementSource(tempVideo);
                const audioDestination = audioContext.createMediaStreamDestination();
                audioSource.connect(audioDestination);
                
                const videoStream = canvas.captureStream(15);
                const tracks = [...videoStream.getTracks(), ...audioDestination.stream.getTracks()];
                const combinedStream = new MediaStream(tracks);
                
                let mimeType = 'video/mp4;codecs=avc1';
                if (!MediaRecorder.isTypeSupported(mimeType)) {
                    mimeType = 'video/webm;codecs=vp8';
                    if (!MediaRecorder.isTypeSupported(mimeType)) {
                        mimeType = 'video/webm;codecs=vp9';
                    }
                }
                
                const mediaRecorder = new MediaRecorder(combinedStream, {
                    mimeType: mimeType,
                    videoBitsPerSecond: targetBitrate,
                    audioBitsPerSecond: 64000,
                    bitsPerSecond: targetBitrate + 64000
                });
                
                const chunks = [];
                mediaRecorder.ondataavailable = e => {
                    if (e.data.size > 0) {
                        chunks.push(e.data);
                    }
                };
                
                mediaRecorder.onstop = function() {
                    const blob = new Blob(chunks, { type: mimeType });
                    const ext = mimeType.includes('mp4') ? '.mp4' : '.webm';
                    const compressedFile = new File([blob], file.name.replace(/\.[^.]+$/, ext), {
                        type: mimeType,
                        lastModified: Date.now()
                    });
                    
                    const savedSize = ((1 - compressedFile.size / file.size) * 100).toFixed(1);
                    infoEl.textContent = `视频压缩完成: ${(compressedFile.size / 1024 / 1024).toFixed(2)}MB (节省${savedSize}%)`;
                    
                    URL.revokeObjectURL(video.src);
                    URL.revokeObjectURL(tempVideo.src);
                    audioContext.close();
                    combinedStream.getTracks().forEach(track => track.stop());
                    
                    resolve({ success: true, file: compressedFile });
                };
                
                mediaRecorder.onerror = function(e) {
                    infoEl.textContent = '视频压缩失败';
                    URL.revokeObjectURL(video.src);
                    audioContext.close();
                    resolve({ success: false, message: '视频压缩失败' });
                };
                
                await tempVideo.play();
                mediaRecorder.start();
                
                function drawFrame() {
                    if (!tempVideo.paused && !tempVideo.ended) {
                        ctx.drawImage(tempVideo, 0, 0, targetWidth, targetHeight);
                        requestAnimationFrame(drawFrame);
                    }
                }
                drawFrame();
                
                setTimeout(() => {
                    mediaRecorder.stop();
                    tempVideo.pause();
                }, duration * 1000 + 500);
                
            } catch (error) {
                infoEl.textContent = '视频压缩不可用，将使用原始视频';
                URL.revokeObjectURL(video.src);
                resolve({ success: true, file: file });
            }
        };
        
        video.onerror = function() {
            infoEl.textContent = '视频处理失败';
            resolve({ success: false, message: '无法读取视频文件' });
        };
        
        video.src = URL.createObjectURL(file);
    });
}

function showMediaUpload() {
    document.getElementById('mediaUploadSection').style.display = 'block';
}

function togglePublishCircleSelect() {
    const section = document.getElementById('circleSelectSection');
    section.classList.toggle('active');
}

function selectPublishCircle(circleId, circleName) {
    // 移除之前选中的样式
    document.querySelectorAll('.circle-tag').forEach(tag => {
        tag.classList.remove('selected');
    });
    
    // 添加当前选中的样式
    const selectedTag = document.querySelector(`[data-circle-id="${circleId}"]`);
    if (selectedTag) {
        selectedTag.classList.add('selected');
    }
    
    selectedCircleId = circleId;
    selectedCircleName = circleName;
    
    // 更新隐藏字段
    document.getElementById('circleId').value = circleId;
    document.getElementById('circleName').value = circleName;
}

function insertTopic() {
    const textarea = document.getElementById('contentInput');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value;
    textarea.value = text.substring(0, start) + '#话题#' + text.substring(end);
    textarea.focus();
    textarea.setSelectionRange(start + 2, start + 2);
}

function insertAt() {
    const textarea = document.getElementById('contentInput');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value;
    textarea.value = text.substring(0, start) + '@' + text.substring(end);
    textarea.focus();
    textarea.setSelectionRange(start + 1, start + 1);
}

function removeMedia(element) {
    const preview = element.parentElement;
    const previews = document.querySelectorAll('.upload-preview');
    const index = Array.from(previews).indexOf(preview);
    if (index >= 0 && index < uploadedImages.length) {
        uploadedImages.splice(index, 1);
    }
    preview.remove();
    updatePublishButton();
}

function removeVideo() {
    uploadedVideo = null;
    document.getElementById('mediaUploadSection').style.display = 'block';
    const videoPreviewContainer = document.getElementById('videoPreviewContainer');
    videoPreviewContainer.classList.remove('active');
    document.getElementById('videoPreviewPlayer').src = '';
    document.getElementById('compressionInfo').textContent = '';
    updatePublishButton();
}

function updatePublishButton() {
    const content = document.getElementById('contentInput').value.trim();
    const publishBtn = document.getElementById('publishBtn');
    if (content || uploadedImages.length > 0 || uploadedVideo) {
        publishBtn.disabled = false;
    } else {
        publishBtn.disabled = true;
    }
}

async function submitForm() {
    const content = document.getElementById('contentInput').value.trim();
    if (!content && uploadedImages.length === 0 && !uploadedVideo) {
        alert('请输入内容或上传图片/视频');
        return;
    }
    
    const publishBtn = document.getElementById('publishBtn');
    publishBtn.textContent = '发布中...';
    publishBtn.disabled = true;
    
    try {
        const formData = new FormData();
        formData.append('content', content);
        formData.append('circle_id', selectedCircleId);
        formData.append('circle_name', selectedCircleName);
        
        for (let i = 0; i < uploadedImages.length; i++) {
            formData.append('images[]', uploadedImages[i]);
        }
        
        if (uploadedVideo) {
            formData.append('video', uploadedVideo);
        }
        
        const response = await fetch(window.HuSNS_Publish.apiUrls.publish, {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.code === 0 || result.success) {
            alert('发布成功');
            window.location.href = window.HuSNS_Publish.redirectUrls.home;
        } else {
            alert(result.message || '发布失败');
            publishBtn.textContent = '发布';
            publishBtn.disabled = false;
        }
    } catch (error) {
        alert('发布失败，请重试');
        publishBtn.textContent = '发布';
        publishBtn.disabled = false;
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    const contentInput = document.getElementById('contentInput');
    const publishBtn = document.getElementById('publishBtn');
    const mediaInput = document.getElementById('mediaInput');
    const mediaPreviewContainer = document.getElementById('mediaPreviewContainer');
    
    contentInput.addEventListener('input', updatePublishButton);
    
    mediaInput.addEventListener('change', function(e) {
        const files = e.target.files;
        if (files.length > 0) {
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 检查是否已经有视频
                if (file.type.startsWith('video/')) {
                    if (uploadedVideo) {
                        alert('最多只能上传一个视频');
                        continue;
                    }
                    
                    // 如果有图片，先清空图片
                    if (uploadedImages.length > 0) {
                        uploadedImages = [];
                        document.querySelectorAll('.upload-preview').forEach(el => el.remove());
                    }
                    
                    processVideo(file).then(result => {
                        if (result.success) {
                            uploadedVideo = result.file;
                            document.getElementById('mediaUploadSection').style.display = 'none';
                            const videoPreviewContainer = document.getElementById('videoPreviewContainer');
                            videoPreviewContainer.classList.add('active');
                            document.getElementById('videoPreviewPlayer').src = URL.createObjectURL(result.file);
                        } else {
                            alert(result.message || '视频处理失败');
                        }
                    });
                } else if (file.type.startsWith('image/')) {
                    // 如果有视频，先移除视频
                    if (uploadedVideo) {
                        removeVideo();
                    }
                    
                    if (uploadedImages.length >= 9) {
                        alert('最多只能上传9张图片');
                        break;
                    }
                    
                    compressImage(file).then(compressedFile => {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const preview = document.createElement('div');
                            preview.className = 'upload-preview';
                            preview.innerHTML = `
                                <img class="uploaded-media" src="${e.target.result}" alt="">
                                <div class="remove-media" onclick="removeMedia(this)">×</div>
                            `;
                            mediaPreviewContainer.insertBefore(preview, mediaPreviewContainer.lastElementChild);
                            uploadedImages.push(compressedFile);
                            updatePublishButton();
                        };
                        reader.readAsDataURL(compressedFile);
                    });
                }
            }
            this.value = '';
        }
    });
    
    updatePublishButton();
});