/**
 * Coloris color picker initialization and Alpine component.
 *
 * Provides:
 * - `initColorPicker()` — global Coloris setup
 * - `colorField` Alpine component — self-contained, works with x-model
 *
 * @since 1.5.0
 */
import Coloris from '@melloware/coloris';



/**
 * Initialize Coloris globally and register the colorField Alpine component.
 */
export function initColorPicker( Alpine ) {
	Coloris.init();

	// Remove Coloris-created elements from tab order after DOM settles.
	requestAnimationFrame( () => {
		document.querySelectorAll( '.clr-field button, .clr-field input' ).forEach( ( el ) => {
			el.setAttribute( 'tabindex', '-1' );
		} );
	} );

	Coloris( {
		el: '.coloris-picker',
		theme: 'pill',
		themeMode: 'light',
		format: 'hex',
		alpha: false,
		formatToggle: false,
		wrap: false,
		margin: 8,
		selectInput: false,
		focusInput: false,
		onChange: ( color, input ) => {
			window.dispatchEvent( new CustomEvent( 'coloris:update', {
				detail: { color, inputId: input?.id || null },
			} ) );
		},
	} );

	// Register the self-contained colorField Alpine component.
	Alpine.data( 'colorField', () => ( {
		// x-modelable exposes `value` for x-model binding on the parent.
		value: '',
		_closingFromInput: false,

		init() {
			// Make `value` bindable via x-model on the parent element.
			this.$nextTick( () => {
				const colorInput = this.$refs.colorInput;
				if ( ! colorInput ) return;

				const pickerId = colorInput.id;

				// Listen for Coloris picker updates (drag/click), filtered by this picker's ID.
				this._onColorisUpdate = ( e ) => {
					if ( e.detail.inputId === pickerId ) {
						this.value = e.detail.color;
					}
				};
				window.addEventListener( 'coloris:update', this._onColorisUpdate );

				// On close, sync any hex typed directly into the popover's input.
				colorInput.addEventListener( 'close', () => {
					if ( this._closingFromInput ) {
						this._closingFromInput = false;
						return;
					}
					const pickerInput = document.querySelector( '#clr-color-value' );
					if ( pickerInput && pickerInput.value ) {
						this.value = pickerInput.value;
					}
				} );
			} );
		},

		/**
		 * Handle manual hex input from the visible text field.
		 */
		onInput( raw ) {
			raw = raw.replace( /[^0-9a-fA-F#]/g, '' );

			if ( ! raw.startsWith( '#' ) ) {
				raw = '#' + raw;
			}

			raw = '#' + raw.slice( 1 ).replace( /#/g, '' );

			if ( /^#[0-9a-fA-F]{6}$/.test( raw ) ) {
				this.value = raw.toLowerCase();
				this._closingFromInput = true;
				Coloris.close();
			}
		},

		destroy() {
			if ( this._onColorisUpdate ) {
				window.removeEventListener( 'coloris:update', this._onColorisUpdate );
			}
		},
	} ) );
}
