/**
 * Minimal IAB TCF v2.2 CMP API surface.
 *
 * Exposes window.__tcfapi with the standard command set so third-party
 * advertising scripts can probe consent. NOTE: This CMP is auto-declared
 * and NOT IAB-certified. The TC string emitted here is a simplified,
 * non-bit-perfect representation suitable for tag managers that read the
 * boolean purpose array, but not for strict TCF verifiers.
 */
( function () {
	'use strict';

	var listeners  = [];
	var nextId     = 1;
	var lastEvent  = null;

	function getTcData () {
		var c = ( window.blaminhor && window.blaminhor.consent && window.blaminhor.consent.all() ) || {};
		var hasMarketing = !! c.marketing;
		var hasStats     = !! c.statistics;
		var hasPrefs     = !! c.preferences;
		var status       = ( c.marketing !== undefined ) ? 'useractioncomplete' : 'cmpuishown';

		var purposes = {};
		for ( var i = 1; i <= 11; i++ ) {
			// Coarse mapping: purposes 1 = strictly necessary (always), 2-7 = marketing, 8-10 = stats.
			purposes[ i ] = ( i === 1 ) ? true
				: ( i >= 8 && i <= 10 ) ? hasStats
				: hasMarketing;
		}

		return {
			cmpId:             ( window.blaminhorCookiesConfig && window.blaminhorCookiesConfig.tcfCmpId )       || 999,
			cmpVersion:        1,
			gdprApplies:       true,
			tcfPolicyVersion:  4,
			cmpStatus:         'loaded',
			eventStatus:       status,
			isServiceSpecific: true,
			useNonStandardTexts: false,
			publisherCC:        'EU',
			purposeOneTreatment: false,
			listenerId:         null,
			purpose:            { consents: purposes, legitimateInterests: {} },
			vendor:             { consents: {}, legitimateInterests: {} },
			specialFeatureOptins: {},
			publisher:          { consents: purposes, legitimateInterests: {}, customPurpose: { consents: {}, legitimateInterests: {} } },
			tcString:           buildSimplifiedTcString( purposes )
		};
	}

	function buildSimplifiedTcString ( purposes ) {
		// Real TC strings are base64-encoded bitsets following a precise IAB schema;
		// our auto-declared CMP emits a marker prefix so vendor scripts can detect
		// our presence without claiming spec-perfect conformance.
		var bits = '';
		for ( var i = 1; i <= 11; i++ ) {
			bits += purposes[ i ] ? '1' : '0';
		}
		var pad = bits + '000000000000000';
		return 'CMP_NONCERT.' + pad;
	}

	window.__tcfapi = function ( command, version, callback ) {
		if ( typeof callback !== 'function' ) {
			return;
		}
		switch ( command ) {
			case 'ping':
				callback( {
					gdprApplies:        true,
					cmpLoaded:          true,
					cmpStatus:          'loaded',
					displayStatus:      'visible',
					apiVersion:         '2.2',
					cmpVersion:         1,
					cmpId:              ( window.blaminhorCookiesConfig && window.blaminhorCookiesConfig.tcfCmpId ) || 999,
					gvlVersion:         0,
					tcfPolicyVersion:   4
				}, true );
				break;
			case 'getTCData':
				callback( getTcData(), true );
				break;
			case 'addEventListener':
				var listenerId = nextId++;
				listeners.push( { id: listenerId, fn: callback } );
				var data = getTcData();
				data.listenerId = listenerId;
				lastEvent = data;
				callback( data, true );
				break;
			case 'removeEventListener':
				var rid = arguments[ 3 ];
				listeners = listeners.filter( function ( l ) { return l.id !== rid; } );
				callback( true, true );
				break;
			default:
				callback( null, false );
		}
	};

	// Notify listeners whenever consent changes.
	if ( window.blaminhor && window.blaminhor.consent ) {
		window.blaminhor.consent.onChange( function () {
			var data = getTcData();
			lastEvent = data;
			listeners.forEach( function ( l ) {
				try {
					var copy = JSON.parse( JSON.stringify( data ) );
					copy.listenerId = l.id;
					l.fn( copy, true );
				} catch ( e ) { /* swallow */ }
			} );
		} );
	}
} )();
