document.addEventListener('DOMContentLoaded', function () {
    // To open and close the emoji picker
    const emojiPickers = document.querySelectorAll('.emojiPicker');
    const closeEmojiPicker = document.getElementById('closeEmojiPicker');
    const emojiPickerContainer = document.getElementById('emojiPickerContainer');
    let statusId;

    emojiPickers.forEach(emojiPicker => {
        emojiPicker.addEventListener('click', function () {
            statusId = emojiPicker.dataset.statusId;
            emojiPickerContainer.classList.remove('hidden');
            console.log(statusId);
        });
    });

    closeEmojiPicker.addEventListener('click', function () {
        emojiPickerContainer.classList.add('hidden');
    });
    
    // Handle emoji selection
    const emojis = document.querySelectorAll('.emojisContainer p');
    emojis.forEach(emoji => {
        emoji.addEventListener('click', function () {
            var emojiText = emoji.innerText;
            var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]").value;
            
            if (statusId) {
                fetch('/add/reaction/' + statusId + '/' + emojiText + '/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrftoken
                    },
                    body: JSON.stringify({ emoji: emojiText })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    location.reload();
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            } else {
                console.error('statusId is undefined');
            }
        });
    });
    
    // To navigate between categories
    const categories = document.querySelectorAll('.emoji-category');
    const categoryContainers = document.querySelectorAll('.emoji-category-container');

    categories.forEach(category => {
        category.addEventListener('click', function () {
            const selectedCategory = category.dataset.category;
            toggleCategory(selectedCategory);
            categories.forEach(cat => {
                cat.classList.toggle('selectedEmojiCategory', cat === category);
            });
        });
    });

    function toggleCategory(category) {
        categoryContainers.forEach(container => {
            const containerId = container.getAttribute('id');
            container.classList.toggle('hidden', containerId !== `${category}Container`);
        });
    }
});
