( function( $ ) {
	'use strict';

	var presets = window.pnlrdbColors && window.pnlrdbColors.presets ? window.pnlrdbColors.presets : {};
	var $overlay = $( '#ap773-theme-modal-overlay' );
	var currentPreset = null;

	/* --- Modale tema --- */
	$( document ).on( 'click', '.ap773-preset-card', function(e) {
		e.preventDefault(); e.stopPropagation();
		var key = $( this ).data( 'preset' );
		var preset = presets[ key ];
		if ( ! preset ) { return; }
		currentPreset = key;
		var p = preset.preview;
		$( '#ap773-modal-preview-sidebar' ).css( 'background', p[0] );
		$( '#ap773-modal-preview-sidebar .line.active' ).css( 'background', p[1] );
		$( '#ap773-modal-preview-content' ).css( 'background', p[2] );
		$( '#ap773-modal-preview-content .block:first-child' ).css( 'color', p[1] );
		$( '#ap773-modal-name' ).text( preset.name );
		$( '#ap773-modal-desc' ).text( preset.description );
		var fHtml = '';
		$.each( preset.features, function( i, f ) { fHtml += '<li>' + $( '<span>' ).text(f).html() + '</li>'; } );
		$( '#ap773-modal-features' ).html( fHtml );
		var $apply = $( '#ap773-modal-apply' );
		if ( preset.is_reset ) {
			$apply.addClass('is-reset').text('' + (window.pnlrdbColors ? window.pnlrdbColors.i18n.resetDefault : '') + '');
		} else {
			$apply.removeClass('is-reset').text('' + (window.pnlrdbColors ? window.pnlrdbColors.i18n.applyTheme : '') + '');
		}
		$overlay.addClass('is-open');
		$('body').css('overflow','hidden');
	} );

	function closeModal() {
		$overlay.removeClass('is-open');
		$('body').css('overflow','');
		currentPreset = null;
	}
	$( '#ap773-modal-cancel' ).on('click', function(e){ e.preventDefault(); e.stopPropagation(); closeModal(); });
	$overlay.on('click', function(e){ if ($( e.target ).is($overlay)) { closeModal(); } });
	$( document ).on('keydown', function(e){ if (e.key==='Escape' && $overlay.hasClass('is-open')) { closeModal(); } });

	$( '#ap773-modal-apply' ).on('click', function(e) {
		e.preventDefault(); e.stopPropagation();
		if (!currentPreset) { return; }
		var $btn = $(this);
		$btn.prop('disabled',true).css('opacity','.7');
		$.post( pnlrdb.ajax_url, {
			action: 'pnlrdb_apply_theme_preset',
			nonce:  pnlrdb.nonce,
			preset: currentPreset
		}, function(res) {
			if (res.success) {
				closeModal();
				$('#ap773-preset-name').text(res.data.name);
				$('#ap773-preset-feedback').show();
				setTimeout(function(){ window.location.reload(); }, 1000);
			} else {
				$btn.prop('disabled',false).css('opacity','1');
			}
		});
	});

	/* --- Dark mode toggle --- */
	$( '#ap773-dm-toggle' ).on('change', function() {
		var isOn = $(this).is(':checked');
		$('#ap773-dm-label').text(isOn
			? '' + (window.pnlrdbColors ? window.pnlrdbColors.i18n.darkModeOn : '') + ''
			: '' + (window.pnlrdbColors ? window.pnlrdbColors.i18n.lightMode : '') + ''
		);
		$.post( pnlrdb.ajax_url, {
			action: 'pnlrdb_toggle_dark_mode',
			nonce:  pnlrdb.nonce,
			value:  isOn ? 'on' : 'off'
		}, function(res) { if (res.success) { window.location.reload(); } });
	});

	/* --- Live preview colori --- */
	function hexToRgb( hex ) {
		hex = ( hex || '' ).replace( '#', '' );
		if ( hex.length === 3 ) {
			hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
		}
		return {
			r: parseInt( hex.substring( 0, 2 ), 16 ) || 0,
			g: parseInt( hex.substring( 2, 4 ), 16 ) || 0,
			b: parseInt( hex.substring( 4, 6 ), 16 ) || 0
		};
	}

	function luminance( hex ) {
		var rgb = hexToRgb( hex );
		function channel( value ) {
			value = value / 255;
			return value <= 0.03928 ? value / 12.92 : Math.pow( ( value + 0.055 ) / 1.055, 2.4 );
		}
		return 0.2126 * channel( rgb.r ) + 0.7152 * channel( rgb.g ) + 0.0722 * channel( rgb.b );
	}

	function contrastRatio( a, b ) {
		var l1 = luminance( a );
		var l2 = luminance( b );
		var light = Math.max( l1, l2 );
		var dark  = Math.min( l1, l2 );
		return ( light + 0.05 ) / ( dark + 0.05 );
	}

	function bestTextColor( background ) {
		return contrastRatio( background, '#ffffff' ) >= contrastRatio( background, '#1d2327' ) ? '#ffffff' : '#1d2327';
	}

	function mixColors( colorA, colorB, ratio ) {
		var a = hexToRgb( colorA );
		var b = hexToRgb( colorB );
		return '#' + [ 'r', 'g', 'b' ].map( function( key ) {
			var value = Math.round( a[ key ] + ( ( b[ key ] - a[ key ] ) * ratio ) );
			var hex = value.toString( 16 );
			return hex.length === 1 ? '0' + hex : hex;
		} ).join( '' );
	}

	function updatePreview( primary, sidebar, textColor ) {
		primary   = primary   || '#2271b1';
		sidebar   = sidebar   || '#1d2327';
		textColor = textColor || '#2c3338';

		var btnText  = bestTextColor( primary );
		var menuText = bestTextColor( sidebar );

		$( '#ap773-color-btn' ).val( btnText );
		$( '#ap773-preview-sidebar' ).css( 'background', sidebar );
		$( '#ap773-preview-dot' ).css( 'background', primary );
		$( '#ap773-preview-active-item' ).css({
			'background': mixColors( sidebar, primary, 0.22 ),
			'border-color': mixColors( sidebar, primary, 0.44 )
		});
		$( '#ap773-preview-active-dot' ).css( 'background', primary );
		$( '#ap773-preview-link' ).css( 'color', primary );
		$( '#ap773-preview-text' ).css( 'color', textColor );
		$( '#ap773-preview-btn' ).css({
			'background': primary,
			'color': btnText
		});
		$( '#ap773-preview-sidebar .line' ).css( 'background', mixColors( menuText, sidebar, 0.72 ) );
		$( '#ap773-preview-sidebar .line.active' ).css( 'background', menuText );
	}

	/* Bind the preview to the color pickers after wpColorPicker is initialized */
	$( document ).ready(function() {
		setTimeout(function() {
			function getVal(id) {
				var $el = $(id);
				// prova prima il valore del campo hidden del color picker
				var wp  = $el.closest('.wp-picker-container').find('.wp-color-picker-' + $el.attr('id').replace('ap773-color-','') );
				return $el.val() || '';
			}

			function refresh() {
				updatePreview(
					$('#ap773-color-primary').val(),
					$('#ap773-color-sidebar').val(),
					$('#ap773-color-text').val()
				);
			}

			/* Ascolta i cambiamenti dai color picker */
			$('#ap773-color-primary, #ap773-color-sidebar, #ap773-color-text, #ap773-color-btn')
				.on('change input', refresh);

			/* Ascolta anche l'evento del wpColorPicker */
			$('.ap773-color-input').on('irischange', refresh);
		}, 300);
	});

} )( jQuery );
