(function () {
    'use strict';
    function sha256(str) {
        var buf = new TextEncoder().encode(str);
        return crypto.subtle.digest('SHA-256', buf).then(function (hash) {
            var arr = new Uint8Array(hash);
            var hex = '';
            for (var i = 0; i < arr.length; i++) {
                hex += ('0' + arr[i].toString(16)).slice(-2);
            }
            return hex;
        });
    }
    function getCanvasHash() {
        try {
            var canvas = document.createElement('canvas');
            canvas.width = 280;
            canvas.height = 60;
            var ctx = canvas.getContext('2d');
            if (!ctx) return 'no-canvas';
            ctx.textBaseline = 'alphabetic';
            ctx.fillStyle = '#f60';
            ctx.fillRect(50, 0, 130, 60);
            ctx.fillStyle = '#069';
            ctx.font = '15px Arial, sans-serif';
            ctx.fillText('noname:fp:2026', 2, 15);
            ctx.fillStyle = 'rgba(102,204,0,0.7)';
            ctx.font = '18px Times New Roman, serif';
            ctx.fillText('noname:fp:2026', 4, 45);
            ctx.beginPath();
            ctx.arc(80, 30, 20, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(255,0,128,0.5)';
            ctx.fill();

            return canvas.toDataURL();
        } catch (e) {
            return 'canvas-error';
        }
    }
    function getWebGLRenderer() {
        try {
            var canvas = document.createElement('canvas');
            var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
            if (!gl) return 'no-webgl';
            var ext = gl.getExtension('WEBGL_debug_renderer_info');
            if (!ext) return 'no-debug-info';
            var vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) || '';
            var renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) || '';
            return vendor + '::' + renderer;
        } catch (e) {
            return 'webgl-error';
        }
    }
    function getAudioFingerprint() {
        return new Promise(function (resolve) {
            try {
                var AudioContext = window.OfflineAudioContext || window.webkitOfflineAudioContext;
                if (!AudioContext) { resolve('no-audio'); return; }

                var ctx = new AudioContext(1, 5000, 44100);
                var oscillator = ctx.createOscillator();
                oscillator.type = 'triangle';
                oscillator.frequency.setValueAtTime(10000, ctx.currentTime);
                var compressor = ctx.createDynamicsCompressor();
                compressor.threshold.setValueAtTime(-50, ctx.currentTime);
                compressor.knee.setValueAtTime(40, ctx.currentTime);
                compressor.ratio.setValueAtTime(12, ctx.currentTime);
                compressor.attack.setValueAtTime(0, ctx.currentTime);
                compressor.release.setValueAtTime(0.25, ctx.currentTime);
                oscillator.connect(compressor);
                compressor.connect(ctx.destination);
                oscillator.start(0);
                ctx.startRendering().then(function (buffer) {
                    var data = buffer.getChannelData(0);
                    var sum = 0;
                    for (var i = 4500; i < 5000; i++) {
                        sum += Math.abs(data[i]);
                    }
                    resolve(sum.toString());
                }).catch(function () {
                    resolve('audio-render-error');
                });
            } catch (e) {
                resolve('audio-error');
            }
        });
    }
    function getScreenSignature() {
        return [
            screen.width,
            screen.height,
            screen.colorDepth,
            window.devicePixelRatio || 1,
            screen.availWidth,
            screen.availHeight
        ].join('x');
    }
    function getPlatformSignals() {
        return [
            navigator.hardwareConcurrency || 0,
            navigator.platform || 'unknown',
            navigator.maxTouchPoints || 0,
            (Intl.DateTimeFormat().resolvedOptions().timeZone || 'unknown'),
            (navigator.languages || [navigator.language || 'en']).join(',')
        ].join('|');
    }
    function getFontSignature() {
        var testFonts = [
            'Arial', 'Verdana', 'Times New Roman', 'Georgia', 'Courier New',
            'Comic Sans MS', 'Impact', 'Trebuchet MS', 'Palatino Linotype',
            'Lucida Console', 'Tahoma', 'Segoe UI', 'Roboto', 'Helvetica Neue'
        ];
        var baseFonts = ['monospace', 'sans-serif', 'serif'];
        var testStr = 'mmmmmmmmmmlli';
        var testSize = '72px';
        var detected = [];
        var span = document.createElement('span');
        span.style.position = 'absolute';
        span.style.left = '-9999px';
        span.style.top = '-9999px';
        span.style.fontSize = testSize;
        span.textContent = testStr;
        document.body.appendChild(span);
        var baseWidths = {};
        for (var b = 0; b < baseFonts.length; b++) {
            span.style.fontFamily = baseFonts[b];
            baseWidths[baseFonts[b]] = span.offsetWidth;
        }

        for (var f = 0; f < testFonts.length; f++) {
            var found = false;
            for (var bb = 0; bb < baseFonts.length; bb++) {
                span.style.fontFamily = '"' + testFonts[f] + '",' + baseFonts[bb];
                if (span.offsetWidth !== baseWidths[baseFonts[bb]]) {
                    found = true;
                    break;
                }
            }
            if (found) detected.push(testFonts[f]);
        }
        document.body.removeChild(span);
        return detected.join(',');
    }
    function collectAndVerify() {
        if (sessionStorage.getItem('_ce_fp_checked')) return;
        var canvasData = getCanvasHash();
        var webgl = getWebGLRenderer();
        var screenSig = getScreenSignature();
        var platform = getPlatformSignals();
        var fonts = getFontSignature();
        getAudioFingerprint().then(function (audioData) {
            var composite = [
                canvasData,
                webgl,
                audioData,
                screenSig,
                platform,
                fonts
            ].join('|||');
            sha256(composite).then(function (deviceHash) {
                Promise.all([
                    sha256(canvasData),
                    sha256(audioData)
                ]).then(function (hashes) {
                    var payload = {
                        device_hash: deviceHash,
                        canvas_hash: hashes[0],
                        audio_hash: hashes[1],
                        webgl_renderer: webgl,
                        screen_sig: screenSig
                    };
                    payload.route = 'security.fingerprint';
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', 'api/index.php', true);
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    xhr.onload = function () {
                        try {
                            var res = JSON.parse(xhr.responseText);
                            if (res && res.excluded) {
                                showExclusionOverlay();
                            }
                        } catch (e) { /* silent */ }
                        sessionStorage.setItem('_ce_fp_checked', '1');
                    };
                    xhr.send(JSON.stringify(payload));
                });
            });
        });
    }
    function showExclusionOverlay() {
        var overlay = document.createElement('div');
        overlay.id = 'exclusion-overlay';
        overlay.style.cssText = [
            'position:fixed', 'top:0', 'left:0', 'right:0', 'bottom:0',
            'background:rgba(0,0,0,.95)', 'z-index:999999',
            'display:flex', 'align-items:center', 'justify-content:center',
            'flex-direction:column', 'color:#fff', 'font-family:system-ui,sans-serif',
            'text-align:center', 'padding:40px'
        ].join(';');
        overlay.innerHTML = '<div style="max-width:500px">'
            + '<h1 style="font-size:28px;margin-bottom:16px;color:#f87171">Access Restricted</h1>'
            + '<p style="font-size:16px;line-height:1.6;color:#d1d5db;margin-bottom:24px">'
            + 'This account has been self-excluded from noname services. '
            + 'This action was taken at your own request to support responsible use.</p>'
            + '<p style="font-size:14px;color:#9ca3af">'
            + 'If you believe this is an error, please contact support.</p>'
            + '</div>';
        document.body.appendChild(overlay);
        document.body.style.overflow = 'hidden';
        document.addEventListener('click', function (e) {
            if (document.getElementById('exclusion-overlay')) {
                e.preventDefault();
                e.stopPropagation();
            }
        }, true);
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            setTimeout(collectAndVerify, 500);
        });
    } else {
        setTimeout(collectAndVerify, 500);
    }
})();
