/**
 * RandomGroup Pro - Custom Ad Manager
 * Supports full custom code injection for each ad slot
 */
(function() {
    var STORAGE_KEY = 'rgp_ad_config_v1';
    var DOMAIN_STORAGE_KEY = 'rgp_domain_config_v1';

    var defaultConfig = {
        enabled: false,
        slots: {
            aboveNav: { enabled: false, code: '' },
            header: { enabled: false, code: '' },
            hero: { enabled: false, code: '' },
            contentTop: { enabled: false, code: '' },
            contentMiddle: { enabled: false, code: '' },
            contentBottom: { enabled: false, code: '' },
            sidebar: { enabled: false, code: '' },
            footer: { enabled: false, code: '' },
            betweenTools: { enabled: false, code: '' },
            popunder: { enabled: false, code: '' },
            socialBar: { enabled: false, code: '' },
            sticky: { enabled: false, code: '' }
        }
    };

    function readConfig() {
        try {
            var raw = localStorage.getItem(STORAGE_KEY);
            if (!raw) return JSON.parse(JSON.stringify(defaultConfig));
            var parsed = JSON.parse(raw);
            var merged = JSON.parse(JSON.stringify(defaultConfig));
            if (parsed.slots) {
                for (var key in parsed.slots) {
                    if (parsed.slots.hasOwnProperty(key)) {
                        merged.slots[key] = parsed.slots[key];
                    }
                }
            }
            merged.enabled = parsed.enabled || false;
            return merged;
        } catch (e) {
            return JSON.parse(JSON.stringify(defaultConfig));
        }
    }

    function readDomainConfig() {
        try {
            var raw = localStorage.getItem(DOMAIN_STORAGE_KEY);
            if (!raw) return { domainUrl: 'https://randomgrouppro.com', siteName: 'RandomGroup Pro' };
            return JSON.parse(raw);
        } catch (e) {
            return { domainUrl: 'https://randomgrouppro.com', siteName: 'RandomGroup Pro' };
        }
    }

    function injectScript(scriptElement) {
        var newScript = document.createElement('script');
        var attrs = scriptElement.attributes;
        for (var i = 0; i < attrs.length; i++) {
            try {
                newScript.setAttribute(attrs[i].name, attrs[i].value);
            } catch (e) {}
        }
        if (scriptElement.innerHTML) {
            newScript.textContent = scriptElement.innerHTML;
        }
        try {
            scriptElement.parentNode.replaceChild(newScript, scriptElement);
        } catch (e) {}
    }

    function injectCustomCode(container, code) {
        if (!code || !container) return;

        try {
            container.innerHTML = code;
            var scripts = container.querySelectorAll('script');
            for (var i = 0; i < scripts.length; i++) {
                injectScript(scripts[i]);
            }
        } catch (e) {
            console.error('Error injecting ad code:', e);
        }
    }

    function mountSlots(config) {
        if (!config.enabled) return;

        var slotNames = ['aboveNav', 'header', 'hero', 'contentTop', 'contentMiddle', 'contentBottom', 'sidebar', 'footer', 'betweenTools'];

        for (var i = 0; i < slotNames.length; i++) {
            var slotName = slotNames[i];
            var nodes = document.querySelectorAll('[data-ad-slot="' + slotName + '"]');
            for (var j = 0; j < nodes.length; j++) {
                var node = nodes[j];
                var slotData = config.slots && config.slots[slotName];
                if (slotData && slotData.enabled && slotData.code) {
                    injectCustomCode(node, slotData.code);
                }
            }
        }
    }

    function initPopunder(config) {
        if (!config.enabled) return;

        var popunderData = config.slots && config.slots.popunder;
        if (popunderData && popunderData.enabled && popunderData.code) {
            var container = document.createElement('div');
            container.id = 'rgp-popunder-container';
            container.style.display = 'none';
            container.innerHTML = popunderData.code;

            var scripts = container.querySelectorAll('script');
            for (var i = 0; i < scripts.length; i++) {
                injectScript(scripts[i]);
            }

            try {
                document.body.appendChild(container);
            } catch (e) {}
        }
    }

    function initSocialBar(config) {
        if (!config.enabled) return;

        var socialBarData = config.slots && config.slots.socialBar;
        if (socialBarData && socialBarData.enabled && socialBarData.code) {
            var container = document.createElement('div');
            container.id = 'rgp-socialbar-container';
            container.innerHTML = socialBarData.code;

            var scripts = container.querySelectorAll('script');
            for (var i = 0; i < scripts.length; i++) {
                injectScript(scripts[i]);
            }

            try {
                document.body.appendChild(container);
            } catch (e) {}
        }
    }

    function initSticky(config) {
        if (!config.enabled) return;

        var stickyData = config.slots && config.slots.sticky;
        if (stickyData && stickyData.enabled && stickyData.code) {
            var container = document.createElement('div');
            container.id = 'rgp-sticky-container';
            container.style.position = 'fixed';
            container.style.bottom = '0';
            container.style.left = '0';
            container.style.right = '0';
            container.style.zIndex = '9999';
            container.innerHTML = stickyData.code;

            var scripts = container.querySelectorAll('script');
            for (var i = 0; i < scripts.length; i++) {
                injectScript(scripts[i]);
            }

            try {
                document.body.appendChild(container);
            } catch (e) {}
        }
    }

    function initializeAdManager() {
        var config = readConfig();

        mountSlots(config);
        initPopunder(config);
        initSocialBar(config);
        initSticky(config);
    }

    window.RGPAdManager = {
        storageKey: STORAGE_KEY,
        domainStorageKey: DOMAIN_STORAGE_KEY,
        defaultConfig: defaultConfig,
        readConfig: readConfig,
        readDomainConfig: readDomainConfig,
        initializeAdManager: initializeAdManager
    };

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