/**
 * 发布弹窗 - 核心模块
 */

(function() {
    'use strict';

    // 发布相关状态 - 暴露到全局供其他模块使用
    window.publishState = {
        images: [],
        videos: [],
        isAnonymous: false,
        circleId: 0,
        circleName: '',
        locationLatLng: '',
        locationName: '',
        isSubmitting: false
    };

    // 压缩配置
    const compressConfig = {
        maxWidth: 1200,
        maxHeight: 1200,
        quality: 0.8,
        imageCompressThreshold: 512 * 1024,
        maxImageSize: 10 * 1024 * 1024,
        videoCompressThreshold: 5 * 1024 * 1024,
        maxVideoSize: 50 * 1024 * 1024,
        videoBitrate: 500000
    };

    /**
     * 压缩图片
     */
    async function compressImage(file) {
        return new Promise((resolve, reject) => {
            if (!file.type.startsWith('image/')) {
                reject(new Error('不是图片文件'));
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                const img = new Image();
                img.onload = function() {
                    let { width, height } = img;
                    const { maxWidth, maxHeight } = compressConfig;

                    if (width > maxWidth) {
                        height = (height * maxWidth) / width;
                        width = maxWidth;
                    }
                    if (height > maxHeight) {
                        width = (width * maxHeight) / height;
                        height = maxHeight;
                    }

                    const canvas = document.createElement('canvas');
                    canvas.width = width;
                    canvas.height = height;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, width, height);

                    let mimeType = 'image/jpeg';
                    if (file.type === 'image/png') {
                        mimeType = 'image/png';
                    } else if (file.type === 'image/webp') {
                        mimeType = 'image/webp';
                    }

                    canvas.toBlob(function(blob) {
                        if (blob) {
                            const compressedFile = new File([blob], file.name, {
                                type: mimeType,
                                lastModified: Date.now()
                            });
                            resolve(compressedFile);
                        } else {
                            reject(new Error('压缩失败'));
                        }
                    }, mimeType, compressConfig.quality);
                };
                img.onerror = reject;
                img.src = e.target.result;
            };
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    }

    /**
     * 压缩视频
     */
    async function compressVideo(file) {
        return new Promise((resolve, reject) => {
            if (!file.type.startsWith('video/')) {
                reject(new Error('不是视频文件'));
                return;
            }

            // 文件小于阈值，不压缩
            if (file.size <= compressConfig.videoCompressThreshold) {
                resolve(file);
                return;
            }

            // 检查支持的 MIME 类型
            const mimeTypes = [
                'video/webm; codecs=vp9,opus',
                'video/webm; codecs=vp8,opus',
                'video/webm',
                'video/mp4'
            ];
            
            let supportedMimeType = '';
            for (const mimeType of mimeTypes) {
                if (MediaRecorder.isTypeSupported && MediaRecorder.isTypeSupported(mimeType)) {
                    supportedMimeType = mimeType;
                    break;
                }
            }

            // 如果不支持压缩，直接返回原文件
            if (!supportedMimeType) {
                console.log('浏览器不支持视频压缩，返回原文件');
                resolve(file);
                return;
            }

            const video = document.createElement('video');
            video.muted = true;
            video.preload = 'metadata';

            video.onloadedmetadata = function() {
                const duration = video.duration;
                
                // 限制最大录制时长为30秒
                const maxDuration = Math.min(duration, 30);
                
                video.currentTime = 0;
                video.play().then(() => {
                    const stream = video.captureStream();
                    const mediaRecorder = new MediaRecorder(stream, {
                        mimeType: supportedMimeType,
                        videoBitsPerSecond: compressConfig.videoBitrate
                    });

                    const chunks = [];
                    
                    mediaRecorder.ondataavailable = function(e) {
                        if (e.data && e.data.size > 0) {
                            chunks.push(e.data);
                        }
                    };

                    mediaRecorder.onstop = function() {
                        // 确保有数据
                        if (chunks.length === 0 || chunks.reduce((acc, c) => acc + c.size, 0) < 1000) {
                            console.error('视频录制数据为空或过小，返回原文件');
                            resolve(file);
                            return;
                        }

                        const mimeExt = supportedMimeType.split(';')[0].split('/')[1];
                        const blob = new Blob(chunks, { type: supportedMimeType.split(';')[0] });
                        
                        // 检查压缩后的文件是否有效
                        if (blob.size < 1000) {
                            console.error('压缩后视频文件过小，返回原文件');
                            resolve(file);
                            return;
                        }

                        const compressedFile = new File([blob], file.name.replace(/\.[^/.]+$/, '.' + mimeExt), {
                            type: supportedMimeType.split(';')[0],
                            lastModified: Date.now()
                        });
                        
                        // 如果压缩后比原文件还大，返回原文件
                        if (compressedFile.size >= file.size) {
                            console.log('压缩后文件更大，使用原文件');
                            resolve(file);
                            return;
                        }
                        
                        console.log(`视频压缩成功: ${(file.size / 1024 / 1024).toFixed(2)}MB -> ${(compressedFile.size / 1024 / 1024).toFixed(2)}MB`);
                        resolve(compressedFile);
                    };

                    mediaRecorder.onerror = function(e) {
                        console.error('视频压缩失败:', e);
                        resolve(file);
                    };
                    
                    mediaRecorder.start(1000); // 每1秒收集一次数据

                    // 根据视频时长设置停止时间
                    setTimeout(() => {
                        if (mediaRecorder.state === 'recording') {
                            mediaRecorder.stop();
                            video.pause();
                        }
                    }, maxDuration * 1000 + 500);
                }).catch(function(err) {
                    console.error('视频播放失败:', err);
                    resolve(file);
                });
            };

            video.onerror = function(e) {
                console.error('视频加载失败:', e);
                resolve(file);
            };
            
            video.src = URL.createObjectURL(file);
        });
    }

    /**
     * 生成唯一ID
     */
    function generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }

    /**
     * 处理发布提交
     */
    window.handlePublishSubmit = async function() {
        const content = document.getElementById('publishContent')?.value?.trim();
        const submitBtn = document.getElementById('publishSubmitBtn');

        if (!content && publishState.images.length === 0 && publishState.videos.length === 0) {
            showToast('请输入内容或添加图片/视频');
            return;
        }

        if (publishState.isSubmitting) return;

        publishState.isSubmitting = true;
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.textContent = '发布中...';
        }

        try {
            const formData = new FormData();
            formData.append('content', content || '');
            formData.append('is_anonymous', publishState.isAnonymous ? '1' : '0');
            
            // 添加圈子信息
            const circleId = document.getElementById('publishCircleId');
            const circleName = document.getElementById('publishCircleName');
            if (circleId && circleId.value) {
                formData.append('circle_id', circleId.value);
            }
            if (circleName && circleName.value) {
                formData.append('circle_name', circleName.value);
            }
            
            // 添加位置信息 - 只有用户主动点击位置按钮才提交
            const locationLatLng = document.getElementById('locationLatLng');
            if (locationLatLng) {
                // 检查用户是否主动设置了位置
                const isLocationSet = typeof getLocationSetByUser === 'function' 
                    ? getLocationSetByUser() 
                    : (typeof locationSetByUser !== 'undefined' ? locationSetByUser : false);
                    
                if (!isLocationSet) {
                    locationLatLng.value = '';
                } else if (locationLatLng.value) {
                    formData.append('location_latlng', locationLatLng.value);
                }
            }

            for (let i = 0; i < publishState.images.length; i++) {
                const image = publishState.images[i];
                if (image.file) {
                    if (image.file.size > compressConfig.imageCompressThreshold) {
                        try {
                            const compressedFile = await compressImage(image.file);
                            formData.append(`images[${i}]`, compressedFile);
                        } catch (e) {
                            formData.append(`images[${i}]`, image.file);
                        }
                    } else {
                        formData.append(`images[${i}]`, image.file);
                    }
                } else if (image.url) {
                    formData.append(`image_urls[${i}]`, image.url);
                }
            }

            for (let i = 0; i < publishState.videos.length; i++) {
                const video = publishState.videos[i];
                if (video.file) {
                    if (video.file.size > compressConfig.videoCompressThreshold) {
                        try {
                            const compressedFile = await compressVideo(video.file);
                            formData.append('video', compressedFile);
                        } catch (e) {
                            formData.append('video', video.file);
                        }
                    } else {
                        formData.append('video', video.file);
                    }
                }
            }

            const baseUrl = window.BASE_URL || window.location.origin;
            const response = await fetch(baseUrl + '/?r=mobileApi/publish', {
                method: 'POST',
                credentials: 'include',
                body: formData
            });

            const result = await response.json();

            if (result.code === 0) {
                showToast('发布成功');
                closeModal('publishModal');
                
                // 重置表单
                const contentEl = document.getElementById('publishContent');
                if (contentEl) contentEl.value = '';
                const charCount = document.getElementById('publishCharCount');
                if (charCount) charCount.textContent = '0';
                publishState.images = [];
                publishState.videos = [];
                
                // 重置位置信息
                if (typeof resetLocationSetByUser === 'function') {
                    resetLocationSetByUser();
                }
                
                // 刷新页面
                if (typeof refreshCurrentPage === 'function') {
                    refreshCurrentPage();
                } else {
                    window.location.reload();
                }
            } else {
                showToast(result.message || '发布失败');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Publish error:', error);
        } finally {
            publishState.isSubmitting = false;
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.textContent = '发布';
            }
        }
    };

    /**
     * 重置发布状态
     */
    function resetPublishState() {
        publishState.images = [];
        publishState.videos = [];
        publishState.isAnonymous = false;
        publishState.circleId = 0;
        publishState.circleName = '';
        publishState.locationLatLng = '';
        publishState.locationName = '';

        const content = document.getElementById('publishContent');
        if (content) content.value = '';

        const imagesContainer = document.getElementById('publishImages');
        if (imagesContainer) {
            imagesContainer.innerHTML = '';
            imagesContainer.classList.remove('active');
        }

        const videosContainer = document.getElementById('publishVideos');
        if (videosContainer) {
            videosContainer.innerHTML = '';
            videosContainer.classList.remove('active');
        }

        const charCount = document.getElementById('publishCharCount');
        if (charCount) charCount.textContent = '0';

        const circleBtn = document.getElementById('circleToolbarBtn');
        if (circleBtn) circleBtn.classList.remove('active');

        const circleLabel = document.getElementById('circleToolbarLabel');
        if (circleLabel) circleLabel.textContent = '圈子';

        const anonymousBtn = document.querySelector('.publish-tool-btn.anonymous-on');
        if (anonymousBtn) anonymousBtn.classList.remove('anonymous-on');

        const circleIdInput = document.getElementById('publishCircleId');
        if (circleIdInput) circleIdInput.value = '0';

        const circleNameInput = document.getElementById('publishCircleName');
        if (circleNameInput) circleNameInput.value = '';

        // 重置位置信息
        if (typeof resetLocationSetByUser === 'function') {
            resetLocationSetByUser();
        }
    }

    /**
     * 处理图片选择（同时支持图片和视频）
     */
    window.handlePublishImageSelect = function(event) {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const imagesContainer = document.getElementById('publishImages');
        const videosContainer = document.getElementById('publishVideos');
        if (!imagesContainer) return;

        // 处理图片数量限制
        const remainingImageSlots = 9 - publishState.images.length;
        let imageSlotsUsed = 0;
        // 视频最多1个
        const videoSlotsUsed = publishState.videos.length;

        Array.from(files).forEach(file => {
            if (file.type.startsWith('image/')) {
                // 处理图片
                if (imageSlotsUsed >= remainingImageSlots) {
                    showToast(`最多只能添加9张图片`);
                    return;
                }
                imageSlotsUsed++;

                if (file.size > compressConfig.maxImageSize) {
                    showToast(`图片超过最大允许大小（${(compressConfig.maxImageSize / 1024 / 1024).toFixed(0)}MB）`);
                    return;
                }

                if (file.size > compressConfig.imageCompressThreshold) {
                    showToast(`图片超过${(compressConfig.imageCompressThreshold / 1024).toFixed(0)}KB，将进行压缩...`);
                }

                const reader = new FileReader();
                reader.onload = function(e) {
                    const imageData = {
                        id: generateId(),
                        file: file,
                        url: e.target.result,
                        originalSize: file.size
                    };

                    publishState.images.push(imageData);

                    const imageItem = document.createElement('div');
                    imageItem.className = 'publish-image-item';
                    imageItem.dataset.id = imageData.id;
                    imageItem.innerHTML = `
                        <img src="${imageData.url}" alt="">
                        <button class="publish-image-remove" onclick="removePublishImage('${imageData.id}')">×</button>
                    `;

                    imagesContainer.appendChild(imageItem);
                    imagesContainer.classList.add('active');
                };

                reader.readAsDataURL(file);
            } else if (file.type.startsWith('video/')) {
                // 处理视频
                if (videoSlotsUsed >= 1) {
                    showToast('最多只能添加1个视频');
                    return;
                }

                if (file.size > compressConfig.maxVideoSize) {
                    showToast(`视频超过最大允许大小（${(compressConfig.maxVideoSize / 1024 / 1024).toFixed(0)}MB）`);
                    return;
                }

                if (file.size > compressConfig.videoCompressThreshold) {
                    showToast(`视频超过${(compressConfig.videoCompressThreshold / 1024 / 1024).toFixed(0)}MB，将进行压缩...`);
                }

                const videoData = {
                    id: generateId(),
                    file: file,
                    url: URL.createObjectURL(file),
                    duration: 0
                };

                publishState.videos.push(videoData);

                const videoItem = document.createElement('div');
                videoItem.className = 'publish-video-item';
                videoItem.dataset.id = videoData.id;
                videoItem.innerHTML = `
                    <div class="video-preview-wrapper">
                        <video src="${videoData.url}" controls poster="" preload="metadata"></video>
                        <div class="video-duration">00:00</div>
                    </div>
                    <button class="publish-video-remove" onclick="removePublishVideo('${videoData.id}')">×</button>
                `;

                if (videosContainer) {
                    videosContainer.appendChild(videoItem);
                    videosContainer.classList.add('active');
                }

                const video = videoItem.querySelector('video');
                video.onloadedmetadata = function() {
                    videoData.duration = video.duration;
                    const durationEl = videoItem.querySelector('.video-duration');
                    if (durationEl) {
                        const mins = Math.floor(video.duration / 60);
                        const secs = Math.floor(video.duration % 60);
                        durationEl.textContent = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
                    }
                };
            } else {
                showToast('请选择图片或视频文件');
            }
        });

        event.target.value = '';
    };

    /**
     * 处理视频选择
     */
    window.handlePublishVideoSelect = function(event) {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const videosContainer = document.getElementById('publishVideos');
        if (!videosContainer) return;

        if (publishState.videos.length >= 1) {
            showToast('最多只能添加1个视频');
            event.target.value = '';
            return;
        }

        const file = files[0];
        if (!file.type.startsWith('video/')) {
            showToast('请选择视频文件');
            event.target.value = '';
            return;
        }

        if (file.size > compressConfig.maxVideoSize) {
            showToast(`视频超过最大允许大小（${(compressConfig.maxVideoSize / 1024 / 1024).toFixed(0)}MB）`);
            event.target.value = '';
            return;
        }
        
        if (file.size > compressConfig.videoCompressThreshold) {
            showToast(`视频超过${(compressConfig.videoCompressThreshold / 1024 / 1024).toFixed(0)}MB，将进行压缩...`);
        }

        const videoData = {
            id: generateId(),
            file: file,
            url: URL.createObjectURL(file),
            duration: 0
        };

        publishState.videos.push(videoData);

        const videoItem = document.createElement('div');
        videoItem.className = 'publish-video-item';
        videoItem.dataset.id = videoData.id;
        videoItem.innerHTML = `
            <div class="video-preview-wrapper">
                <video src="${videoData.url}" controls poster="" preload="metadata"></video>
                <div class="video-duration">00:00</div>
            </div>
            <button class="publish-video-remove" onclick="removePublishVideo('${videoData.id}')">×</button>
        `;

        videosContainer.appendChild(videoItem);
        videosContainer.classList.add('active');

        const video = videoItem.querySelector('video');
        video.onloadedmetadata = function() {
            videoData.duration = video.duration;
            const durationEl = videoItem.querySelector('.video-duration');
            if (durationEl) {
                const mins = Math.floor(video.duration / 60);
                const secs = Math.floor(video.duration % 60);
                durationEl.textContent = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            }
        };

        event.target.value = '';
    };

    /**
     * 统一处理媒体选择（图片/视频）
     */
    window.handlePublishMediaSelect = function(event) {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const imagesContainer = document.getElementById('publishImages');
        
        let hasVideo = false;
        
        Array.from(files).forEach(file => {
            if (file.type.startsWith('video/')) {
                if (!hasVideo && publishState.videos.length === 0) {
                    hasVideo = true;
                    const videosContainer = document.getElementById('publishVideos');
                    if (!videosContainer) return;

                    const videoData = {
                        id: generateId(),
                        file: file,
                        url: URL.createObjectURL(file),
                        duration: 0
                    };

                    publishState.videos.push(videoData);

                    const videoItem = document.createElement('div');
                    videoItem.className = 'publish-video-item';
                    videoItem.dataset.id = videoData.id;
                    videoItem.innerHTML = `
                        <div class="video-preview-wrapper">
                            <video src="${videoData.url}" controls poster="" preload="metadata"></video>
                            <div class="video-duration">00:00</div>
                        </div>
                        <button class="publish-video-remove" onclick="removePublishVideo('${videoData.id}')">×</button>
                    `;

                    videosContainer.appendChild(videoItem);
                    videosContainer.classList.add('active');

                    const video = videoItem.querySelector('video');
                    video.onloadedmetadata = function() {
                        videoData.duration = video.duration;
                        const durationEl = videoItem.querySelector('.video-duration');
                        if (durationEl) {
                            const mins = Math.floor(video.duration / 60);
                            const secs = Math.floor(video.duration % 60);
                            durationEl.textContent = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
                        }
                    };
                }
            } else if (file.type.startsWith('image/')) {
                if (publishState.images.length < 9) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const imageData = {
                            id: generateId(),
                            file: file,
                            url: e.target.result,
                            originalSize: file.size
                        };

                        publishState.images.push(imageData);

                        const imageItem = document.createElement('div');
                        imageItem.className = 'publish-image-item';
                        imageItem.dataset.id = imageData.id;
                        imageItem.innerHTML = `
                            <img src="${imageData.url}" alt="">
                            <button class="publish-image-remove" onclick="removePublishImage('${imageData.id}')">×</button>
                        `;

                        imagesContainer.appendChild(imageItem);
                        imagesContainer.classList.add('active');
                    };

                    reader.readAsDataURL(file);
                }
            }
        });

        event.target.value = '';
    }

    /**
     * 移除发布图片
     */
    window.removePublishImage = function(imageId) {
        const index = publishState.images.findIndex(img => img.id === imageId);
        if (index > -1) {
            publishState.images.splice(index, 1);
        }

        const imageItem = document.querySelector(`.publish-image-item[data-id="${imageId}"]`);
        if (imageItem) {
            imageItem.remove();
        }

        const imagesContainer = document.getElementById('publishImages');
        if (imagesContainer && publishState.images.length === 0) {
            imagesContainer.classList.remove('active');
        }
    };

    /**
     * 移除发布视频
     */
    window.removePublishVideo = function(videoId) {
        const index = publishState.videos.findIndex(vid => vid.id === videoId);
        if (index > -1) {
            URL.revokeObjectURL(publishState.videos[index].url);
            publishState.videos.splice(index, 1);
        }

        const videoItem = document.querySelector(`.publish-video-item[data-id="${videoId}"]`);
        if (videoItem) {
            videoItem.remove();
        }

        const videosContainer = document.getElementById('publishVideos');
        if (videosContainer && publishState.videos.length === 0) {
            videosContainer.classList.remove('active');
        }
    };

    /**
     * 切换匿名发布
     */
    window.toggleAnonymous = function(btn) {
        publishState.isAnonymous = !publishState.isAnonymous;

        if (btn) {
            btn.classList.toggle('anonymous-on');
        }
    };

    /**
     * 切换圈子选择
     */
    window.toggleCircleSelect = function() {
        const circleModal = document.getElementById('circleSelectModal');
        if (!circleModal) return;

        if (circleModal.style.display === 'none' || !circleModal.classList.contains('active')) {
            loadCircles();
            circleModal.style.display = 'flex';
            setTimeout(() => {
                circleModal.classList.add('active');
            }, 10);
        } else {
            circleModal.classList.remove('active');
            setTimeout(() => {
                circleModal.style.display = 'none';
            }, 300);
        }
    };

    /**
     * 加载圈子列表
     */
    async function loadCircles() {
        const circleList = document.getElementById('circleList');
        if (!circleList) return;

        if (circleList.dataset.loaded === 'true' && circleList.children.length > 1) {
            return;
        }

        try {
            const response = await fetch('/?r=mobileApi/getCirclesList');
            const result = await response.json();

            if (result.code === 0) {
                const defaultItem = circleList.querySelector('.circle-item[data-circle-id="0"]');
                circleList.innerHTML = '';
                if (defaultItem) {
                    circleList.appendChild(defaultItem);
                }

                if (result.data && result.data.length > 0) {
                    result.data.forEach(circle => {
                        const circleItem = document.createElement('div');
                        circleItem.className = 'circle-item' + (circle.joined ? '' : ' circle-item-not-joined');
                        circleItem.dataset.circleId = circle.id;
                        circleItem.dataset.circleJoined = circle.joined ? '1' : '0';
                        circleItem.innerHTML = `
                            <span class="circle-radio" id="circleRadio${circle.id}"></span>
                            <span class="circle-text">${circle.name}</span>
                            ${circle.joined ? '' : '<span class="circle-not-joined-tag">未加入</span>'}
                        `;
                        circleItem.addEventListener('click', () => {
                            if (circle.joined) {
                                selectCircle(circle.id, circle.name);
                            } else {
                                showToast('还未加入该圈子');
                            }
                        });
                        circleList.appendChild(circleItem);
                    });
                } else {
                    const emptyItem = document.createElement('div');
                    emptyItem.className = 'circle-item-empty';
                    emptyItem.style.cssText = 'padding: 20px; text-align: center; color: #999;';
                    emptyItem.textContent = '暂无圈子';
                    circleList.appendChild(emptyItem);
                }

                circleList.dataset.loaded = 'true';
            }
        } catch (error) {
            console.error('Load circles error:', error);
        }
    }

    /**
     * 刷新圈子列表（供外部调用）
     */
    window.refreshPublishCircles = async function() {
        const circleList = document.getElementById('circleList');
        if (!circleList) return;

        try {
            const response = await fetch('/?r=mobileApi/getCirclesList');
            const result = await response.json();

            if (result.code === 0) {
                const defaultItem = circleList.querySelector('.circle-item[data-circle-id="0"]');
                circleList.innerHTML = '';
                if (defaultItem) {
                    circleList.appendChild(defaultItem);
                }

                if (result.data && result.data.length > 0) {
                    result.data.forEach(circle => {
                        const circleItem = document.createElement('div');
                        circleItem.className = 'circle-item' + (circle.joined ? '' : ' circle-item-not-joined');
                        circleItem.dataset.circleId = circle.id;
                        circleItem.dataset.circleJoined = circle.joined ? '1' : '0';
                        circleItem.innerHTML = `
                            <span class="circle-radio" id="circleRadio${circle.id}"></span>
                            <span class="circle-text">${circle.name}</span>
                            ${circle.joined ? '' : '<span class="circle-not-joined-tag">未加入</span>'}
                        `;
                        circleItem.addEventListener('click', () => {
                            if (circle.joined) {
                                selectCircle(circle.id, circle.name);
                            } else {
                                showToast('还未加入该圈子');
                            }
                        });
                        circleList.appendChild(circleItem);
                    });
                } else {
                    const emptyItem = document.createElement('div');
                    emptyItem.className = 'circle-item-empty';
                    emptyItem.style.cssText = 'padding: 20px; text-align: center; color: #999;';
                    emptyItem.textContent = '暂无圈子';
                    circleList.appendChild(emptyItem);
                }

                circleList.dataset.loaded = 'true';
            }
        } catch (error) {
            console.error('Refresh circles error:', error);
        }
    };

    /**
     * 选择圈子
     */
    window.selectCircle = function(circleId, circleName) {
        publishState.circleId = circleId;
        publishState.circleName = circleName;

        const circleIdInput = document.getElementById('publishCircleId');
        if (circleIdInput) circleIdInput.value = circleId.toString();

        const circleNameInput = document.getElementById('publishCircleName');
        if (circleNameInput) circleNameInput.value = circleName;

        const circleBtn = document.getElementById('circleToolbarBtn');
        const circleLabel = document.getElementById('circleToolbarLabel');
        if (circleId !== 0 && circleName) {
            // 选中圈子后显示圈子名称
            if (circleBtn) circleBtn.classList.add('active');
            if (circleLabel) {
                circleLabel.textContent = circleName;
            }
            showToast('已选择: ' + circleName);
        } else {
            if (circleBtn) circleBtn.classList.remove('active');
            if (circleLabel) {
                circleLabel.textContent = '圈子';
            }
        }

        toggleCircleSelect();
    };

    /**
     * 更新字符计数（共享函数，供其他模块调用）
     */
    window.updatePublishCharCount = function() {
        const content = document.getElementById('publishContent')?.value || '';
        const charCount = document.getElementById('publishCharCount');
        if (charCount) {
            charCount.textContent = content.length.toString();
        }
    };

    /**
     * 初始化发布弹窗
     */
    function initPublishModal() {
        const imageInput = document.getElementById('publishImageInput');
        if (imageInput) {
            imageInput.addEventListener('change', window.handlePublishImageSelect);
        }

        const mediaInput = document.getElementById('publishMediaInput');
        if (mediaInput) {
            mediaInput.addEventListener('change', window.handlePublishMediaSelect);
        }

        const content = document.getElementById('publishContent');
        if (content) {
            content.addEventListener('input', window.updatePublishCharCount);
        }

        const submitBtn = document.getElementById('publishSubmitBtn');
        if (submitBtn) {
            submitBtn.addEventListener('click', window.handlePublishSubmit);
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', initPublishModal);
})();
