
// ============================================
// AdRevSurge - Frontend JavaScript
// ============================================

(function() {
    'use strict';

    const WORKER_URL = 'https://plugin.waecghresults.workers.dev';

    const ADV = {
        init: function() {
            console.log('AdRevSurge: Initializing...');
            this.impressions = {};
            this.userId = this.getUserId();
            this.findAndProcessSlots();
            this.observeNewSlots();
            this.trackClicks();
        },

        getUserId: function() {
            const match = document.cookie.match(/adv_user_id=([^;]+)/);
            return match ? match[1] : null;
        },

        getApiUrl: function(endpoint) {
            return WORKER_URL + '/api/' + endpoint;
        },

        findAndProcessSlots: function() {
            const self = this;
            
            const slots = document.querySelectorAll('[data-adv-slot]');
            const autoSlots = document.querySelectorAll('.adsbygoogle, .ad-container, .ad, .ads, .advertisement, .sponsored, [class*="ad-"], [class*="ads-"]');
            
            autoSlots.forEach(function(el) {
                if (!el.hasAttribute('data-adv-slot') && !el.closest('[data-adv-slot]')) {
                    const slotName = el.className.replace(/\s+/g, '-').substring(0, 30) || 'auto-' + Date.now();
                    const wrapper = document.createElement('div');
                    wrapper.setAttribute('data-adv-slot', slotName);
                    el.parentNode.insertBefore(wrapper, el);
                    wrapper.appendChild(el);
                }
            });
            
            const allSlots = document.querySelectorAll('[data-adv-slot]');
            if (allSlots.length === 0) {
                console.log('AdRevSurge: No ad slots found');
                return;
            }
            
            console.log('AdRevSurge: Found ' + allSlots.length + ' ad slots');
            
            allSlots.forEach(function(slot) {
                const slotId = slot.getAttribute('data-adv-slot') || 'default';
                const pageUrl = window.location.href;
                self.requestPrice(slot, slotId, pageUrl);
            });
        },

        observeNewSlots: function() {
            const self = this;
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    mutation.addedNodes.forEach(function(node) {
                        if (node.nodeType === 1) {
                            if (node.matches && node.matches('.adsbygoogle, .ad-container, .ad, .ads, .advertisement, .sponsored, [class*="ad-"], [class*="ads-"]')) {
                                self.findAndProcessSlots();
                            }
                            if (node.querySelectorAll) {
                                const ads = node.querySelectorAll('.adsbygoogle, .ad-container, .ad, .ads, .advertisement, .sponsored, [class*="ad-"], [class*="ads-"]');
                                if (ads.length > 0) {
                                    self.findAndProcessSlots();
                                }
                            }
                        }
                    });
                });
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        },

        requestPrice: function(slot, slotId, pageUrl) {
            const self = this;
            const apiUrl = this.getApiUrl('get_price');
            
            fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    ad_slot: slotId,
                    page_url: pageUrl,
                    user_id: self.userId
                })
            })
            .then(function(response) {
                if (!response.ok) {
                    throw new Error('HTTP ' + response.status);
                }
                return response.json();
            })
            .then(function(response) {
                if (response.success) {
                    const price = response.data.price;
                    const impressionId = response.data.impression_id;
                    
                    self.impressions[slotId] = impressionId;
                    slot.setAttribute('data-reserve-price', price);
                    slot.setAttribute('data-impression-id', impressionId);
                    self.recordImpression(slotId, price);
                } else {
                    console.warn('AdRevSurge: API error:', response.error || 'Unknown error');
                    slot.setAttribute('data-reserve-price', '0.50');
                }
            })
            .catch(function(error) {
                console.warn('AdRevSurge: Price request failed for slot ' + slotId);
                console.warn('Error:', error.message);
                slot.setAttribute('data-reserve-price', '0.50');
            });
        },

        recordImpression: function(slotId, price) {
            const apiUrl = this.getApiUrl('record_impression');
            
            fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    ad_slot: slotId,
                    price: price,
                    user_id: this.userId
                })
            }).catch(function() {
                console.warn('AdRevSurge: Failed to record impression for slot ' + slotId);
            });
        },

        trackClicks: function() {
            const self = this;
            
            document.addEventListener('click', function(e) {
                const slot = e.target.closest('[data-adv-slot]');
                if (slot) {
                    const slotId = slot.getAttribute('data-adv-slot') || 'default';
                    const price = parseFloat(slot.getAttribute('data-reserve-price')) || 0.50;
                    const impressionId = slot.getAttribute('data-impression-id') || '';
                    self.recordClick(slotId, price, price, impressionId);
                }
            });
        },

        recordClick: function(slotId, winningBid, revenue, impressionId) {
            const apiUrl = this.getApiUrl('record_click');
            
            fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    impression_id: impressionId,
                    ad_slot: slotId,
                    winning_bid: winningBid,
                    revenue: revenue,
                    user_id: this.userId
                })
            }).catch(function() {
                console.warn('AdRevSurge: Failed to record click for slot ' + slotId);
            });
        }
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            ADV.init();
        });
    } else {
        ADV.init();
    }

    window.ADV = ADV;

})();
