/**
 * 发布弹窗 - @用户选择模块
 */

(function() {
    'use strict';

    /**
     * 打开@用户弹窗
     */
    window.insertAt = function() {
        const atModal = document.getElementById('atUserModal');
        if (!atModal) {
            createAtModal();
        }
        loadAtUsers();
        atModal.style.display = 'flex';
        setTimeout(() => {
            atModal.classList.add('active');
        }, 10);
    };

    /**
     * 创建@用户选择弹窗
     */
    function createAtModal() {
        const modal = document.createElement('div');
        modal.className = 'modal-overlay at-user-modal';
        modal.id = 'atUserModal';
        modal.style.display = 'none';
        modal.innerHTML = `
            <div class="modal-container at-user-container">
                <div class="modal-header">
                    <button class="modal-close" onclick="closeAtModal()">×</button>
                    <h3 class="modal-title">选择用户</h3>
                    <div style="width: 32px;"></div>
                </div>
                <div class="at-search">
                    <input type="text" id="atSearchInput" placeholder="搜索用户..." oninput="searchAtUsers()">
                </div>
                <div class="at-list-container" id="atList">
                    <div class="at-section">
                        <div class="at-section-title">最近联系人</div>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }

    /**
     * 加载@用户列表
     */
    async function loadAtUsers() {
        const atList = document.getElementById('atList');
        if (!atList) return;

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

            atList.innerHTML = '';

            if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
                const section = document.createElement('div');
                section.className = 'at-section';
                section.innerHTML = '<div class="at-section-title">好友列表</div>';

                result.data.items.forEach(user => {
                    const userItem = document.createElement('div');
                    userItem.className = 'at-item';
                    userItem.dataset.userId = user.id;
                    userItem.dataset.username = user.username;
                    userItem.innerHTML = `
                        <img src="${user.avatar || '/templates/mobile/images/avatar_default.png'}" class="at-avatar" alt="">
                        <span class="at-username">${user.username}</span>
                    `;
                    userItem.addEventListener('click', () => {
                        insertAtUser(user.username);
                        closeAtModal();
                    });
                    section.appendChild(userItem);
                });
                atList.appendChild(section);
            } else {
                // 好友列表为空，显示提示
                const emptyTip = document.createElement('div');
                emptyTip.className = 'at-empty-tip';
                emptyTip.innerHTML = `
                    <div style="text-align: center; padding: 30px 20px; color: var(--text-secondary-color);">
                        <div style="font-size: 14px;">您还没有关注任何人</div>
                        <div style="font-size: 12px; margin-top: 8px; color: var(--text-tertiary-color);">去关注一些用户，然后在这里@他们</div>
                    </div>
                `;
                atList.appendChild(emptyTip);
            }
        } catch (error) {
            console.error('Load users error:', error);
            // 网络错误，显示提示
            const atList = document.getElementById('atList');
            if (atList) {
                atList.innerHTML = `
                    <div style="text-align: center; padding: 30px 20px; color: var(--text-secondary-color);">
                        <div style="font-size: 14px;">加载失败</div>
                        <div style="font-size: 12px; margin-top: 8px; color: var(--text-tertiary-color);">请检查网络后重试</div>
                    </div>
                `;
            }
        }
    }

    /**
     * 搜索用户
     */
    window.searchAtUsers = function() {
        const input = document.getElementById('atSearchInput');
        if (!input) return;
        const keyword = input.value.trim().toLowerCase();
        const userItems = document.querySelectorAll('.at-item');

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

    /**
     * 插入@用户到发布框
     */
    window.insertAtUser = function(username) {
        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) + `@${username} ` + value.substring(end);
        
        textarea.selectionStart = textarea.selectionEnd = start + username.length + 2;
        textarea.focus();

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

    /**
     * 关闭@用户弹窗
     */
    window.closeAtModal = function() {
        const atModal = document.getElementById('atUserModal');
        if (!atModal) return;

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