/**
 * Relatedly Admin - Settings Page JS
 *
 * Handles toggle labels, theme setting visibility, previews, color pickers,
 * enhanced selects, tooltips, and dismissible sidebar boxes.
 *
 * @package Relatedly
 * @since   2.0.0
 * @since   2.3.0 Simplified for the native settings UI.
 */

( function ( $ ) {
	'use strict';

	function initDisplayToggleStatus() {
		var toggle = document.getElementById( 'relatedly-enabled' );
		var status = document.querySelector( '[data-relatedly-toggle-status]' );

		if ( ! toggle || ! status ) {
			return;
		}

		function update() {
			var strings = window.relatedlyAdmin.strings || {};
			if ( toggle.checked ) {
				status.classList.remove( 'is-inactive' );
				status.textContent = strings.active || 'Active';
			} else {
				status.classList.add( 'is-inactive' );
				status.textContent = strings.inactive || 'Inactive';
			}
		}

		toggle.addEventListener( 'change', update );
		update();
	}

	function updateThemeSettings( selectId, prefix ) {
		var select = document.getElementById( selectId );
		if ( ! select ) {
			return;
		}

		function update() {
			document.querySelectorAll( '[id^="' + prefix + '"]' ).forEach( function ( element ) {
				element.classList.toggle( 'relatedly-is-hidden', element.id !== prefix + select.value );
			} );
		}

		select.addEventListener( 'change', update );
		update();
	}

	function loadThemePreview( context, themeKey, $container ) {
		if ( ! $container.length ) {
			return;
		}

		$container.html( '<span class="spinner is-active relatedly-inline-spinner"></span>' );

		$.post( window.relatedlyAdmin.ajaxUrl, {
			action:    'relatedly_theme_preview',
			nonce:     window.relatedlyAdmin.nonce,
			context:   context,
			theme_key: themeKey,
		}, function ( response ) {
			if ( response.success ) {
				$container.html( response.data.html );
				return;
			}

			$container.html(
				'<p class="relatedly-preview-error">' +
				( response.data.message || 'Preview failed.' ) +
				'</p>'
			);
		} );
	}

	function initThemePreviewTriggers() {
		$( '#inline_theme' ).on( 'change', function () {
			loadThemePreview( 'inline', $( this ).val(), $( '#relatedly-inline-preview' ) );
		} );

		$( '#end_content_theme' ).on( 'change', function () {
			loadThemePreview( 'end_content', $( this ).val(), $( '#relatedly-end-content-preview' ) );
		} );

		$( '#floating_sidebar_variant' ).on( 'change', function () {
			loadThemePreview( 'floating', $( this ).val(), $( '#relatedly-floating-preview' ) );
		} );
	}

	function initColorPickers() {
		$( '.relatedly-color-picker' ).each( function () {
			var $input = $( this );
			$input.wpColorPicker( {
				change: function ( event, ui ) {
					$input.val( ui.color.toString() ).trigger( 'change' );
				},
				clear: function () {
					$input.val( '' ).trigger( 'change' );
				},
			} );
		} );
	}

	function initChoices() {
		if ( typeof window.Choices === 'undefined' ) {
			return;
		}

		document.querySelectorAll( '.relatedly-choices' ).forEach( function ( element ) {
			new window.Choices( element, {
				searchEnabled:    true,
				itemSelectText:   '',
				shouldSort:       false,
				removeItemButton: true,
				placeholder:      true,
				placeholderValue: element.dataset.placeholder || '',
				position:          'bottom',
			} );
		} );
	}

	function initTooltips() {
		if ( typeof window.tippy === 'undefined' ) {
			return;
		}

		document.querySelectorAll( '[data-tippy-content]' ).forEach( function ( element ) {
			window.tippy( element, { placement: 'right', arrow: true } );
		} );
	}

	function initDismissButtons() {
		$( document ).on( 'click', '.relatedly-dismiss-box', function ( event ) {
			event.preventDefault();

			var $button = $( this );

			$.post( window.relatedlyAdmin.ajaxUrl, {
				action: 'relatedly_dismiss_box',
				nonce:  window.relatedlyAdmin.nonce,
				box:    $button.data( 'box' ),
				type:   $button.data( 'type' ) || 'permanent',
			}, function () {
				$button.closest( '.relatedly-sidebar-box' ).fadeOut( 300 );
			} );
		} );
	}

	$( function () {
		initDisplayToggleStatus();
		updateThemeSettings( 'inline_theme', 'relatedly-inline-settings-' );
		updateThemeSettings( 'end_content_theme', 'relatedly-end-settings-' );
		initThemePreviewTriggers();
		initColorPickers();
		initChoices();
		initTooltips();
		initDismissButtons();
	} );
} )( jQuery );
