/**
 * AIEO shared admin colour picker.
 *
 * ONE control across every AIEO config page (unification): instead of each
 * module calling `wpColorPicker()` on its own class, they all enqueue this and
 * it initialises a union of the legacy classes + the canonical `.aieo-color`.
 *
 * Adds RGBA / alpha (transparency) WITHOUT patching Iris: wp-color-picker owns
 * the hue/hex; a small opacity slider beside it adds the alpha channel. The
 * field stores a plain hex when fully opaque, or `rgba(r,g,b,a)` otherwise —
 * both are valid CSS, and AIEO_Admin_Color::sanitize() accepts either on save.
 *
 * Opt a field OUT of alpha with `data-aieo-alpha="no"`.
 *
 * @package ai-eshop-optimizer
 */
( function ( $ ) {
	'use strict';

	// Every legacy per-module class + the canonical .aieo-color.
	var SELECTOR = [
		'.aieo-color',
		'.aieo-dmm-btn-color', '.aieo-nav-color', '.aieo-cmp-color',
		'.aieo-dmm-bg-color', '.aieo-dmm-compl-color', '.aieo-dmm-fs-color',
		'.aieo-dmm-pn-color', '.aieo-dmm-ratings-color'
	].join( ',' );

	function clamp( n, lo, hi ) {
		n = parseInt( n, 10 );
		if ( isNaN( n ) ) { n = lo; }
		return Math.max( lo, Math.min( hi, n ) );
	}
	function h2( n ) { n = ( n & 255 ).toString( 16 ); return n.length < 2 ? '0' + n : n; }
	function rgbToHex( r, g, b ) { return '#' + h2( r ) + h2( g ) + h2( b ); }
	function hexToRgb( hex ) {
		hex = ( hex || '' ).replace( '#', '' );
		if ( hex.length === 3 ) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; }
		if ( ! /^[0-9a-fA-F]{6}$/.test( hex ) ) { return null; }
		return { r: parseInt( hex.slice( 0, 2 ), 16 ), g: parseInt( hex.slice( 2, 4 ), 16 ), b: parseInt( hex.slice( 4, 6 ), 16 ) };
	}
	function parseColor( str ) {
		str = ( str || '' ).trim();
		var m = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec( str );
		if ( m ) {
			var a = m[4] !== undefined ? parseFloat( m[4] ) : 1;
			if ( isNaN( a ) ) { a = 1; }
			return { hex: rgbToHex( clamp( m[1], 0, 255 ), clamp( m[2], 0, 255 ), clamp( m[3], 0, 255 ) ), alpha: Math.max( 0, Math.min( 1, a ) ) };
		}
		return { hex: str, alpha: 1 };
	}
	function combine( hex, alpha ) {
		if ( alpha >= 1 ) { return hex; }
		var rgb = hexToRgb( hex );
		if ( ! rgb ) { return hex; }
		return 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + ( Math.round( alpha * 100 ) / 100 ) + ')';
	}

	function initOne( input ) {
		var $input = $( input );
		if ( $input.data( 'aieoCp' ) || typeof $input.wpColorPicker !== 'function' ) { return; }
		$input.data( 'aieoCp', 1 );

		var allowAlpha = $input.attr( 'data-aieo-alpha' ) !== 'no'; // alpha on by default
		var parsed = parseColor( $input.val() );
		var state = { hex: parsed.hex || ( $input.attr( 'data-default-color' ) || '' ), alpha: parsed.alpha };
		var $slider = null, $label = null;

		function updateLabel() { if ( $label ) { $label.text( Math.round( state.alpha * 100 ) + '%' ); } }
		function writeValue() { $input.val( combine( state.hex, state.alpha ) ); }

		// Seed the field with the hex part so wp-color-picker can read it.
		$input.val( state.hex );

		$input.wpColorPicker( {
			change: function ( ev, ui ) {
				state.hex = ui.color ? ui.color.toString() : state.hex;
				writeValue();
			},
			clear: function () {
				state.hex = '';
				state.alpha = 1;
				if ( $slider ) { $slider.val( 100 ); }
				updateLabel();
				$input.val( '' );
			}
		} );

		if ( allowAlpha ) {
			var $wrap = $input.closest( '.wp-picker-container' );
			$slider = $( '<input type="range" min="0" max="100" step="1" class="aieo-cp-alpha" aria-label="Opacity" />' ).val( Math.round( state.alpha * 100 ) );
			$label = $( '<span class="aieo-cp-alpha-val" aria-hidden="true"></span>' );
			$( '<span class="aieo-cp-alpha-row"></span>' )
				.append( '<span class="aieo-cp-alpha-ico" aria-hidden="true">▦</span>' )
				.append( $slider )
				.append( $label )
				.appendTo( $wrap.length ? $wrap : $input.parent() );
			updateLabel();
			$slider.on( 'input change', function () {
				state.alpha = clamp( this.value, 0, 100 ) / 100;
				updateLabel();
				if ( ! state.hex ) { state.hex = $input.attr( 'data-default-color' ) || '#000000'; }
				writeValue();
			} );
			writeValue(); // reflect the combined value immediately
		}
	}

	function initAll( root ) {
		$( root || document ).find( SELECTOR ).each( function () { initOne( this ); } );
	}

	// Public API (so repeater rows added later can re-init).
	window.AIEOColorPicker = { init: initAll, initOne: initOne };

	$( function () { initAll( document ); } );

} )( jQuery );
