/**
 * FocusFeed Content Script
 * Handles signal-over-noise filtering across platforms (Deutsch).
 */

const CONFIG = {
    platforms: {
        linkedin: {
            postSelector: '.feed-shared-update-v2',
            textSelector: '.feed-shared-update-v2__description-wrapper'
        },
        twitter: {
            postSelector: 'article[data-testid="tweet"]',
            textSelector: 'div[data-testid="tweetText"]'
        },
        instagram: {
            postSelector: 'article',
            textSelector: '._ap3a'
        },
        tiktok: {
            postSelector: '.tiktok-1p6thf-DivItemContainerV2, .tiktok-1667s3z-DivVideoContainer',
            textSelector: '.tiktok-1m7487m-PText, .tiktok-1v96oov-PText'
        },
        youtube: {
            postSelector: 'ytd-reel-video-renderer',
            textSelector: '#overlay .title'
        }
    }
};

const WEIGHTS = {
    keywords: {
        'mindset': 8,
        'synergie': 6,
        'skalierung': 7,
        'hustle': 6,
        'passives einkommen': 10,
        'entrepreneur': 4,
        'erfolg': 3,
        'finanzielle freiheit': 10,
        'scaling': 7
    },
    bait: {
        'stimmst du zu?': 8,
        'markiere jemanden': 7,
        'schreib es in die kommentare': 8,
        'wait for it': 10,
        'link in der bio': 5,
        'do you agree?': 8
    },
    indicators: {
        '🚀': 4,
        '✅': 3,
        '💡': 3,
        'in der heutigen schnelllebigen welt': 8,
        'hast du dich jemals gefragt': 6,
        'look no further': 7
    }
};

const THRESHOLD = 10; // Minimum score to block a post

// State
let filteredCount = 0;

function processFeed() {
    chrome.storage.local.get(['toggle_0', 'toggle_1', 'toggle_2', 'customKeywords'], (settings) => {
        const hardFilterActive = settings.toggle_0 !== false;
        const aiDetectorActive = settings.toggle_1 !== false;
        const shortsFilterActive = settings.toggle_2 !== false;
        const customKeywords = settings.customKeywords || [];

        const hostname = window.location.hostname;
        let platformKey = '';

        if (hostname.includes('linkedin')) platformKey = 'linkedin';
        else if (hostname.includes('twitter') || hostname.includes('x.com')) platformKey = 'twitter';
        else if (hostname.includes('instagram')) platformKey = 'instagram';
        else if (hostname.includes('tiktok')) platformKey = 'tiktok';
        else if (hostname.includes('youtube')) platformKey = 'youtube';

        if (!platformKey) return;

        // Skip if shorts filter is off and we are on a shorts platform
        if (!shortsFilterActive && (platformKey === 'tiktok' || platformKey === 'youtube')) return;

        const platformConfig = CONFIG.platforms[platformKey];
        const posts = document.querySelectorAll(platformConfig.postSelector);

        posts.forEach(post => {
            if (post.dataset.focusFeedProcessed) return;

            const textElement = post.querySelector(platformConfig.textSelector);
            if (!textElement) return;

            const text = textElement.innerText.toLowerCase();
            let score = 0;
            let detectedTriggers = [];

            // 1. Check Hard Filter (Keywords)
            if (hardFilterActive) {
                // Predefined Keywords
                for (const [kw, weight] of Object.entries(WEIGHTS.keywords)) {
                    if (text.includes(kw)) {
                        score += weight;
                        detectedTriggers.push(kw);
                    }
                }
                // Custom Keywords (High Weight)
                customKeywords.forEach(kw => {
                    if (text.includes(kw.toLowerCase())) {
                        score += 10; // Custom keywords are immediate red flags
                        detectedTriggers.push(kw);
                    }
                });
            }

            // 2. Check Engagement Bait
            if (hardFilterActive) {
                for (const [bait, weight] of Object.entries(WEIGHTS.bait)) {
                    if (text.includes(bait)) {
                        score += weight;
                        detectedTriggers.push('Engagement-Bait');
                    }
                }
            }

            // 3. Check AI/Structural Indicators
            if (aiDetectorActive) {
                for (const [ind, weight] of Object.entries(WEIGHTS.indicators)) {
                    if (text.includes(ind)) {
                        score += weight;
                        detectedTriggers.push('KI-Muster');
                    }
                }
                // Bonus for many emojis
                const emojiMatches = text.match(/[🚀✅💡]/g) || [];
                if (emojiMatches.length >= 3) {
                    score += 5;
                    detectedTriggers.push('Emoji-Spam');
                }
            }

            if (score >= THRESHOLD) {
                const category = score > 15 ? 'ai' : 'keywords'; // Simple logic for category
                const reason = `Noise Score: ${score}/10 (${detectedTriggers.slice(0,2).join(', ')})`;
                applyFilter(post, reason, category);
            }

            post.dataset.focusFeedProcessed = 'true';
        });
    });
}

// State
let tabFilteredCount = 0;

function applyFilter(post, reason, category) {
    const bar = document.createElement('div');
    bar.className = 'focus-feed-collapsed-bar';
    bar.innerHTML = `
        <div class="ff-bar-content">
            <span class="ff-label">FOCUSFEED BLOCKIERT</span>
            <span class="ff-reason">${reason}</span>
        </div>
        <button class="ff-override-btn">Trotzdem anzeigen</button>
    `;

    post.classList.add('ff-collapsed-post');
    post.prepend(bar);

    bar.querySelector('.ff-override-btn').addEventListener('click', (e) => {
        e.stopPropagation();
        post.classList.toggle('ff-show-override');
        bar.querySelector('.ff-override-btn').innerText = 
            post.classList.contains('ff-show-override') ? 'Verbergen' : 'Trotzdem anzeigen';
    });

    // Track detailed stats
    chrome.storage.local.get(['stats'], (result) => {
        const stats = result.stats || { total: 0, keywords: 0, ai: 0, shorts: 0 };
        stats.total++;
        if (category === 'keywords') stats.keywords++;
        else if (category === 'ai') stats.ai++;
        else if (category === 'shorts') stats.shorts++;
        
        chrome.storage.local.set({ stats, filteredCount: stats.total });
        
        // Update Badge via Background
        tabFilteredCount++;
        chrome.runtime.sendMessage({ type: 'BLOCK_EVENT', count: tabFilteredCount });
    });
}

const observer = new MutationObserver(() => {
    processFeed();
});

observer.observe(document.body, { childList: true, subtree: true });
processFeed();
console.log('FocusFeed aktiv. Suche nach Rauschen...');
