(function() {
    'use strict';

    var devtoolsOpen = false;

    document.addEventListener('keydown', function(e) {
        if (e.key === 'F12') {
            e.preventDefault();
            logEvent('devtools_f12');
            return false;
        }

        if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'I') {
            e.preventDefault();
            logEvent('devtools_shortcut');
            return false;
        }

        if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'J') {
            e.preventDefault();
            logEvent('console_shortcut');
            return false;
        }

        if ((e.ctrlKey || e.metaKey) && e.key === 'u') {
            e.preventDefault();
            logEvent('view_source');
            return false;
        }

        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            logEvent('save_page');
            return false;
        }
    });

    function checkDevTools() {
        var start = performance.now();
        // debugger trap disabled for development
        var end = performance.now();

        var wasOpen = devtoolsOpen;
        devtoolsOpen = (end - start) > 100;

        if (devtoolsOpen && !wasOpen) {
            logEvent('devtools_detected');
        }
    }

    // setInterval(checkDevTools, 5000);

    function watchDom() {
        var content = document.getElementById('content');
        if (!content) return;

        var observer = new MutationObserver(function(mutations) {
            for (var i = 0; i < mutations.length; i++) {
                var mutation = mutations[i];
                if (mutation.type === 'childList') {
                    for (var j = 0; j < mutation.addedNodes.length; j++) {
                        var node = mutation.addedNodes[j];
                        if (node.tagName === 'SCRIPT' && node.src && node.src.indexOf(window.location.origin) !== 0) {
                            logEvent('script_injection');
                            node.remove();
                        }
                    }
                }
            }
        });

        observer.observe(content, { childList: true, subtree: true });
    }

    function checkSessionIntegrity() {
        var stored = sessionStorage.getItem('_wdg_check');
        var csrf = (document.querySelector('meta[name="csrf-token"]') || {}).content || '';

        if (stored) {
            var parts = stored.split(':');
            if (parts[0] !== window.location.origin) {
                logEvent('session_tampering');
            }
        }

        sessionStorage.setItem('_wdg_check', window.location.origin + ':' + Date.now());
    }

    function muteConsole() {
        if (window.location.hostname === 'localhost') return;
        var noop = function() {};
        console.log = noop;
        console.warn = noop;
        console.info = noop;
        console.debug = noop;
    }

    function logEvent(action) {
        try {
            fetch('/api/router.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'watchdog',
                    event: action,
                    timestamp: Date.now(),
                    csrf: (document.querySelector('meta[name="csrf-token"]') || {}).content || ''
                })
            }).catch(function() {});
        } catch (e) {}
    }

    document.addEventListener('DOMContentLoaded', function() {
        watchDom();
        checkSessionIntegrity();
        muteConsole();
    });
})();
