/**
 * Coupon Filter System
 * Filters coupons by type: All, Coupons (with code), Cashback, Deals (no code)
 */

document.addEventListener('DOMContentLoaded', function() {
    initializeCouponFilter();
});

function initializeCouponFilter() {
    const filterTabs = document.querySelectorAll('.coupon-filter-tab');
    const couponItems = document.querySelectorAll('.coupon-item');

    if (filterTabs.length === 0 || couponItems.length === 0) {
        return; // No filters or coupons on this page
    }

    // Count coupons by type
    const counts = {
        all: couponItems.length,
        coupons: 0,
        cashback: 0,
        deals: 0
    };

    couponItems.forEach(item => {
        const type = item.getAttribute('data-coupon-type');
        if (type === 'coupon') counts.coupons++;
        else if (type === 'cashback') counts.cashback++;
        else if (type === 'deal') counts.deals++;
    });

    // Update count badges
    updateFilterCounts(counts);

    // Add click handlers to filter tabs
    filterTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const filterType = this.getAttribute('data-filter');
            
            // Update active state
            filterTabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');

            // Filter coupons
            filterCoupons(filterType, couponItems);

            // Update URL without reload (optional)
            if (history.pushState) {
                const url = new URL(window.location);
                if (filterType === 'all') {
                    url.searchParams.delete('filter');
                } else {
                    url.searchParams.set('filter', filterType);
                }
                history.pushState({}, '', url);
            }
        });
    });

    // Check URL for initial filter
    const urlParams = new URLSearchParams(window.location.search);
    const initialFilter = urlParams.get('filter');
    if (initialFilter) {
        const activeTab = document.querySelector(`[data-filter="${initialFilter}"]`);
        if (activeTab) {
            activeTab.click();
        }
    }
}

function filterCoupons(filterType, couponItems) {
    let visibleCount = 0;

    couponItems.forEach(item => {
        const couponType = item.getAttribute('data-coupon-type');
        
        if (filterType === 'all') {
            item.classList.remove('hidden');
            visibleCount++;
        } else if (filterType === couponType) {
            item.classList.remove('hidden');
            visibleCount++;
        } else {
            item.classList.add('hidden');
        }
    });

    // Show/hide no results message
    showNoResultsMessage(visibleCount);
}

function updateFilterCounts(counts) {
    const allTab = document.querySelector('[data-filter="all"] .count');
    const couponsTab = document.querySelector('[data-filter="coupon"] .count');
    const cashbackTab = document.querySelector('[data-filter="cashback"] .count');
    const dealsTab = document.querySelector('[data-filter="deal"] .count');

    if (allTab) allTab.textContent = `(${counts.all})`;
    if (couponsTab) couponsTab.textContent = `(${counts.coupons})`;
    if (cashbackTab) cashbackTab.textContent = `(${counts.cashback})`;
    if (dealsTab) dealsTab.textContent = `(${counts.deals})`;
}

function showNoResultsMessage(visibleCount) {
    let noResultsMsg = document.querySelector('.no-coupons-message');
    
    if (visibleCount === 0) {
        if (!noResultsMsg) {
            noResultsMsg = document.createElement('div');
            noResultsMsg.className = 'no-coupons-message';
            noResultsMsg.innerHTML = `
                <i class="fas fa-inbox"></i>
                <h4>No coupons found</h4>
                <p>Try selecting a different filter</p>
            `;
            
            const couponContainer = document.querySelector('.uk-grid-medium');
            if (couponContainer) {
                couponContainer.appendChild(noResultsMsg);
            }
        }
        noResultsMsg.style.display = 'block';
    } else {
        if (noResultsMsg) {
            noResultsMsg.style.display = 'none';
        }
    }
}

// Export for use in other scripts if needed
window.CouponFilter = {
    initialize: initializeCouponFilter,
    filter: filterCoupons
};
