/**
 * 发布弹窗 - 话题选择模块
 */

(function() {
    'use strict';

    /**
     * 插入话题到发布框
     */
    window.insertTopic = function() {
        const textarea = document.getElementById('publishContent');
        if (!textarea) return;

        const topicText = '#话题#';
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const value = textarea.value;

        textarea.value = value.substring(0, start) + topicText + value.substring(end);

        textarea.selectionStart = textarea.selectionEnd = start + 1;
        textarea.focus();

        if (window.updatePublishCharCount) {
            window.updatePublishCharCount();
        }
    };

    /**
     * 创建话题选择弹窗
     */
    function createTopicModal() {
        const modal = document.createElement('div');
        modal.className = 'modal-overlay topic-select-modal';
        modal.id = 'topicSelectModal';
        modal.style.display = 'none';
        modal.innerHTML = `
            <div class="modal-container topic-select-container">
                <div class="modal-header">
                    <button class="modal-close" onclick="closeTopicModal()">×</button>
                    <h3 class="modal-title">选择话题</h3>
                    <div style="width: 32px;"></div>
                </div>
                <div class="topic-search">
                    <input type="text" id="topicSearchInput" placeholder="搜索话题..." oninput="searchTopics()">
                </div>
                <div class="topic-list-container" id="topicList">
                    <div class="topic-section">
                        <div class="topic-section-title">热门话题</div>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }

    /**
     * 加载话题列表
     */
    async function loadTopics() {
        const topicList = document.getElementById('topicList');
        if (!topicList) return;

        try {
            const baseUrl = window.BASE_URL || window.location.origin;
            const response = await fetch(baseUrl + '/?r=mobileApi/getHotTopics');
            const result = await response.json();

            topicList.innerHTML = '';

            if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
                const hotSection = document.createElement('div');
                hotSection.className = 'topic-section';
                hotSection.innerHTML = '<div class="topic-section-title">🔥 热门话题</div>';

                result.data.items.forEach(topic => {
                    const topicItem = document.createElement('div');
                    topicItem.className = 'topic-item';
                    topicItem.dataset.topicName = topic.name;
                    topicItem.innerHTML = `
                        <span class="topic-name">#${topic.name}</span>
                        <span class="topic-count">${topic.count}讨论</span>
                    `;
                    topicItem.addEventListener('click', () => {
                        insertTopicText(topic.name);
                        closeTopicModal();
                    });
                    hotSection.appendChild(topicItem);
                });
                topicList.appendChild(hotSection);
            } else {
                loadMockTopics();
            }
        } catch (error) {
            console.error('Load topics error:', error);
            loadMockTopics();
        }
    }

    /**
     * 加载模拟话题数据
     */
    function loadMockTopics() {
        const topicList = document.getElementById('topicList');
        if (!topicList) return;

        const mockTopics = [
            { name: '今日热门', count: 1234 },
            { name: '科技前沿', count: 856 },
            { name: '生活分享', count: 2341 },
            { name: '美食探店', count: 567 },
            { name: '旅行日记', count: 987 },
            { name: '数码评测', count: 432 },
            { name: '职场感悟', count: 723 },
            { name: '读书打卡', count: 345 }
        ];

        topicList.innerHTML = '';
        const hotSection = document.createElement('div');
        hotSection.className = 'topic-section';
        hotSection.innerHTML = '<div class="topic-section-title">🔥 热门话题</div>';

        mockTopics.forEach(topic => {
            const topicItem = document.createElement('div');
            topicItem.className = 'topic-item';
            topicItem.dataset.topicName = topic.name;
            topicItem.innerHTML = `
                <span class="topic-name">#${topic.name}</span>
                <span class="topic-count">${topic.count}讨论</span>
            `;
            topicItem.addEventListener('click', () => {
                insertTopicText(topic.name);
                closeTopicModal();
            });
            hotSection.appendChild(topicItem);
        });
        topicList.appendChild(hotSection);
    }

    /**
     * 搜索话题
     */
    window.searchTopics = function() {
        const input = document.getElementById('topicSearchInput');
        const keyword = input.value.trim().toLowerCase();
        const topicItems = document.querySelectorAll('.topic-item');

        topicItems.forEach(item => {
            const topicName = item.dataset.topicName.toLowerCase();
            item.style.display = topicName.includes(keyword) ? 'flex' : 'none';
        });
    };

    /**
     * 插入话题文本到发布框
     */
    function insertTopicText(topicName) {
        const textarea = document.getElementById('publishContent');
        if (!textarea) return;

        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const value = textarea.value;

        textarea.value = value.substring(0, start) + `#${topicName}# ` + value.substring(end);
        
        textarea.selectionStart = textarea.selectionEnd = start + topicName.length + 3;
        textarea.focus();

        if (window.updatePublishCharCount) {
            window.updatePublishCharCount();
        }
    }

    /**
     * 关闭话题选择弹窗
     */
    window.closeTopicModal = function() {
        const topicModal = document.getElementById('topicSelectModal');
        if (!topicModal) return;

        topicModal.classList.remove('active');
        setTimeout(() => {
            topicModal.style.display = 'none';
        }, 300);
    };
})();
