// Configuration & State
let showProtection = false;
const GRID_SELECTOR = '.feed-grid .feed-grid__item';
const H1_SELECTOR = 'h1.web_ui__Text__text.web_ui__Text__heading.web_ui__Text__left.web_ui__Text__parent';

// 1. Create and Inject the Toggle Button
const btn = document.createElement('button');
btn.id = 'vinted-helper-toggle';
btn.innerText = "Show Total Price (Incl. Protection)";
btn.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 10000;
    padding: 12px 20px;
    background: #007782;
    color: white;
    border: 2px solid #005f68;
    border-radius: 8px;
    cursor: pointer;
    font-family: sans-serif;
    font-weight: bold;
`;
document.body.appendChild(btn);

// 2. Calculation Logic
const updateDisplayAndSum = () => {
    const items = document.querySelectorAll(GRID_SELECTOR);
    let totalSum = 0;
    let count = 0;

    items.forEach(item => {
        const basePriceEl = item.querySelector('[data-testid*="--price-text"]');
        const protectPriceEl = item.querySelector('[data-testid*="--breakdown"] .web_ui__Text__subtitle');

        if (basePriceEl && protectPriceEl) {
            // Determine which price to use for the sum
            const targetEl = showProtection ? protectPriceEl : basePriceEl;
            const price = parseFloat(targetEl.innerText.replace(/[^\d,.]/g, '').replace(',', '.'));

            if (!isNaN(price)) {
                totalSum += price;
                count++;
            }

            // Visual Toggling
            if (showProtection) {
                basePriceEl.style.display = 'none';
                protectPriceEl.style.color = '#eb5a62';
                protectPriceEl.style.fontWeight = 'bold';
                protectPriceEl.style.fontSize = '1.1em';
            } else {
                basePriceEl.style.display = 'block';
                protectPriceEl.style.color = '';
                protectPriceEl.style.fontWeight = '';
                protectPriceEl.style.fontSize = '';
            }
        }
    });

    // Update the H1 Header
    const header = document.querySelector(H1_SELECTOR);
    if (header && count > 0) {
        const formattedSum = totalSum.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        const label = showProtection ? "Total (with Prot.)" : "Total";
        
        // Remove old brackets if they exist, then append new total
        const cleanTitle = header.innerText.split(' [')[0];
        header.innerText = `${cleanTitle} [${label}: €${formattedSum}]`;
    }
};

// 3. Event Listener
btn.addEventListener('click', () => {
    showProtection = !showProtection;
    btn.innerText = showProtection ? "Show Base Price" : "Show Total Price (Incl. Protection)";
    btn.style.background = showProtection ? "#eb5a62" : "#007782";
    updateDisplayAndSum();
});

// Initial run
setTimeout(updateDisplayAndSum, 2000);

// Update sum when scrolling (lazy loading support)
let scrollTimeout;
window.addEventListener('scroll', () => {
    clearTimeout(scrollTimeout);
    scrollTimeout = setTimeout(updateDisplayAndSum, 500);
});