//utils.js

function truncateText(text, maxLength) {
  return text.length > maxLength ? text.slice(0, maxLength) + '...' : text;
}


function extractBaseDomainFromUrl(url) {
    if (!url) return null;
    const matches = url.match(/:\/\/(www\.)?([^\/]+)/);
    return matches ? matches[2] : null;
}





function extractDomainFromUrl(url) {
    if (!url) return null;
    const matches = url.match(/^(?:https?:\/\/)?(?:www\.)?([^\/]+)/i);
    return matches ? matches[1] : null;
}






      function extractTagsFromTitle(title) {
        // Normaliza o título removendo pontuação e convertendo para minúsculas
        let normalizedTitle = title.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "").toLowerCase();

        // Divide o título em palavras
        let words = normalizedTitle.split(" ");

        // Lista de palavras comuns estendida
        let commonWords = ["a", "an", "the", "and", "or", "but", "in", "at", "on", "with", "to", "–", "for", "is", "of", "that", "it", "by", "from", "as", "are", "was", "be", "has", "have", "will", "this", "which", "its", "about", "up", "more", "who", "also", "they", "out", "he", "she", "you", "their", "we", "her", "his", "them", "been", "these", "would", "some", "can", "like", "there", "if", "all", "my", "what", "so", "then", "into", "just", "over", "do", "than", "when", "other", "how", "our", "any", "new", "me", "after", "most", "made", "only", "time", "will", "where", "year", "years", "make", "does", "could", "were", "your", "good", "well", "them"];

        // Filtra as palavras pequenas e comuns
        let keywords = words.filter(word => !commonWords.includes(word) && word.length > 2);

        return keywords;
      }

     

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++) {
        let value = (hash >> (i * 8)) & 0xFF;
        color += ('00' + value.toString(16)).substr(-2);
    }
    return color;
}


function isColorDark(hex) {
    let r = parseInt(hex.slice(1, 3), 16);
    let g = parseInt(hex.slice(3, 5), 16);
    let b = parseInt(hex.slice(5, 7), 16);
    let brightness = (r * 299 + g * 587 + b * 114) / 1000;
    return brightness < 128;
}

function prepareShareData(feed) {
    return {
        title: feed.title || 'Sem título',
        url: `https://myhashtag.io/pindetails.php?id=${feed.id}`,
        description: feed.description || 'Sem descrição',
        thumbnail: feed.thumbnail || 'URL_PADRAO_PARA_THUMBNAIL'
    };
}




function shareOnPlatform(platform, url, title = '', thumbnail = '') {
    title = encodeURIComponent(title);
    url = encodeURIComponent(url);
    thumbnail = encodeURIComponent(thumbnail);

    let shareUrl = '';
    switch(platform) {
        case 'facebook':
            shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}&t=${title}&picture=${thumbnail}`;
            break;
        case 'twitter':
            shareUrl = `https://twitter.com/intent/tweet?url=${url}&text=${title}&image=${thumbnail}`;
            break;
        case 'whatsapp':
            shareUrl = `https://api.whatsapp.com/send?text=${title} ${url}`;
            break;
        case 'pinterest':
            shareUrl = `https://pinterest.com/pin/create/button/?url=${url}&media=${thumbnail}&description=${title}`;
            break;
        case 'telegram':
            shareUrl = `https://t.me/share/url?url=${url}&text=${title}`;
            break;
        case 'reddit':
            shareUrl = `https://www.reddit.com/submit?url=${url}&title=${title}`;
            break;
        // Adicione mais plataformas conforme necessário
    }

    window.open(shareUrl, '_blank');
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        alert('Link copied to clipboard!');
    }).catch(err => {
        console.error('Something went wrong', err);
    });
}

function toggleShareOptions(buttonElement) {
    var shareOptions = buttonElement.nextElementSibling;
    shareOptions.style.display = shareOptions.style.display === "none" ? "block" : "none";
}

// Exemplo de uso: Adicione esta função ao botão de compartilhamento de cada feed
function createShareButton(feed) {
    var shareData = prepareShareData(feed);
    var copyIframeButtonHtml = `<button class="copy-iframe-btn" data-feed-id="${feed.id}" title="Copy Iframe Code"><i class="fas fa-code"></i></button>`; // Botão de cópia do iframe
    var shareButtonHtml = `
        <div class="share-button-container">
            <button class="share-icon-button" onclick="toggleShareOptions(this)">
                <i class="fas fa-share-alt"></i> <!-- Ícone de compartilhamento -->
            </button>
            <div class="share-options" style="display: none;">
                <button onclick="shareOnPlatform('facebook', '${shareData.url}', '${shareData.title}', '${shareData.thumbnail}')">
                    <i class="fab fa-facebook-f"></i>
                </button>
                <button onclick="shareOnPlatform('twitter', '${shareData.url}', '${shareData.title}', '${shareData.thumbnail}')">
                    <i class="fab fa-twitter"></i>
                </button>
                <button onclick="shareOnPlatform('whatsapp', '${shareData.url}', '${shareData.title}', '${shareData.thumbnail}')">
                    <i class="fab fa-whatsapp"></i>
                </button>
                <button onclick="shareOnPlatform('pinterest', '${shareData.url}', '${shareData.title}', '${shareData.thumbnail}')">
                    <i class="fab fa-pinterest"></i>
                </button>
                <button onclick="shareOnPlatform('telegram', '${shareData.url}', '${shareData.title}', '${shareData.thumbnail}')">
                    <i class="fab fa-telegram-plane"></i>
                </button>
                <button onclick="shareOnPlatform('reddit', '${shareData.url}', '${shareData.title}', '${shareData.thumbnail}')">
                    <i class="fab fa-reddit-alien"></i>
                </button>
                <button onclick="copyToClipboard('${shareData.url}')">
                    <i class="fas fa-copy"></i>
                </button>
            ${copyIframeButtonHtml} <!-- Inclui o botão de cópia do iframe aqui -->
        </div>`;

    return shareButtonHtml;
}

$(document).ready(function() {
    $('.result').each(function() {
        var resultWidth = $(this).width(); // Pega a largura do resultado
        if (resultWidth < 300) { // Se a largura for menor que um valor específico
            $(this).find('.share-options button i').css('font-size', '16px'); // Reduz o tamanho da fonte dos ícones
            $(this).find('.share-options button').css({'padding': '2px', 'margin-right': '2px'}); // Reduz o padding e a margem
        }
    });
});
