/**
 * 发布弹窗 - 表情选择器模块
 */

(function() {
    'use strict';

    // 表情数据
    var emojiData = {
        default: [],
        hot: [],
        emoji: [
            {name: '😀', code: 'grinning'},
            {name: '😃', code: 'smiley'},
            {name: '😄', code: 'smile'},
            {name: '😁', code: 'grin'},
            {name: '😆', code: 'laughing'},
            {name: '😅', code: 'sweat_smile'},
            {name: '🤣', code: 'rofl'},
            {name: '😂', code: 'joy'},
            {name: '🙂', code: 'slightly_smiling'},
            {name: '🙃', code: 'upside_down'},
            {name: '😉', code: 'wink'},
            {name: '😊', code: 'blush'},
            {name: '😇', code: 'innocent'},
            {name: '🥰', code: 'smiling_face_with_3_hearts'},
            {name: '😍', code: 'heart_eyes'},
            {name: '🤩', code: 'star-struck'},
            {name: '😘', code: 'kissing_heart'},
            {name: '😗', code: 'kissing'},
            {name: '😚', code: 'kissing_closed_eyes'},
            {name: '😙', code: 'kissing_smiling_eyes'},
            {name: '🥲', code: 'smiling_face_with_tear'},
            {name: '😋', code: 'yum'},
            {name: '😛', code: 'stuck_out_tongue'},
            {name: '😜', code: 'stuck_out_tongue_winking_eye'},
            {name: '🤪', code: 'zany_face'},
            {name: '😝', code: 'stuck_out_tongue_closed_eyes'},
            {name: '🤑', code: 'money_mouth_face'},
            {name: '🤗', code: 'hugging_face'},
            {name: '🤭', code: 'face_with_hand_over_mouth'},
            {name: '🤫', code: 'shushing_face'},
            {name: '🤔', code: 'thinking_face'},
            {name: '🤐', code: 'zipper_mouth_face'},
            {name: '🤨', code: 'face_with_raised_eyebrow'},
            {name: '😐', code: 'neutral_face'},
            {name: '😑', code: 'expressionless'},
            {name: '😶', code: 'no_mouth'},
            {name: '😏', code: 'smirk'},
            {name: '😒', code: 'unamused'},
            {name: '🙄', code: 'roll_eyes'},
            {name: '😬', code: 'grimacing'},
            {name: '😮', code: 'open_mouth'},
            {name: '🤯', code: 'exploding_head'},
            {name: '😱', code: 'scream'},
            {name: '😨', code: 'fearful'},
            {name: '😰', code: 'anxious'},
            {name: '😥', code: 'sad_relieved'},
            {name: '😢', code: 'cry'},
            {name: '😭', code: 'sob'},
            {name: '😤', code: 'angry'},
            {name: '😡', code: 'rage'},
            {name: '🤬', code: 'cursing'},
            {name: '👍', code: 'thumbsup'},
            {name: '👎', code: 'thumbsdown'},
            {name: '👏', code: 'clap'},
            {name: '🙌', code: 'raised_hands'},
            {name: '🤝', code: 'handshake'},
            {name: '❤️', code: 'heart'},
            {name: '🧡', code: 'orange_heart'},
            {name: '💛', code: 'yellow_heart'},
            {name: '💚', code: 'green_heart'},
            {name: '💙', code: 'blue_heart'},
            {name: '💜', code: 'purple_heart'},
            {name: '🖤', code: 'black_heart'},
            {name: '🤍', code: 'white_heart'},
            {name: '💔', code: 'broken_heart'},
            {name: '💕', code: 'two_hearts'},
            {name: '💖', code: 'sparkling_heart'},
            {name: '💗', code: 'heartpulse'},
            {name: '💘', code: 'cupid'},
            {name: '💝', code: 'gift_heart'}
        ]
    };

    // 默认表情名称列表
    var defaultEmojiNames = ['微笑', '嘻嘻', '哈哈', '可爱', '可怜', '挤眼', '害羞', '闭嘴', '鄙视', '爱你', '泪', '偷笑', '亲亲', '生病', '太开心', '白眼', '右哼哼', '左哼哼', '嘘', '衰', '吐', '哈欠', '抱抱', '怒', '疑问', '馋嘴', '拜拜', '思考', '汗', '打脸', '惊恐', '失望', '酷', '厉害', '弱', '握手', '胜利', '抱拳', '鼓励', '抠鼻'];

    // 热门表情名称列表
    var hotEmojiNames = ['doge', '二哈', '喵喵', '笑cry', '并不简单', '摊手', '跪了', '费解', '憧憬', '悲伤', '允悲', '赞', 'no', 'ok', 'haha', '哼', '666', 'awsl', '吃瓜', '打call'];

    /**
     * 切换表情选择器（发布弹窗专用）
     */
    window.togglePublishEmojiPicker = function() {
        const emojiPicker = document.getElementById('emojiPicker');
        if (!emojiPicker) {
            console.log('emojiPicker not found');
            return;
        }

        emojiPicker.classList.toggle('active');

        if (emojiPicker.classList.contains('active')) {
            loadEmojis('default');

            document.querySelectorAll('.emoji-picker .emoji-tab').forEach(tab => {
                tab.onclick = function() {
                    const category = this.dataset.category;
                    loadEmojis(category);
                };
            });
        }
    };

    // 加载表情映射
    async function loadEmojiMap() {
        if (emojiData.default.length > 0) return;

        try {
            const baseUrl = window.BASE_URL || window.location.origin;
            const response = await fetch(baseUrl + '/static/emoji/emoji_map.json');
            const emojiMap = await response.json();

            const emojiPath = baseUrl + '/static/emoji/';

            defaultEmojiNames.forEach(function(name) {
                var code = '[' + name + ']';
                if (emojiMap[code]) {
                    emojiData.default.push({
                        name: name,
                        code: code,
                        url: emojiPath + emojiMap[code]
                    });
                }
            });

            hotEmojiNames.forEach(function(name) {
                var code = '[' + name + ']';
                if (emojiMap[code]) {
                    emojiData.hot.push({
                        name: name,
                        code: code,
                        url: emojiPath + emojiMap[code]
                    });
                }
            });
        } catch (error) {
            console.error('Failed to load emoji map:', error);
        }
    }

    function loadEmojis(category) {
        const emojiGrid = document.getElementById('emojiGrid');
        if (!emojiGrid) return;

        emojiGrid.innerHTML = '';

        if (emojiData.default.length === 0) {
            loadEmojiMap().then(function() {
                renderEmojis(category);
            });
        } else {
            renderEmojis(category);
        }
    }

    function renderEmojis(category) {
        const emojiGrid = document.getElementById('emojiGrid');
        if (!emojiGrid) return;

        const emojis = emojiData[category] || [];

        emojiGrid.innerHTML = '';

        emojis.forEach(function(emoji) {
            if (category === 'emoji') {
                var emojiItem = document.createElement('span');
                emojiItem.className = 'emoji-item emoji-text';
                emojiItem.textContent = emoji.name;
                emojiItem.dataset.code = emoji.name;
                emojiItem.title = emoji.name;
                emojiItem.addEventListener('click', function() {
                    insertEmoji(emoji.name);
                });
                emojiGrid.appendChild(emojiItem);
            } else {
                var emojiItem = document.createElement('img');
                emojiItem.className = 'emoji-item emoji-img';
                emojiItem.src = emoji.url;
                emojiItem.alt = emoji.name;
                emojiItem.title = emoji.name;
                emojiItem.dataset.code = emoji.code;
                emojiItem.addEventListener('click', function() {
                    insertEmoji(emoji.code);
                });
                emojiGrid.appendChild(emojiItem);
            }
        });

        document.querySelectorAll('.emoji-picker .emoji-tab').forEach(tab => {
            tab.classList.toggle('active', tab.dataset.category === category);
        });
    }

    /**
     * 插入表情到发布框
     */
    function insertEmoji(emoji) {
        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) + emoji + value.substring(end);

        textarea.selectionStart = textarea.selectionEnd = start + emoji.length;
        textarea.focus();

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

    // 暴露表情数据供其他模块使用
    window.publishEmojiData = emojiData;
})();
