// feeds.js - Parte 1: Sistema Masonry e Funções Principais

// Sistema Masonry para layout Pinterest
class MasonryLayout {
    constructor(container, options = {}) {
        this.container = container;
        this.items = [];
        this.columns = options.columns || 10;
        this.gap = options.gap || 20;
        this.resizeTimer = null;
        this.isProcessing = false;
        this.queue = [];
        this.columnHeights = [];
        
        this.init();
    }
    
    init() {
        this.updateColumns();
        this.bindEvents();
        this.resetColumnHeights();
    }
    
    bindEvents() {
        window.addEventListener('resize', () => {
            clearTimeout(this.resizeTimer);
            this.resizeTimer = setTimeout(() => {
                this.updateColumns();
                this.relayout();
            }, 250);
        });
    }
    
    updateColumns() {
        const width = window.innerWidth;
        
        if (width <= 500) this.columns = 1;
        else if (width <= 800) this.columns = 2;
        else if (width <= 1100) this.columns = 3;
        else if (width <= 1400) this.columns = 4;
        else if (width <= 1600) this.columns = 5;
        else if (width <= 1800) this.columns = 6;
        else if (width <= 2000) this.columns = 7;
        else if (width <= 2200) this.columns = 8;
        else if (width <= 2400) this.columns = 9;
        else this.columns = 10;
        
        this.resetColumnHeights();
    }
    
    resetColumnHeights() {
        this.columnHeights = new Array(this.columns).fill(0);
    }
    
    async addItem(element) {
        // Se for mobile (1 coluna), não usa posicionamento absoluto
        if (this.columns === 1) {
            element.style.position = 'relative';
            element.style.width = '100%';
            element.style.left = 'auto';
            element.style.top = 'auto';
            element.classList.add('show');
            return;
        }
        
        // Aguarda imagens carregarem
        await this.waitForImages(element);
        
        // Encontra a coluna mais curta
        let shortestColumn = 0;
        let minHeight = this.columnHeights[0];
        
        for (let i = 1; i < this.columns; i++) {
            if (this.columnHeights[i] < minHeight) {
                minHeight = this.columnHeights[i];
                shortestColumn = i;
            }
        }
        
        // Calcula largura do item
        const containerWidth = this.container.offsetWidth;
        const itemWidth = (containerWidth - (this.columns - 1) * this.gap) / this.columns;
        
        // Define posição
        element.style.position = 'absolute';
        element.style.left = (shortestColumn * (itemWidth + this.gap)) + 'px';
        element.style.top = this.columnHeights[shortestColumn] + 'px';
        element.style.width = itemWidth + 'px';
        
        // Atualiza altura da coluna
        this.columnHeights[shortestColumn] += element.offsetHeight + this.gap;
        
        // Atualiza altura do container
        const maxHeight = Math.max(...this.columnHeights);
        this.container.style.height = maxHeight + 'px';
        
        // Anima entrada
        setTimeout(() => {
            element.classList.add('show');
        }, 50);
        
        // Marca container como carregado
        this.container.classList.add('loaded');
    }
    
    async waitForImages(element) {
        const images = element.querySelectorAll('img');
        const promises = [];
        
        images.forEach(img => {
            if (!img.complete) {
                promises.push(new Promise(resolve => {
                    img.onload = resolve;
                    img.onerror = resolve;
                    // Timeout de segurança
                    setTimeout(resolve, 3000);
                }));
            }
        });
        
        if (promises.length > 0) {
            await Promise.all(promises);
        }
    }
    
    async relayout() {
        this.resetColumnHeights();
        const elements = this.container.querySelectorAll('.result');
        
        for (let element of elements) {
            element.classList.remove('show');
            await this.addItem(element);
        }
    }
}

// Variável global para o Masonry
let masonry = null;

// Variáveis globais
var feeds = feeds || {};
var loading = loading || false;
var page = page || 1;
var loadThreshold = loadThreshold || 2000;
var displayedFeeds = displayedFeeds || {};

// Função para exibir apenas feeds com imagem
function displayFeedsOnlyWithImage() {
    console.log('Exibindo feeds com imagem...');
    var container = $('#feeds');
    var filteredFeeds = [];

    $.each(feeds, function(key, feed) {
        var image = feed.image || '';
        var thumbnail = feed.thumbnail || '';

        if (image || thumbnail) {
            // Verifique se o feed já foi exibido
            if (!displayedFeeds[feed.link]) {
                displayedFeeds[feed.link] = true;
                filteredFeeds.push(feed);
            }
        }
    });

    console.log('Feeds filtrados:', filteredFeeds.length);
    displayFeedsToContainer(filteredFeeds, container);
}

// Função principal para exibir feeds
function displayFeeds() {
    console.log('Exibindo feeds...');
    var searchQuery = $('#search-query').val().toLowerCase();
    var filteredFeeds = [];

    if (searchQuery.startsWith("author:")) {
        var authorName = searchQuery.replace("author:", "").trim();
        filteredFeeds = $.map(feeds, function(feed, key) {
            if ((feed.author || '').toLowerCase().includes(authorName)) {
                return feed;
            }
        });
    } else if (searchQuery.startsWith("source:")) {
        var sourceDomain = searchQuery.replace("source:", "").trim();
        filteredFeeds = $.map(feeds, function(feed, key) {
            if (extractBaseDomainFromUrl(feed.link) === sourceDomain) {
                return feed;
            }
        });
    } else {
        var searchWords = searchQuery.split(/\s+/);
        $.each(feeds, function(key, feed) {
            var title = (feed.title || '').toLowerCase();
            var description = (feed.description || '').toLowerCase();
            var hasMatchingWord = searchWords.some(searchWord => 
                title.includes(searchWord) || description.includes(searchWord)
            );
            if (hasMatchingWord) {
                filteredFeeds.push(feed);
            }
        });
    }

    console.log('Feeds filtrados:', filteredFeeds.length);
    displayFeedsToContainer(filteredFeeds, $('#feeds'));
}

// Função para exibir feeds no container
function displayFeedsToContainer(feedsArr, container) {
    console.log('Exibindo', feedsArr.length, 'feeds no container');
    
    // Inicializa Masonry na primeira vez OU reseta se for página 1
    if (!masonry && container[0]) {
        console.log('Inicializando Masonry...');
        masonry = new MasonryLayout(container[0], {
            columns: 10,
            gap: 20
        });
    } else if (masonry && page === 1) {
        // Reset completo do Masonry para novas buscas
        console.log('Resetando Masonry para nova busca...');
        masonry.columnHeights = [];
        masonry.resetColumnHeights();
        masonry.container.style.height = '0px';
        
        // Remove todos os estilos dos elementos existentes
        container.find('.result').each(function() {
            $(this).removeAttr('style');
        });
    }
    
    // Se for página 1, limpa o container completamente
    if (page === 1) {
        container.empty();
        displayedFeeds = {};
    }
    
    // Ordena os feeds pela data de publicação, mais recentes primeiro
    feedsArr.sort(function(a, b) {
        var dateA = new Date(a.pubDate);
        var dateB = new Date(b.pubDate);
        return dateA < dateB ? 1 : -1;
    });

    // Array para armazenar os elementos a adicionar
    let itemsToAdd = [];

    // Itera sobre cada feed para montar o HTML correspondente
    $.each(feedsArr, function(index, feed) {
        // Verifica se o feed já foi exibido
        if (displayedFeeds[feed.link]) {
            return true; // Continue para o próximo
        }
        displayedFeeds[feed.link] = true;
        
        var itemHtml = createFeedHTML(feed);
        var itemElement = $(itemHtml);
        container.append(itemElement);
        itemsToAdd.push(itemElement[0]);
        
        // Vincula eventos ao elemento
        bindFeedEvents(itemElement, feed);
    });
    
    // Adiciona todos os items ao Masonry com delay
    itemsToAdd.forEach((item, index) => {
        setTimeout(() => {
            if (masonry) {
                masonry.addItem(item);
            }
        }, index * 30); // 30ms de delay entre cada item
    });
    
    // Reprocessa embeds sociais após um delay
    setTimeout(() => {
        if (typeof FB !== 'undefined') {
            FB.XFBML.parse();
        }
        if (typeof twttr !== 'undefined') {
            twttr.widgets.load();
        }
    }, 1000);
}

// Função para criar o HTML de um feed
function createFeedHTML(feed) {
    var thumbnail = feed.thumbnail || '';
    var author = feed.author || 'Anonymous';
    var sourceName = feed.sourceName || extractDomainFromUrl(feed.link) || 'Unknown';
    var sourceLogo = feed.sourceLogo;
    
    var sourceDomain = extractBaseDomainFromUrl(feed.link);
    var truncatedSourceName = truncateText(sourceName, 20);
    
    // Exibe o logo da fonte se disponível
    var sourceHtml = sourceLogo ? 
        `<img src="${sourceLogo}" alt="${sourceName}" class="source-logo"> 
         <a href="#" class="source-search-link" data-source-domain="${sourceDomain}">${truncatedSourceName}</a>` 
        : `<a href="#" class="source-search-link" data-source-domain="${sourceDomain}">${truncatedSourceName}</a>`;
    
    var title = feed.title || 'Untitled';
    var description = feed.description || '';
    var pubDate = feed.pubDate || '';
    var truncatedTitle = truncateText(title, 80);
    var truncatedDescription = truncateText(description, 80);
    var thumbnailHtml = '';
    
    // Verifica o domínio para gerar o embed apropriado
    if (sourceDomain.includes('twitter.com') || sourceDomain.includes('x.com')) {
        thumbnailHtml = generateTwitterEmbed(feed.link);
    } else if (sourceDomain.includes('reddit.com')) {
        thumbnailHtml = generateRedditEmbed(feed.link);
    } else if (sourceDomain.includes('facebook.com')) {
        thumbnailHtml = generateFacebookEmbed(feed.link);
    } else if (sourceDomain.includes('youtube.com')) {
        thumbnailHtml = generateYouTubeThumbnailEmbed(feed.link);
    } else if (sourceDomain.includes('instagram.com')) {
        thumbnailHtml = generateInstagramEmbed(feed.link);
    } else {
        thumbnailHtml = thumbnail ? 
            `<a href="pindetails.php?id=${feed.id}" target="_blank" rel="noopener noreferrer">
             <img src="${thumbnail}" alt="Thumbnail" class="feed-thumbnail"></a>` : '';
    }
    
    var faviconLink = feed.link ? getFaviconUrl(feed.link) : '';
    var shareButtonHtml = createShareButton(feed);
    var tagsHtml = createTagsHTML(title);
    
    var isSaved = feed.isSaved;
    var saveButtonHtml = `<button class="save-btn ${isSaved ? 'saved' : ''}" data-feed-id="${feed.id}">
                            <i class="fas fa-bookmark"></i>
                          </button>`;
    
    var isFollowingAuthor = feed.isFollowingAuthor;
    var followAuthorButtonText = isFollowingAuthor ? 'Unfollow' : 'Follow';
    var followAuthorButtonColor = isFollowingAuthor ? '#28a745' : '#FFC107';
    
    var followAuthorButtonHtml = `<button class="follow-btn" data-follow-type="author" data-follow-value="${author}" 
                                  style="margin-left: 5px; padding: 5px 10px; border-radius: 5px; 
                                  background-color: ${followAuthorButtonColor}; 
                                  color: ${followAuthorButtonColor === '#FFC107' ? 'black' : 'white'}; 
                                  font-family: 'Roboto', sans-serif; font-size: 14px; font-weight: 700; 
                                  border: none; cursor: pointer;">
                                  ${followAuthorButtonText}
                                  </button>`;
    
    var followSourceButtonHtml = `<button class="follow-btn" data-follow-type="source_domain" data-follow-value="${sourceDomain}">
                                    <i class="fas fa-plus"></i>
                                  </button>`;
    
    var commentsCount = feed.comments_count || 0;
    var commentIconColor = feed.user_has_commented ? '#007bff' : '#cccccc';
    
    var authorAvatar = thumbnail ? 
        `<img src="${thumbnail}" alt="Avatar" class="author-avatar" 
         style="width: 40px; height: 40px; margin-right: 10px; border: 2px solid black; 
         border-radius: 40px; vertical-align: middle;">` : '';
    
    // Continua na Parte 2...
    // feeds.js - Parte 2: Continuação do createFeedHTML e Funções de Suporte

    // Continuação da função createFeedHTML...
    var commentsHtml = createCommentsHTML(feed);
    
    // Montando o HTML final do feed
    var itemHtml = `
    <div class="result" data-feed-id="${feed.id}">
        <div class="result-header" style="display: flex; align-items: center; margin-bottom: 10px;">
            ${authorAvatar}<a href="#" class="author-search-link" data-author="${author}" style="vertical-align: middle;">@${author}</a> ${followAuthorButtonHtml}
        </div>
        ${thumbnailHtml}
        <a href="pindetails.php?id=${feed.id}" target="_blank" rel="noopener noreferrer"><h2>${truncatedTitle}</h2></a>
        <p>${truncatedDescription}</p>
        <p>Channel: ${sourceHtml} ${followSourceButtonHtml}</p>
        <p>${pubDate}</p>
        ${tagsHtml}
        <div class="favicon-and-site">
            <a href="${feed.link}" target="_blank">
                <img src="${faviconLink}" alt="Favicon" style="width: 20px; height: 20px;" />
                <span class="source-name">${truncatedSourceName}</span>
            </a>
        </div>
        <!-- Like, dislike, comentários e salvar botões -->
        <div class="like-dislike-container">
            <button class="like-btn ${feed.user_action === 'like' ? 'liked' : ''}" data-feed-id="${feed.id}">
                <i class="fas fa-thumbs-up"></i> <span class="like-count">${feed.likes || 0}</span>
            </button>
            <button class="dislike-btn ${feed.user_action === 'dislike' ? 'disliked' : ''}" data-feed-id="${feed.id}">
                <i class="fas fa-thumbs-down"></i> <span class="dislike-count">${feed.dislikes || 0}</span>
            </button>
            <i id="comment-icon-${feed.id}" class="fas fa-comments" style="font-size: 15px; color: ${commentIconColor}; margin-right: 5px; cursor: pointer;"></i>
            <span id="comments-count-${feed.id}" style="font-size: 15px;">${commentsCount}</span>
            ${saveButtonHtml}
        </div>
        ${commentsHtml}
        <!-- Seção de compartilhamento -->
        <div class="share-buttons-container" style="margin-top: 5px;">
            ${shareButtonHtml}
        </div>
    </div>`;
    
    return itemHtml;
}

// Função para criar HTML dos comentários
function createCommentsHTML(feed) {
    var commentsCount = feed.comments_count || 0;
    var commentIconColor = feed.user_has_commented ? '#007bff' : '#cccccc';
    
    var commentsListHTML = '';
    if (feed.comments && feed.comments.length > 0) {
        commentsListHTML = feed.comments.map(comment => `
            <div class="comment" id="comment-${comment.comment_id}" style="display: flex; align-items: flex-start; margin-bottom: 10px; font-size: 14px; max-width: 98%;">
                <img src="${comment.author_thumbnail || 'default-avatar.png'}" alt="@${comment.author}" 
                     class="comment-avatar" style="width: 25px; height: 25px; border-radius: 50%; margin-right: 10px; border: 1px solid #cccccc;">
                <div style="flex-grow: 1;">
                    <a href="https://digupdog.com/author.html?name=${comment.author}" target="_blank" style="color: #007bff; text-decoration: none;">
                        @${comment.author}
                    </a>
                    <p style="margin: 5px 0; line-height: 1.5; font-size: 12px; color: #E0E0E0; background-color: #2c3e50; padding: 8px; border-radius: 4px; max-width: 90%; overflow-wrap: break-word; word-break: break-all;">
                        ${formatCommentText(comment.comment_text)}
                    </p>
                    ${comment.thumbnail ? `<img src="${comment.thumbnail}" alt="Thumbnail" style="width: 97%; height: auto; margin-top: 5px; border: 2px solid #cccccc; border-radius: 4px;" />` : ''}
                    ${comment.link_preview ? `
                        <div class="preview-container" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; background-color: #f9f9f9; max-width: 98%;">
                            <h5 style="margin: 0; font-size: 13px; color: #333; word-break: break-all; overflow-wrap: anywhere; hyphens: auto;">
                                ${comment.title || 'No Title'}
                            </h5>
                            <p style="margin: 5px 0; font-size: 12px; color: #666; word-break: break-all; overflow-wrap: anywhere; hyphens: auto;">
                                ${comment.description || 'No description available.'}
                            </p>
                            ${getEmbedHtml(comment.link_preview)}
                        </div>
                    ` : ''}
                    <!-- Botão de Reply com ícone -->
                    <button class="reply-btn" data-author="${comment.author}" data-comment-id="${comment.comment_id}" data-feed-id="${feed.id}" 
                            style="background-color: transparent; border: none; cursor: pointer; color: #007bff;">
                        <i class="fas fa-reply" style="font-size: 16px; color: #007bff;"></i>
                    </button>
                </div>
            </div>
        `).join('');
    }
    
    return `
        <!-- Exibindo a seção de comentários, inicialmente escondida -->
        <div class="comment-section" id="comments-${feed.id}" style="display: none; width: 98%; height: 300px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; margin-top: 10px;">
            <div style="margin-bottom: 10px; display: flex; align-items: center; width: 98%;">
                <input type="text" id="search-comments-${feed.id}" placeholder="Search comments..." 
                       style="width: calc(100% - 30px); padding: 8px; border-radius: 5px; 
                              background-color: #2c3e50; color: #fff; border: 1px solid #ccc; 
                              margin-right: 10px;">
            </div>
            <textarea id="new-comment-${feed.id}" placeholder="Add a comment..." style="width: 93%; height: auto; min-height: 60px; margin-bottom: 10px; border-radius: 5px; padding: 10px; border: 1px solid #2c3e50; font-size: 16px; background-color: #34495e; color: #cccccc;"></textarea>
            
            <!-- Contêiner para pré-visualização -->
            <div class="preview-container" style="margin-bottom: 10px;"></div>
            
            <!-- Botões de emoji e envio abaixo do campo de comentário -->
            <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 5px;">
                <!-- Botão de emoji à esquerda -->
                <button type="button" onclick="toggleEmojiList(${feed.id})" 
                        style="cursor: pointer; font-size: 20px; background: none; border: none; padding: 5px;">
                    😊
                </button>

                <!-- Botão de envio à direita -->
                <button class="post-comment-btn" data-feed-id="${feed.id}" title="Post Comment" 
                        style="cursor: pointer; background: none; border: none; padding: 5px;">
                    <i class="fas fa-paper-plane" style="color: #007bff; font-size: 20px;"></i>
                </button>
            </div>

            <!-- Importando a lista de emojis separadamente -->
            ${getEmojiListHtml(feed.id)}
            <h4>Comments:</h4>
            ${commentsListHTML}
        </div>`;
}

// Função para criar HTML das tags
function createTagsHTML(title) {
    var tags = extractTagsFromTitle(title);
    var tagsHtml = '';
    
    if (tags.length > 0) {
        tagsHtml = '<p>Tags: ';
        tags.forEach((tag, i) => {
            tag = truncateText(tag, 30);
            let bgColor = stringToColor(tag);
            let textColor = isColorDark(bgColor) ? 'white' : 'black';

            tagsHtml += (i > 0 ? ', ' : '') + `
                <a href="#" class="tag-search-link" data-tag="${tag}" 
                   style="background-color: ${bgColor}; color: ${textColor}; 
                          padding: 2px 8px; margin-top: 5px; margin-bottom: 5px; 
                          display: inline-block; border-radius: 5px; font-size: 15px;">
                   #${tag}
                </a>
                <button class="follow-btn" data-follow-type="tag" data-follow-value="${tag}">
                    <i class="fas fa-plus"></i>
                </button>`;
        });
        tagsHtml += '</p>';
    }
    
    return tagsHtml;
}

// Função para vincular eventos a um elemento de feed
function bindFeedEvents(itemElement, feed) {
    // Evento para exibir/ocultar os comentários
    itemElement.find('#comment-icon-' + feed.id).on('click', function() {
        var commentSection = itemElement.find('#comments-' + feed.id);
        commentSection.slideToggle(300);
    });

    // Listener para o botão de postar comentário
    itemElement.find('.post-comment-btn').on('click', function() {
        postComment(feed.id);
    });

    // Listener para o campo de busca de comentários
    itemElement.find('#search-comments-' + feed.id).on('input', function() {
        var searchTerm = $(this).val();
        filterComments(feed.id, searchTerm);
    });

    // Carrega o estado de follow para cada botão
    itemElement.find('.follow-btn').each(function() {
        var followType = $(this).data('follow-type');
        var followValue = $(this).data('follow-value');
        var buttonElement = $(this);
        loadFollowStatus(followType, followValue, buttonElement);
    });
    
    // Evento para like
    itemElement.find('.like-btn').on('click', function() {
        handleLikeDislike(feed.id, 'like');
    });
    
    // Evento para dislike
    itemElement.find('.dislike-btn').on('click', function() {
        handleLikeDislike(feed.id, 'dislike');
    });
    
    // Evento para salvar
    itemElement.find('.save-btn').on('click', function() {
        toggleSave(feed.id);
    });
    
    // Evento para follow/unfollow
    itemElement.find('.follow-btn').on('click', function() {
        var followType = $(this).data('follow-type');
        var followValue = $(this).data('follow-value');
        var action = $(this).data('action') || 'follow';
        toggleFollow(followType, followValue, action, $(this));
    });
    
    // Listener para o campo de comentário (pré-visualização de links)
    itemElement.find('textarea[id^="new-comment-"]').on('input', function() {
        const commentText = $(this).val();
        const urlMatch = commentText.match(/(?:https?:\/\/|www\.)[^\s/$.?#].[^\s]*/g);
        const previewContainer = $(this).closest('.comment-section').find('.preview-container');
        
        if (urlMatch && urlMatch.length > 0) {
            previewLink(urlMatch[0], previewContainer);
        } else {
            previewContainer.html('');
        }
    });
}

// Função para manipular like/dislike
function handleLikeDislike(feedId, action) {
    $.ajax({
        url: 'like_dislike.php',
        type: 'POST',
        data: {
            feed_id: feedId,
            action: action
        },
        success: function(response) {
            if (response.success) {
                updateLikeDislikeUI(feedId, response);
                
                // Mostra emoji animado
                if (action === 'like') {
                    showAnimatedEmoji('👍', '#like-emoji');
                } else {
                    showAnimatedEmoji('👎', '#dislike-emoji');
                }
            }
        },
        error: function() {
            console.error('Erro ao processar like/dislike');
        }
    });
}

// Função para atualizar UI de like/dislike
function updateLikeDislikeUI(feedId, data) {
    var likeBtn = $(`.like-btn[data-feed-id="${feedId}"]`);
    var dislikeBtn = $(`.dislike-btn[data-feed-id="${feedId}"]`);
    
    // Atualiza contadores
    likeBtn.find('.like-count').text(data.likes);
    dislikeBtn.find('.dislike-count').text(data.dislikes);
    
    // Atualiza estados
    likeBtn.toggleClass('liked', data.user_action === 'like');
    dislikeBtn.toggleClass('disliked', data.user_action === 'dislike');
}

// Função para mostrar emoji animado
function showAnimatedEmoji(emoji, selector) {
    var emojiElement = $(selector);
    if (emojiElement.length === 0) {
        emojiElement = $(`<div id="${selector.substring(1)}" style="font-size: 100px;">${emoji}</div>`);
        $('body').append(emojiElement);
    }
    
    emojiElement.text(emoji);
    emojiElement.addClass('show');
    
    setTimeout(function() {
        emojiElement.removeClass('show');
    }, 1000);
}

// Continua na Parte 3...
// feeds.js - Parte 3: Funções de Comentários, Follow, Embeds e Scroll

// Função para postar comentário
function postComment(feedId) {
    var commentText = $('#new-comment-' + feedId).val();
    if (commentText.trim() === "") {
        alert("O comentário não pode estar vazio.");
        return;
    }

    var postButton = $('.post-comment-btn[data-feed-id="' + feedId + '"]');
    postButton.prop('disabled', true);

    // Encontrar o primeiro link no comentário
    const urlMatch = commentText.match(/(?:https?:\/\/|www\.)[^\s/$.?#].[^\s]*/g);
    let linkPreview = '';
    let thumbnail = '';
    let title = '';
    let description = '';

    if (urlMatch && urlMatch.length > 0) {
        linkPreview = urlMatch[0];

        $.ajax({
            url: 'fetch_metadata.php',
            type: 'POST',
            data: { url: linkPreview },
            success: function(metadataResponse) {
                try {
                    const metadata = JSON.parse(metadataResponse);
                    if (metadata.success) {
                        title = metadata.title;
                        description = metadata.description;
                        thumbnail = metadata.image;
                    }
                } catch (e) {
                    console.error('Erro ao processar os metadados do link:', e);
                }
                sendComment(feedId, commentText, linkPreview, title, description, thumbnail);
            },
            error: function() {
                sendComment(feedId, commentText, '', '', '', '');
            }
        });
    } else {
        sendComment(feedId, commentText, '', '', '', '');
    }
}

// Função para enviar os dados do comentário
function sendComment(feedId, commentText, linkPreview, title, description, thumbnail) {
    $.ajax({
        url: 'post_comment.php',
        type: 'POST',
        data: {
            feed_id: feedId,
            comment_text: commentText,
            link_preview: linkPreview,
            title: title,
            description: description,
            thumbnail: thumbnail
        },
        success: function(response) {
            try {
                response = JSON.parse(response);
                if (response.success) {
                    // Adiciona o comentário na interface
                    var newCommentHtml = `
                        <div class="comment" style="display: flex; align-items: flex-start; margin-bottom: 10px; font-size: 14px;">
                            <img src="default-avatar.png" alt="Anonymous" 
                                 class="comment-avatar" style="width: 25px; height: 25px; border-radius: 50%; margin-right: 10px; border: 1px solid #cccccc;">
                            <div style="flex-grow: 1;">
                                <a href="#" class="author-search-link" data-author="Anonymous" style="color: #007bff; text-decoration: none;">
                                    @Anonymous
                                </a>
                                <p style="margin: 5px 0; line-height: 1.5; font-size: 12px; color: #E0E0E0; background-color: #2c3e50; padding: 8px; border-radius: 4px;">
                                    ${convertLinks(commentText)}
                                </p>
                                ${thumbnail ? `<img src="${thumbnail}" alt="Thumbnail" style="width: 100px; height: auto; margin-top: 5px;" />` : ''}
                                ${title ? `<h4>${title}</h4>` : ''}
                                ${description ? `<p>${description}</p>` : ''}
                            </div>
                        </div>`;
                    
                    $('#comments-' + feedId).append(newCommentHtml);
                    $('#new-comment-' + feedId).val('');
                    
                    // Atualiza contador de comentários
                    var countElement = $('#comments-count-' + feedId);
                    var currentCount = parseInt(countElement.text()) || 0;
                    countElement.text(currentCount + 1);
                    
                    // Muda cor do ícone de comentário
                    $('#comment-icon-' + feedId).css('color', '#007bff');
                } else {
                    alert(response.message || 'Erro ao postar comentário');
                }
            } catch (e) {
                alert('Erro ao processar a resposta do servidor.');
            }
        },
        error: function() {
            alert('Falha ao postar o comentário.');
        },
        complete: function() {
            $('.post-comment-btn[data-feed-id="' + feedId + '"]').prop('disabled', false);
        }
    });
}

// Função para converter links em texto
function convertLinks(text) {
    const urlRegex = /(?:https?:\/\/|www\.)[^\s/$.?#].[^\s]*/g;
    const mentionRegex = /@(\w+)/g;

    text = text.replace(urlRegex, function(url) {
        const link = url.startsWith('http') ? url : 'http://' + url;
        return `<a href="${link}" target="_blank" style="color: #007bff; text-decoration: underline;">${url}</a>`;
    });

    text = text.replace(mentionRegex, function(mention) {
        return `<span style="color: #007bff; font-weight: bold;">${mention}</span>`;
    });

    return text;
}

// Função para filtrar comentários
function filterComments(feedId, searchTerm) {
    var comments = $(`#comments-${feedId} .comment`);
    searchTerm = searchTerm.toLowerCase();

    comments.each(function() {
        var commentText = $(this).text().toLowerCase();
        if (commentText.includes(searchTerm)) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}

// Função para formatar texto de comentário com reply
function formatCommentText(commentText) {
    return commentText.replace(/@(\w+)\sReply\sC-Id:\s(\d+):/g, (match, author, commentId) => {
        return `Reply <a href="https://digupdog.com/author.html?name=${author}" target="_blank">@${author}</a>, <a href="#comment-${commentId}" class="comment-link" data-comment-id="${commentId}">C-Id: ${commentId}</a>:`;
    });
}

// Função para responder comentário
function replyToComment(author, commentId, feedId) {
    const replyText = `@${author} Reply C-Id: ${commentId}: `;
    const textarea = $('#new-comment-' + feedId);
    
    textarea.val(replyText).focus();
    
    textarea.on('input', function() {
        if (!textarea.val().startsWith(replyText)) {
            textarea.val(replyText + textarea.val().slice(replyText.length));
        }
    });
}

// Função para toggle save
function toggleSave(feedId) {
    var saveBtn = $(`.save-btn[data-feed-id="${feedId}"]`);
    var isSaved = saveBtn.hasClass('saved');
    
    $.ajax({
        url: 'toggle_save.php',
        type: 'POST',
        data: {
            feed_id: feedId,
            action: isSaved ? 'unsave' : 'save'
        },
        success: function(response) {
            if (response.success) {
                saveBtn.toggleClass('saved');
                
                if (!isSaved) {
                    showCustomNotification('Feed salvo com sucesso!');
                }
            }
        },
        error: function() {
            alert('Erro ao salvar/remover feed');
        }
    });
}

// Função para toggle follow
function toggleFollow(followType, followValue, action, buttonElement) {
    $.ajax({
        url: 'follow.php',
        type: 'POST',
        data: {
            follow_type: followType,
            follow_value: followValue,
            action: action
        },
        success: function(response) {
            if (response.success) {
                if (action === 'follow') {
                    buttonElement.data('action', 'unfollow');
                    
                    if (followType === 'author') {
                        buttonElement.html('Unfollow').css({
                            'background-color': '#28a745',
                            'color': 'white'
                        });
                    } else {
                        buttonElement.html('<i class="fas fa-check"></i>');
                    }
                    
                    showFollowPopup(followType, followValue, true);
                } else {
                    buttonElement.data('action', 'follow');
                    
                    if (followType === 'author') {
                        buttonElement.html('Follow').css({
                            'background-color': '#FFC107',
                            'color': 'black'
                        });
                    } else {
                        buttonElement.html('<i class="fas fa-plus"></i>');
                    }
                    
                    showFollowPopup(followType, followValue, false);
                }
            }
        },
        error: function() {
            alert('Erro ao seguir/deixar de seguir');
        }
    });
}

// Função para carregar status de follow
function loadFollowStatus(followType, followValue, buttonElement) {
    $.get('follow.php', { 
        follow_type: followType, 
        follow_value: followValue 
    }, function(response) {
        if (response.status === 'following') {
            buttonElement.addClass('following').removeClass('not-following');
            
            if (followType === 'author') {
                buttonElement.html('Unfollow').css({
                    'background-color': '#28a745',
                    'color': 'white',
                    'font-family': 'Roboto, sans-serif',
                    'font-weight': '700',
                    'border-radius': '5px',
                    'padding': '5px 10px',
                    'border': 'none',
                    'cursor': 'pointer'
                });
            } else {
                buttonElement.html('<i class="fas fa-check"></i>');
            }
            
            buttonElement.data('action', 'unfollow');
        } else {
            buttonElement.addClass('not-following').removeClass('following');
            
            if (followType === 'author') {
                buttonElement.html('Follow').css({
                    'background-color': '#FFC107',
                    'color': 'black',
                    'font-family': 'Roboto, sans-serif',
                    'font-weight': '700',
                    'border-radius': '5px',
                    'padding': '5px 10px',
                    'border': 'none',
                    'cursor': 'pointer'
                });
            } else {
                buttonElement.html('<i class="fas fa-plus"></i>');
            }
            
            buttonElement.data('action', 'follow');
        }

        buttonElement.addClass('visible');
    }, 'json').fail(function() {
        console.log('Erro ao carregar o status de follow');
    });
}

// Função para mostrar popup de follow
function showFollowPopup(type, value, isFollowing) {
    var message = isFollowing ? 
        `Você está seguindo ${type}: ${value}` : 
        `Você deixou de seguir ${type}: ${value}`;
    
    var popup = $('#follow-popup');
    if (popup.length === 0) {
        popup = $('<div id="follow-popup"></div>');
        $('body').append(popup);
    }
    
    popup.html(`
        <span class="icon">${isFollowing ? '✅' : '❌'}</span>
        <span class="highlight">${message}</span>
    `);
    
    popup.addClass('show');
    
    setTimeout(function() {
        popup.removeClass('show').addClass('hide');
        setTimeout(function() {
            popup.removeClass('hide');
        }, 300);
    }, 2000);
}

// Funções de embed para diferentes plataformas
function generateTwitterEmbed(url) {
    const tweetId = extractTweetId(url);
    if (tweetId) {
        return `<blockquote class="twitter-tweet"><a href="https://twitter.com/x/status/${tweetId}"></a></blockquote>
                <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>`;
    }
    return '';
}

function extractTweetId(url) {
    const match = url.match(/(?:twitter\.com|x\.com)\/.*\/status\/(\d+)/);
    return match ? match[1] : null;
}

function generateRedditEmbed(url) {
    return `<blockquote class="reddit-card"><a href="${url}">Link do Post do Reddit</a></blockquote>
            <script async src="https://www.redditstatic.com/comment-embed.js"></script>`;
}

function generateFacebookEmbed(url) {
    return `<div class="facebook-embed"><div>Facebook post: ${url}</div></div>`;
}

function generateYouTubeThumbnailEmbed(url) {
    const videoId = extractYouTubeId(url);
    if (videoId) {
        return `<div class="youtube-thumbnail" data-embed-url="https://www.youtube.com/embed/${videoId}">
            <img src="https://img.youtube.com/vi/${videoId}/maxresdefault.jpg" alt="YouTube Video">
            <div class="play-button">▶</div>
        </div>`;
    }
    return '';
}

function generateInstagramEmbed(url) {
    return `<div class="instagram-embed"><div>Instagram post: ${url}</div></div>`;
}

function extractYouTubeId(url) {
    const regExp = /^.*(youtu.be\/|v\/|embed\/|watch\?v=|watch\?.+&v=)([^#&?]*).*/;
    const match = url.match(regExp);
    return (match && match[2].length === 11) ? match[2] : null;
}

// Função para obter HTML de embed
function getEmbedHtml(url) {
    let embedHtml = '';

    if (url.includes('youtube.com') || url.includes('youtu.be')) {
        const videoId = extractYouTubeId(url);
        if (videoId) {
            embedHtml = `<iframe width="98%" height="auto" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`;
        }
    } else if (url.includes('vimeo.com')) {
        const videoId = extractVimeoId(url);
        if (videoId) {
            embedHtml = `<iframe width="98%" height="auto" src="https://player.vimeo.com/video/${videoId}" frameborder="0" allowfullscreen></iframe>`;
        }
    }
    
    return embedHtml;
}

function extractVimeoId(url) {
    const regExp = /vimeo\.com\/(\d+)/;
    const match = url.match(regExp);
    return match ? match[1] : null;
}

// Funções utilitárias
function extractDomainFromUrl(url) {
    try {
        const urlObj = new URL(url);
        return urlObj.hostname.replace('www.', '');
    } catch (e) {
        return '';
    }
}

function extractBaseDomainFromUrl(url) {
    try {
        const domain = extractDomainFromUrl(url);
        const parts = domain.split('.');
        if (parts.length > 2) {
            return parts.slice(-2).join('.');
        }
        return domain;
    } catch (e) {
        return '';
    }
}

function truncateText(text, maxLength) {
    if (!text) return '';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
}

function stringToColor(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    let color = '#';
    for (let i = 0; i < 3; i++) {
        const value = (hash >> (i * 8)) & 0xFF;
        color += ('00' + value.toString(16)).substr(-2);
    }
    return color;
}

function isColorDark(color) {
    const hex = color.replace('#', '');
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    const brightness = ((r * 299) + (g * 587) + (b * 114)) / 1000;
    return brightness < 128;
}

function extractTagsFromTitle(title) {
    if (!title) return [];
    
    const words = title.toLowerCase()
        .replace(/[^\w\s]/g, ' ')
        .split(/\s+/)
        .filter(word => word.length > 3);
    
    const stopWords = ['para', 'como', 'sobre', 'mais', 'novo', 'melhor', 'quando', 'onde', 'porque'];
    
    return words
        .filter(word => !stopWords.includes(word))
        .slice(0, 5);
}

function getFaviconUrl(url) {
    try {
        const urlObj = new URL(url);
        return urlObj.origin + '/favicon.ico';
    } catch (e) {
        return '';
    }
}

function createShareButton(feed) {
    const url = encodeURIComponent(feed.link);
    const title = encodeURIComponent(feed.title);
    
    return `
    <div class="share-button-container">
        <button class="share-icon-button" title="Compartilhar">
            <i class="fas fa-share-alt"></i>
        </button>
        <div class="share-options">
            <button onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=${url}', '_blank')" title="Facebook">
                <i class="fab fa-facebook-f"></i>
            </button>
            <button onclick="window.open('https://twitter.com/intent/tweet?url=${url}&text=${title}', '_blank')" title="Twitter">
                <i class="fab fa-twitter"></i>
            </button>
            <button onclick="window.open('https://www.linkedin.com/sharing/share-offsite/?url=${url}', '_blank')" title="LinkedIn">
                <i class="fab fa-linkedin"></i>
            </button>
            <button onclick="window.open('https://wa.me/?text=${title}%20${url}', '_blank')" title="WhatsApp">
                <i class="fab fa-whatsapp"></i>
            </button>
            <button onclick="navigator.clipboard.writeText('${feed.link}')" title="Copiar Link">
                <i class="fas fa-copy"></i>
            </button>
        </div>
    </div>`;
}

function getEmojiListHtml(feedId) {
    const emojis = {
        'Smileys': ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇'],
        'Love': ['❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '🤎', '💕'],
        'Gestures': ['👍', '👎', '👏', '🙌', '🤝', '🙏', '✌️', '🤞', '🤟', '🤘'],
        'Objects': ['🎉', '🎊', '🎈', '🎁', '🏆', '🥇', '🥈', '🥉', '🏅', '🎯']
    };
    
    let html = `<div id="emoji-list-${feedId}" class="emoji-list">
        <button class="close-btn" onclick="toggleEmojiList(${feedId})">×</button>`;
    
    for (const [category, emojiList] of Object.entries(emojis)) {
        html += `<div class="emoji-category">
            <div class="emoji-category-title">${category}</div>
            <div class="emoji-grid">`;
        
        for (const emoji of emojiList) {
            html += `<span class="emoji-item" onclick="insertEmoji('${emoji}', ${feedId})">${emoji}</span>`;
        }
        
        html += `</div></div>`;
    }
    
    html += `</div>`;
    return html;
}

function toggleEmojiList(feedId) {
    const emojiList = $(`#emoji-list-${feedId}`);
    if (emojiList.hasClass('show')) {
        emojiList.removeClass('show');
    } else {
        $('.emoji-list').removeClass('show');
        emojiList.addClass('show');
    }
}

function insertEmoji(emoji, feedId) {
    const textarea = $(`#new-comment-${feedId}`);
    const currentValue = textarea.val();
    textarea.val(currentValue + emoji);
    textarea.focus();
    toggleEmojiList(feedId);
}

function previewLink(url, container) {
    if (url.includes('youtube.com') || url.includes('youtu.be')) {
        const videoId = extractYouTubeId(url);
        const embedCode = `<iframe width="100%" height="200" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`;
        container.html(embedCode);
    } else if (url.includes('vimeo.com')) {
        const videoId = extractVimeoId(url);
        const embedCode = `<iframe width="100%" height="200" src="https://player.vimeo.com/video/${videoId}" frameborder="0" allowfullscreen></iframe>`;
        container.html(embedCode);
    } else {
        fetchLinkMetadata(url, container);
    }
}

function fetchLinkMetadata(url, container) {
    $.ajax({
        url: 'fetch_metadata.php',
        type: 'POST',
        data: { url: url },
        success: function(data) {
            const metadata = JSON.parse(data);
            if (metadata.success) {
                const previewHtml = `
                    <div style="background-color: #fff; padding: 10px; border-radius: 4px; margin-top: 10px;">
                        <h4 style="margin: 0;">${metadata.title}</h4>
                        <p style="margin: 5px 0;">${metadata.description}</p>
                        <img src="${metadata.image}" alt="Preview" style="max-width: 100%; height: auto; border-radius: 4px;" />
                    </div>
                `;
                container.html(previewHtml);
            } else {
                container.html('<p style="color: red;">Não foi possível obter os dados para este link.</p>');
            }
        },
        error: function() {
            container.html('<p style="color: red;">Erro ao obter os dados do link.</p>');
        }
    });
}

function showCustomNotification(message) {
    var notification = document.createElement('div');
    notification.textContent = message;
    notification.style.position = 'fixed';
    notification.style.bottom = '20px';
    notification.style.right = '20px';
    notification.style.backgroundColor = 'rgba(0,0,0,0.7)';
    notification.style.color = 'white';
    notification.style.padding = '10px';
    notification.style.borderRadius = '5px';
    notification.style.zIndex = '1000';
    document.body.appendChild(notification);

    setTimeout(function() {
        document.body.removeChild(notification);
    }, 3000);
}

// Event handlers globais
$(document).ready(function() {
    console.log('feeds.js carregado');
    
    // Manipulação de cliques para embutir vídeos do YouTube
    $(document).on('click', '.youtube-thumbnail', function() {
        const embedURL = $(this).data('embed-url');
        const embedHtml = `<iframe src="${embedURL}" style="width: 100%; height: 100%; border: none;" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
        $(this).replaceWith(embedHtml);
    });
    
    // Click em links de comentários
    $(document).on('click', '.comment-link', function(e) {
        e.preventDefault();
        const commentId = $(this).data('comment-id');
        const targetComment = $(`#comment-${commentId}`);
        const commentContainer = targetComment.closest('.comment-section');

        if (targetComment.length && commentContainer.length) {
            commentContainer.animate({
                scrollTop: targetComment.position().top + commentContainer.scrollTop() - 50
            }, 700, 'swing', function() {
                targetComment.css({
                    'background-color': '#ffffe0',
                    'transition': 'background-color 0.8s ease-in-out'
                });

                setTimeout(() => {
                    targetComment.css('background-color', '');
                }, 2000);
            });
        }
    });
    
    // Evento de clique para botão responder
    $(document).on('click', '.reply-btn', function() {
        const author = $(this).data('author');
        const commentId = $(this).data('comment-id');
        const feedId = $(this).data('feed-id');
        replyToComment(author, commentId, feedId);
    });
    
    // Evento para copiar iframe
    $(document).on('click', '.copy-iframe-btn', function() {
        var feedId = $(this).data('feed-id');
        var feed = feeds[feedId];
        if (feed) {
            var iframeCode = generateIframeCode(feed);
            showCardNotificationWithIframe('Here is the preview of the Iframe', iframeCode);
        } else {
            console.error('Feed not found:', feedId);
        }
    });
});

// Função generateIframeCode
function generateIframeCode(feed) {
    // Implementação simplificada - você pode expandir conforme necessário
    var iframeContent = `
        <div style="padding: 20px; background: #f5f5f5; border-radius: 10px;">
            <h3>${feed.title}</h3>
            <p>${feed.description}</p>
            <a href="${feed.link}" target="_blank">Ver mais</a>
        </div>
    `;
    
    return `<iframe srcdoc="${iframeContent.replace(/"/g, '&quot;')}" width="100%" height="300" frameborder="0"></iframe>`;
}

function showCardNotificationWithIframe(message, iframeCode) {
    // Implementação da função de notificação
    showCustomNotification('Código iframe copiado!');
    
    // Copia para clipboard
    var textarea = document.createElement('textarea');
    textarea.value = iframeCode;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
}

// SCROLL INFINITO - CORREÇÕES
$(window).off('scroll.infinite');

let scrollTimeout;

$(window).on('scroll.infinite', function() {
    clearTimeout(scrollTimeout);
    scrollTimeout = setTimeout(function() {
        const scrollPosition = $(window).scrollTop() + $(window).height();
        const documentHeight = $(document).height();
        const threshold = 1000;
        
        if (scrollPosition > documentHeight - threshold && !loading) {
            const hasContent = $('#feeds .result').length > 0;
            
            if (hasContent) {
                console.log('Carregando mais feeds... Página:', page + 1);
                page++;
                
                loadFeeds().then(function(data) {
                    console.log('Mais feeds carregados com sucesso');
                    setTimeout(checkIfNeedMoreContent, 500);
                }).catch(function(error) {
                    console.error('Erro ao carregar mais feeds:', error);
                    page--;
                });
            }
        }
    }, 100);
});

// Inicialização
$(document).ready(function() {
    if (typeof window.feeds === 'undefined') window.feeds = {};
    if (typeof window.displayedFeeds === 'undefined') window.displayedFeeds = {};
    if (typeof window.page === 'undefined') window.page = 1;
    if (typeof window.loading === 'undefined') window.loading = false;
    if (typeof window.masonry === 'undefined') window.masonry = null;
    
    // Carrega feeds iniciais
    console.log('Iniciando carregamento de feeds...');
    loadFeeds().then(function() {
        console.log('Feeds iniciais carregados');
        setTimeout(checkIfNeedMoreContent, 1000);
    }).catch(function(error) {
        console.error('Erro ao carregar feeds iniciais:', error);
    });
});

// Função de debug
window.debugSystem = function() {
    console.log('=== DEBUG DO SISTEMA ===');
    console.log('Feeds carregados:', Object.keys(feeds || {}).length);
    console.log('Feeds exibidos:', $('#feeds .result').length);
    console.log('Página atual:', page);
    console.log('Carregando:', loading);
    console.log('Altura do documento:', $(document).height());
    console.log('Altura da janela:', $(window).height());
    console.log('Posição do scroll:', $(window).scrollTop());
    console.log('Masonry:', masonry ? 'Inicializado' : 'Não inicializado');
    if (masonry) {
        console.log('Masonry colunas:', masonry.columns);
        console.log('Masonry alturas:', masonry.columnHeights);
    }
    console.log('=======================');
};