console.log('🚀 Codak Footer - Loading...');

// IMMEDIATE EXECUTION - runs before anything else
(function () {
    'use strict';

    var injected = false;
    var forceInjectionInterval = null;

    // CRITICAL: Remove EspoCRM copyright text specifically
    function removeEspoCRMCopyright() {
        // Target specific text: "© 2025 EspoCRM, Inc."
        var allElements = document.querySelectorAll('*');

        allElements.forEach(function (element) {
            // Check text nodes specifically
            if (element.nodeType === Node.ELEMENT_NODE) {
                var walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
                var textNodes = [];
                var node;

                while (node = walker.nextNode()) {
                    textNodes.push(node);
                }

                textNodes.forEach(function (textNode) {
                    // Check if text contains EspoCRM 2025
                    if (textNode.textContent.includes('EspoCRM') && textNode.textContent.includes('2025')) {
                        // Replace with Codak copyright
                        textNode.textContent = 'Copyright © 2026 Codak';
                    }
                });
            }
        });

        // Also check for elements with the specific text
        var paragraphs = document.querySelectorAll('p');
        paragraphs.forEach(function (p) {
            if (p.textContent.includes('EspoCRM') && p.textContent.includes('2025')) {
                p.innerHTML = 'Copyright © 2026 <a href="https://codak.net" target="_blank" rel="noopener noreferrer">Codak</a>';
            }
        });
    }

    // CRITICAL: Inject footer immediately
    function injectCodakFooter() {
        try {
            var footer = document.getElementById('footer');

            // Create footer if it doesn't exist
            if (!footer) {
                footer = document.createElement('footer');
                footer.id = 'footer';
                document.body.appendChild(footer);
            }

            // Check if already injected correctly
            if (footer.querySelector('.codak-footer-container')) {
                return;
            }

            // FORCE CLEAR everything in footer
            footer.innerHTML = '';

            // Apply styles immediately
            footer.style.cssText = 'display: block !important; visibility: visible !important; width: 100% !important; padding: 12px 20px !important; margin: 0 !important; border: none !important; background: transparent !important; text-align: center !important;';

            // Create container
            var container = document.createElement('div');
            container.className = 'codak-footer-container';

            // Create copyright text
            var copyright = document.createElement('p');
            copyright.className = 'codak-copyright';

            // Add text before link
            var textBefore = document.createTextNode('Copyright © 2026 ');

            // Create link
            var link = document.createElement('a');
            link.href = 'https://codak.net';
            link.target = '_blank';
            link.className = 'codak-link';
            link.textContent = 'Codak';
            link.setAttribute('rel', 'noopener noreferrer');

            // Append elements
            copyright.appendChild(textBefore);
            copyright.appendChild(link);
            container.appendChild(copyright);
            footer.appendChild(container);

            injected = true;
            console.log('✅ Codak Footer injected successfully');

        } catch (error) {
            console.error('❌ Footer injection error:', error);
        }
    }

    // CRITICAL: Hide original footer immediately
    function hideOriginalFooter() {
        var style = document.getElementById('hide-original-footer-style');
        if (!style) {
            style = document.createElement('style');
            style.id = 'hide-original-footer-style';
            style.textContent = '#footer .credit, #footer p:not(.codak-copyright), #footer > div:not(.codak-footer-container) { display: none !important; visibility: hidden !important; opacity: 0 !important; height: 0 !important; }';
            document.head.appendChild(style);
        }

        // Also remove EspoCRM elements during loading
        removeEspoCRMCopyright();
    }

    // Execute IMMEDIATELY
    hideOriginalFooter();
    injectCodakFooter();

    // Execute after 50ms
    setTimeout(function () {
        hideOriginalFooter();
        injectCodakFooter();
    }, 50);

    // Execute after 100ms
    setTimeout(function () {
        hideOriginalFooter();
        injectCodakFooter();
    }, 100);

    // Execute after 500ms
    setTimeout(function () {
        hideOriginalFooter();
        injectCodakFooter();
    }, 500);

    // Execute after 1s
    setTimeout(function () {
        hideOriginalFooter();
        injectCodakFooter();
    }, 1000);

    // Execute on DOMContentLoaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            hideOriginalFooter();
            injectCodakFooter();
            removeEspoCRMCopyright();
        });
    }

    // Execute on load
    window.addEventListener('load', function () {
        hideOriginalFooter();
        injectCodakFooter();
        removeEspoCRMCopyright();
    });

    // CRITICAL: Monitor footer changes - reapply if needed
    var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            if (mutation.addedNodes.length || mutation.removedNodes.length) {
                var footer = document.getElementById('footer');
                if (footer && !footer.querySelector('.codak-footer-container')) {
                    injected = false;
                    hideOriginalFooter();
                    injectCodakFooter();
                }
                // Always remove EspoCRM copyright
                removeEspoCRMCopyright();
            }
        });
    });

    setTimeout(function () {
        var footer = document.getElementById('footer');
        if (footer) {
            observer.observe(footer, {
                childList: true,
                subtree: true,
                attributes: true,
                characterData: true
            });
        }
        observer.observe(document.body, { childList: true, subtree: true });
    }, 500);

    // FORCE injection every 2 seconds for first 10 seconds
    var forcedChecks = 0;
    forceInjectionInterval = setInterval(function () {
        forcedChecks++;
        hideOriginalFooter();

        var footer = document.getElementById('footer');
        if (footer && !footer.querySelector('.codak-footer-container')) {
            injected = false;
            injectCodakFooter();
        }

        if (forcedChecks >= 5) {
            clearInterval(forceInjectionInterval);
        }
    }, 2000);

})();