(function() {
    'use strict';

    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.body.classList.add('blur-protect');
        } else {
            document.body.classList.remove('blur-protect');
        }
    });

    document.addEventListener('keyup', function(e) {
        if (e.key === 'PrintScreen') {
            flashOverlay();
            logWatchdogEvent('screenshot_attempt');
        }
    });

    window.print = function() {
        logWatchdogEvent('print_blocked');
    };

    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
            e.preventDefault();
            logWatchdogEvent('print_blocked');
        }
    });

    function flashOverlay() {
        var overlay = document.createElement('div');
        overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:#fff;z-index:999999;opacity:1;transition:opacity 0.3s;';
        document.body.appendChild(overlay);
        setTimeout(function() {
            overlay.style.opacity = '0';
            setTimeout(function() {
                if (overlay.parentNode) overlay.remove();
            }, 300);
        }, 150);
    }

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