/**
 * fingerprint.js — PrimeSender Hardware Fingerprinting Module
 * Phase 24.3: Dual-Factor Anti-Trial-Bypass
 * 
 * Runs in MAIN WORLD (page context). Generates a deterministic
 * hardware fingerprint from Canvas + WebGL rendering signatures.
 * Posts the result via window.postMessage for the Content Script world.
 */
(function() {
    'use strict';

    async function generateFingerprint() {
        const signals = [];

        // 1. Canvas Fingerprint
        try {
            const canvas = document.createElement('canvas');
            canvas.width = 280;
            canvas.height = 60;
            const ctx = canvas.getContext('2d');
            if (ctx) {
                // Draw complex shapes for uniqueness
                ctx.textBaseline = 'alphabetic';
                ctx.fillStyle = '#f60';
                ctx.fillRect(100, 1, 62, 20);
                ctx.fillStyle = '#069';
                ctx.font = '15px Arial';
                ctx.fillText('PrimeSender \uD83D\uDE80 fp', 2, 15);
                ctx.fillStyle = 'rgba(102, 204, 0, 0.7)';
                ctx.font = '18px Times New Roman';
                ctx.fillText('PrimeSender \uD83D\uDE80 fp', 4, 45);
                // Arc for GPU path rendering
                ctx.beginPath();
                ctx.arc(50, 50, 50, 0, Math.PI * 2, true);
                ctx.closePath();
                ctx.fill();
                signals.push(canvas.toDataURL());
            }
        } catch (e) {
            signals.push('canvas-error');
        }

        // 2. WebGL Fingerprint
        try {
            const glCanvas = document.createElement('canvas');
            const gl = glCanvas.getContext('webgl') || glCanvas.getContext('experimental-webgl');
            if (gl) {
                const renderer = gl.getParameter(gl.RENDERER) || '';
                const vendor = gl.getParameter(gl.VENDOR) || '';
                const version = gl.getParameter(gl.VERSION) || '';
                const shadingVer = gl.getParameter(gl.SHADING_LANGUAGE_VERSION) || '';
                
                // UNMASKED values (more unique)
                let unmaskedRenderer = '';
                let unmaskedVendor = '';
                const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
                if (debugInfo) {
                    unmaskedRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || '';
                    unmaskedVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) || '';
                }
                
                signals.push(`webgl:${vendor}|${renderer}|${version}|${shadingVer}|${unmaskedVendor}|${unmaskedRenderer}`);
                
                // Max texture size (varies by GPU)
                signals.push(`maxtex:${gl.getParameter(gl.MAX_TEXTURE_SIZE)}`);
                signals.push(`maxvtx:${gl.getParameter(gl.MAX_VERTEX_ATTRIBS)}`);
            }
        } catch (e) {
            signals.push('webgl-error');
        }

        // 3. Screen + Hardware Constants
        signals.push(`screen:${screen.width}x${screen.height}x${screen.colorDepth}`);
        signals.push(`dpr:${window.devicePixelRatio}`);
        signals.push(`cores:${navigator.hardwareConcurrency || 0}`);
        signals.push(`platform:${navigator.platform}`);
        signals.push(`tz:${Intl.DateTimeFormat().resolvedOptions().timeZone}`);
        signals.push(`lang:${navigator.language}`);

        // 4. Hash all signals into a single SHA-256
        const raw = signals.join('|||');
        const encoder = new TextEncoder();
        const hashBuffer = await crypto.subtle.digest('SHA-256', encoder.encode(raw));
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('').toUpperCase();
        
        // Return first 32 chars for a compact but unique fingerprint
        return hashHex.substring(0, 32);
    }

    async function init() {
        try {
            const fingerprint = await generateFingerprint();
            
            // Store locally for persistence
            localStorage.setItem('ps_hw_fingerprint', fingerprint);
            
            // Post to Content Script world
            window.postMessage({
                type: 'PS_FINGERPRINT',
                fingerprint: fingerprint
            }, '*');
            
            console.log('🔏 Hardware Fingerprint Generated:', fingerprint.substring(0, 8) + '...');
        } catch (err) {
            console.error('🔏 Fingerprint generation failed:', err);
            // Post null fingerprint — trial will still work, just without HW binding
            window.postMessage({
                type: 'PS_FINGERPRINT',
                fingerprint: null
            }, '*');
        }
    }

    // Run immediately
    init();
})();
