/**
 * Smart Product Sort — Admin UI.
 *
 * @package Smart_Product_Sort
 */

/* global spsortData, jQuery */
( function ( $ ) {
	'use strict';

	var $overlay = $( '#spsort-modal-overlay' );
	var $form    = $( '#spsort-rule-form' );
	var $notice  = $( '#spsort-notice' );
	var $saveBtn = $( '#spsort-save-btn' );

	// ── Helpers ───────────────────────────────────────────────────────────

	/**
	 * Display a notice using safe DOM construction (no .html()).
	 *
	 * @param {string} message Notice text.
	 * @param {string} type    'success' or 'error'.
	 */
	function showNotice( message, type ) {
		var $p = $( '<p>' ).text( message );

		$notice
			.empty()
			.removeClass( 'notice-success notice-error' )
			.addClass( 'notice-' + type )
			.append( $p )
			.show();

		$( 'html, body' ).animate( { scrollTop: $notice.offset().top - 40 }, 300 );
	}

	function openModal( title ) {
		$( '#spsort-modal-title' ).text( title );
		$overlay.show();
		$( '#spsort-rule-name' ).trigger( 'focus' );
	}

	function closeModal() {
		$overlay.hide();
		$form[ 0 ].reset();
		$( '#spsort-rule-id' ).val( '' );
		$( '#spsort-is-active' ).prop( 'checked', true );
	}

	function reloadPage() {
		window.location.reload();
	}

	// ── Add rule ──────────────────────────────────────────────────────────

	$( '#spsort-add-rule' ).on(
		'click',
		function () {
			openModal( spsortData.i18n.addSortRule );
		}
	);

	// ── Edit rule ─────────────────────────────────────────────────────────

	$( document ).on(
		'click',
		'.spsort-edit-rule',
		function () {
			var rule = $( this ).data( 'rule' );

			$( '#spsort-rule-id' ).val( rule.id );
			$( '#spsort-rule-name' ).val( rule.rule_name );
			$( '#spsort-sort-by' ).val( rule.sort_by );
			$( '#spsort-sort-order' ).val( rule.sort_order );
			$( '#spsort-category' ).val( rule.category_id || '' );
			$( '#spsort-priority' ).val( rule.priority );
			$( '#spsort-is-active' ).prop( 'checked', '1' === String( rule.is_active ) );

			openModal( spsortData.i18n.editSortRule );
		}
	);

	// ── Close modal ───────────────────────────────────────────────────────

	$( '#spsort-cancel-btn, #spsort-cancel-btn-footer' ).on( 'click', closeModal );

	$overlay.on(
		'click',
		function ( e ) {
			if ( $( e.target ).is( '#spsort-modal-overlay' ) ) {
				closeModal();
			}
		}
	);

	$( document ).on(
		'keydown',
		function ( e ) {
			if ( 27 === e.which ) {
				closeModal();
			}
		}
	);

	// ── Save rule (create / update) ───────────────────────────────────────

	$form.on(
		'submit',
		function ( e ) {
			e.preventDefault();

			var $name = $( '#spsort-rule-name' );
			if ( '' === $.trim( $name.val() ) ) {
				$name.trigger( 'focus' );
				return;
			}

			$saveBtn.text( spsortData.i18n.saving ).prop( 'disabled', true );

			$.post(
				spsortData.ajaxUrl,
				{
					action     : 'spsort_save_rule',
					nonce      : spsortData.nonce,
					rule_id    : $( '#spsort-rule-id' ).val(),
					rule_name  : $( '#spsort-rule-name' ).val(),
					sort_by    : $( '#spsort-sort-by' ).val(),
					sort_order : $( '#spsort-sort-order' ).val(),
					category_id: $( '#spsort-category' ).val(),
					priority   : $( '#spsort-priority' ).val(),
					is_active  : $( '#spsort-is-active' ).is( ':checked' ) ? 1 : 0,
				}
			)
			.done(
				function ( res ) {
					if ( res.success ) {
							showNotice( res.data.message, 'success' );
							closeModal();
							reloadPage();
					} else {
						showNotice( res.data.message, 'error' );
					}
				}
			)
			.fail(
				function () {
					showNotice( spsortData.i18n.error, 'error' );
				}
			)
			.always(
				function () {
					$saveBtn.text( spsortData.i18n.saveRule ).prop( 'disabled', false );
				}
			);
		}
	);

	// ── Delete rule ───────────────────────────────────────────────────────

	$( document ).on(
		'click',
		'.spsort-delete-rule',
		function () {
			if ( ! window.confirm( spsortData.i18n.confirmDelete ) ) {
				return;
			}

			var $btn = $( this );
			var id   = $btn.data( 'id' );

			$btn.prop( 'disabled', true );

			$.post(
				spsortData.ajaxUrl,
				{
					action  : 'spsort_delete_rule',
					nonce   : spsortData.nonce,
					rule_id : id,
				}
			)
			.done(
				function ( res ) {
					if ( res.success ) {
							$btn.closest( 'tr' ).fadeOut(
								300,
								function () {
									$( this ).remove();
									if ( 0 === $( '#spsort-rules-body tr' ).length ) {
										var $div = $( '<div>' ).addClass( 'spsort-empty-state' );
										$div.append( $( '<p>' ).text( spsortData.i18n.noRules ) );
										var $td = $( '<td>' ).attr( 'colspan', '7' ).append( $div );
										var $tr = $( '<tr>' ).attr( 'id', 'spsort-no-rules' ).append( $td );
										$( '#spsort-rules-body' ).append( $tr );
									}
								}
							);
							showNotice( res.data.message, 'success' );
					} else {
						showNotice( res.data.message, 'error' );
						$btn.prop( 'disabled', false );
					}
				}
			)
			.fail(
				function () {
					showNotice( spsortData.i18n.error, 'error' );
					$btn.prop( 'disabled', false );
				}
			);
		}
	);

	// ── Toggle rule ───────────────────────────────────────────────────────

	$( document ).on(
		'click',
		'.spsort-toggle-rule',
		function () {
			var $btn = $( this );
			var id   = $btn.data( 'id' );

			$btn.prop( 'disabled', true );

			$.post(
				spsortData.ajaxUrl,
				{
					action  : 'spsort_toggle_rule',
					nonce   : spsortData.nonce,
					rule_id : id,
				}
			)
			.done(
				function ( res ) {
					if ( res.success ) {
							var active = 1 === res.data.is_active;
							$btn
						.toggleClass( 'spsort-active', active )
						.toggleClass( 'spsort-inactive', ! active )
						.text( active ? spsortData.i18n.active : spsortData.i18n.inactive );
							showNotice( res.data.message, 'success' );
					} else {
						showNotice( res.data.message, 'error' );
					}
				}
			)
			.fail(
				function () {
					showNotice( spsortData.i18n.error, 'error' );
				}
			)
			.always(
				function () {
					$btn.prop( 'disabled', false );
				}
			);
		}
	);

} )( jQuery );
