/**
 * TrustLens browser fingerprint collector.
 *
 * Collects stable device signals, hashes them to a 22-char base64url
 * fingerprint, and writes the hash to a hidden form field (`_tl_fp`)
 * on the Classic WooCommerce checkout. Same hash is exposed as
 * window.__tlFingerprint for the Blocks integration to read.
 *
 * @since 1.3.0
 */
( function () {
	'use strict';

	function canvasHash() {
		try {
			var c = document.createElement( 'canvas' );
			c.width = 200;
			c.height = 50;
			var ctx = c.getContext( '2d' );
			if ( ! ctx ) { return ''; }
			ctx.textBaseline = 'top';
			ctx.font = '16px Arial';
			ctx.fillStyle = '#f60';
			ctx.fillRect( 10, 10, 100, 20 );
			ctx.fillStyle = '#069';
			ctx.fillText( 'TrustLens \u{1F512}', 15, 15 );
			return c.toDataURL();
		} catch ( e ) { return ''; }
	}

	function webglVendorRenderer() {
		try {
			var gl = document.createElement( 'canvas' ).getContext( 'webgl' );
			if ( ! gl ) { return ''; }
			var ext = gl.getExtension( 'WEBGL_debug_renderer_info' );
			if ( ! ext ) { return ''; }
			return gl.getParameter( ext.UNMASKED_VENDOR_WEBGL ) + '|' +
			       gl.getParameter( ext.UNMASKED_RENDERER_WEBGL );
		} catch ( e ) { return ''; }
	}

	function fontFingerprint() {
		try {
			var baseFonts = [ 'monospace', 'sans-serif', 'serif' ];
			var testFonts = [ 'Arial', 'Courier New', 'Georgia', 'Times New Roman', 'Verdana', 'Tahoma', 'Trebuchet MS', 'Impact', 'Comic Sans MS', 'Palatino', 'Garamond', 'Bookman' ];
			var span = document.createElement( 'span' );
			span.style.fontSize = '72px';
			span.innerHTML = 'mmmmmmmmmmlli';
			document.body.appendChild( span );
			var baseline = {};
			baseFonts.forEach( function ( base ) {
				span.style.fontFamily = base;
				baseline[ base ] = { w: span.offsetWidth, h: span.offsetHeight };
			} );
			var available = [];
			testFonts.forEach( function ( font ) {
				var detected = false;
				baseFonts.forEach( function ( base ) {
					span.style.fontFamily = '"' + font + '",' + base;
					if ( span.offsetWidth !== baseline[ base ].w || span.offsetHeight !== baseline[ base ].h ) {
						detected = true;
					}
				} );
				if ( detected ) {
					available.push( font );
				}
			} );
			document.body.removeChild( span );
			return available.join( '|' );
		} catch ( e ) { return ''; }
	}

	function collectSignals() {
		var screenPart = [
			screen.width, screen.height, window.devicePixelRatio || 1, screen.colorDepth
		].join( 'x' );

		var tz = '';
		try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch ( e ) {}

		var signals = [
			canvasHash(),
			screenPart,
			tz,
			navigator.language || '',
			navigator.platform || '',
			webglVendorRenderer()
		];

		// Pro-only signals — opt-in via a data-attribute the PHP enqueue adds.
		var script = document.currentScript || document.querySelector( 'script[data-tl-pro-fingerprint]' );
		if ( script && script.getAttribute( 'data-tl-pro-fingerprint' ) === '1' ) {
			signals.push( fontFingerprint() );
		}

		return signals.join( '||' );
	}

	function sha256Base64Url( input ) {
		var enc = new TextEncoder();
		return crypto.subtle.digest( 'SHA-256', enc.encode( input ) ).then( function ( buf ) {
			var bytes = new Uint8Array( buf ).slice( 0, 16 );
			var b64 = btoa( String.fromCharCode.apply( null, bytes ) );
			return b64.replace( /\+/g, '-' ).replace( /\//g, '_' ).replace( /=+$/, '' );
		} );
	}

	function computeFingerprint() {
		if ( ! ( window.crypto && window.crypto.subtle ) ) {
			return Promise.resolve( '' );
		}
		return sha256Base64Url( collectSignals() );
	}

	function injectHiddenField( hash ) {
		var form = document.querySelector( 'form.checkout, form.woocommerce-checkout' );
		if ( ! form ) { return; }
		var input = form.querySelector( 'input[name="_tl_fp"]' );
		if ( ! input ) {
			input = document.createElement( 'input' );
			input.type = 'hidden';
			input.name = '_tl_fp';
			form.appendChild( input );
		}
		input.value = hash;
	}

	computeFingerprint().then( function ( hash ) {
		if ( ! hash ) { return; }
		window.__tlFingerprint = hash;
		injectHiddenField( hash );
	} );
} )();
