/**
 * Biscotti CMP — A/B Testing (local admin script)
 *
 * Create tests (with per-variant colour pickers / weights / position / type) via
 * create-ab-test, and start/stop/delete existing tests. All through the
 * authenticated admin-ajax proxy.
 *
 * @package Biscotti_CMP
 */
( function ( $ ) {
	'use strict';
	var cfg = window.biscottiAdmin || {};
	var i18n = cfg.i18n || {};
	function t( k, f ) { return i18n[ k ] || f; }
	var variantCount = 2;

	function proxy( action, payload ) {
		return $.ajax( {
			url: cfg.ajaxUrl, method: 'POST',
			data: { action: 'biscotti_proxy', nonce: cfg.nonce, proxy_action: action, payload: JSON.stringify( payload || {} ) }
		} );
	}

	function abStatus( msg, isError ) {
		var s = document.getElementById( 'ab-status' );
		if ( s ) { s.textContent = msg; s.style.color = isError ? '#dc2626' : '#16a34a'; }
	}

	function variantMarkup( idx ) {
		var dname = ( t( 'variant', 'Variant' ) + ' ' + ( idx + 1 ) ).replace( /"/g, '&quot;' );
		return '<div class="ab-variant" data-idx="' + idx + '">' +
			'<div class="biscotti-lw-grid-2">' +
			'<p class="biscotti-form-row"><label>' + t( 'variantName', 'Variant Name' ) + '</label><input type="text" class="biscotti-svc-input ab-vname" value="' + dname + '" /></p>' +
			'<p class="biscotti-form-row"><label>' + t( 'weight', 'Weight (%)' ) + '</label><input type="number" class="biscotti-svc-input ab-vweight" value="' + Math.floor( 100 / ( idx + 1 ) ) + '" min="1" max="100" /></p>' +
			'</div>' +
			'<div class="biscotti-lw-grid-2">' +
			'<p class="biscotti-form-row"><label>' + t( 'primaryColor', 'Primary Color' ) + '</label><input type="color" class="ab-vcolor" value="#' + Math.floor( Math.random() * 16777215 ).toString( 16 ).padStart( 6, '0' ) + '" style="width:100%;height:40px;padding:4px;border:1px solid #cbd5e1;border-radius:6px;box-sizing:border-box;" /></p>' +
			'<p class="biscotti-form-row"><label>' + t( 'borderRadius', 'Border Radius (px)' ) + '</label><input type="number" class="biscotti-svc-input ab-vradius" value="12" min="0" max="50" /></p>' +
			'</div>' +
			'<div class="biscotti-lw-grid-2">' +
			'<p class="biscotti-form-row"><label>' + t( 'position', 'Position' ) + '</label><select class="biscotti-svc-input ab-vposition"><option value="bottom-center">' + t( 'posBottomCenter', 'Bottom Center' ) + '</option><option value="bottom-left">' + t( 'posBottomLeft', 'Bottom Left' ) + '</option><option value="bottom-right">' + t( 'posBottomRight', 'Bottom Right' ) + '</option><option value="top-center">' + t( 'posTopCenter', 'Top Center' ) + '</option><option value="center">' + t( 'posCenterModal', 'Center (Modal)' ) + '</option></select></p>' +
			'<p class="biscotti-form-row"><label>' + t( 'variantType', 'Type' ) + '</label><select class="biscotti-svc-input ab-vtype"><option value="bar">' + t( 'typeBar', 'Bar' ) + '</option><option value="modal">' + t( 'typeModal', 'Modal' ) + '</option><option value="corner">' + t( 'typeCorner', 'Corner' ) + '</option><option value="floating">' + t( 'typeFloating', 'Floating' ) + '</option></select></p>' +
			'</div>' +
			'<p><button type="button" class="button ab-remove-variant" style="color:#b91c1c;">✕ ' + t( 'remove', 'Remove' ) + '</button></p>' +
			'</div>';
	}

	function collectVariants() {
		var variants = [];
		$( '.ab-variant' ).each( function () {
			var name = $( this ).find( '.ab-vname' ).val().trim();
			if ( ! name ) { return; }
			variants.push( {
				name: name,
				weight: parseInt( $( this ).find( '.ab-vweight' ).val(), 10 ) || 50,
				config: {
					color: $( this ).find( '.ab-vcolor' ).val(),
					borderRadius: parseInt( $( this ).find( '.ab-vradius' ).val(), 10 ) || 12,
					position: $( this ).find( '.ab-vposition' ).val(),
					type: $( this ).find( '.ab-vtype' ).val()
				}
			} );
		} );
		return variants;
	}

	function actionThenReload( action, payload, confirmMsg, $btn ) {
		if ( confirmMsg && ! window.confirm( confirmMsg ) ) { return; }
		var orig = $btn.text();
		$btn.prop( 'disabled', true ).text( '⏳' );
		proxy( action, payload )
			.done( function ( res ) {
				if ( res && res.success ) { window.location.reload(); }
				else { $btn.prop( 'disabled', false ).text( orig ); if ( window.BiscottiAdmin ) { BiscottiAdmin.showToast( 'error', ( res && res.data ) || t( 'error', 'Error' ) ); } }
			} )
			.fail( function () { $btn.prop( 'disabled', false ).text( orig ); if ( window.BiscottiAdmin ) { BiscottiAdmin.showToast( 'error', t( 'connectionError', 'Connection error' ) ); } } );
	}

	$( function () {
		$( '#ab-create-btn' ).on( 'click', function () { $( '#ab-form' ).show(); $( this ).hide(); } );
		$( '#ab-cancel' ).on( 'click', function () { $( '#ab-form' ).hide(); $( '#ab-create-btn' ).show(); } );

		$( '#ab-add-variant' ).on( 'click', function () {
			if ( variantCount >= 5 ) { window.alert( t( 'maxVariants', 'Maximum 5 variants.' ) ); return; }
			$( '#ab-variants' ).append( variantMarkup( variantCount ) );
			variantCount++;
		} );
		$( document ).on( 'click', '.ab-remove-variant', function () { $( this ).closest( '.ab-variant' ).remove(); variantCount--; } );

		$( '#ab-submit' ).on( 'click', function () {
			var name = $( '#ab-name' ).val().trim();
			if ( ! name ) { abStatus( '❌ ' + t( 'testNameRequired', 'Test name is required.' ), true ); return; }
			var variants = collectVariants();
			if ( variants.length < 2 ) { abStatus( '❌ ' + t( 'twoVariants', 'At least 2 variants are required.' ), true ); return; }
			var $btn = $( this );
			$btn.prop( 'disabled', true );
			abStatus( t( 'saving', 'Saving…' ) );
			proxy( 'create-ab-test', { name: name, variants: variants } )
				.done( function ( res ) {
					$btn.prop( 'disabled', false );
					if ( res && res.success ) { abStatus( '✅ ' + t( 'saved', 'Created!' ) ); setTimeout( function () { window.location.reload(); }, 1200 ); }
					else { abStatus( '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true ); }
				} )
				.fail( function () { $btn.prop( 'disabled', false ); abStatus( '❌ ' + t( 'connectionError', 'Connection error' ), true ); } );
		} );

		$( document ).on( 'click', '.ab-start', function () { actionThenReload( 'start-ab-test', { testId: $( this ).data( 'testId' ) }, t( 'confirmStart', 'Start this A/B test?' ), $( this ) ); } );
		$( document ).on( 'click', '.ab-stop', function () { actionThenReload( 'stop-ab-test', { testId: $( this ).data( 'testId' ) }, t( 'confirmStop', 'Stop this A/B test?' ), $( this ) ); } );
		$( document ).on( 'click', '.ab-delete', function () { actionThenReload( 'delete-ab-test', { testId: $( this ).data( 'testId' ) }, t( 'confirmDeleteTest', 'Delete this A/B test? This cannot be undone.' ), $( this ) ); } );
	} );
} )( jQuery );
