/**
 * Captain Widgets Kit — Deactivation Feedback Modal
 * assets/js/deactivate-feedback.js
 *
 * All API calls go through WordPress AJAX (admin-ajax.php) which then
 * proxies to the Captain Data remote server via wp_remote_post().
 *
 * AJAX actions:
 *   cwk_deactive_count  — count-only ping (Submit Like it / Skip & Deactivate)
 *   cwk_deactive_detail — full detail    (Submit Not Like it)
 *
 * Flow:
 *   Submit & Deactivate → wait for AJAX to complete → redirect
 *   Skip & Deactivate   → wait for count AJAX → close modal (no redirect)
 *   X / outside click   → close modal only, no API, no redirect
 */

( function ( $ ) {
	'use strict';

	$( document ).ready( function () {

		if ( typeof cwkDeactivate === 'undefined' ) {
			return;
		}

		var ajaxUrl        = cwkDeactivate.ajax_url;
		var nonce          = cwkDeactivate.nonce;
		var deactivateHref = '';

		/* ── Intercept the Deactivate Link ─────────────────────
		 * WordPress renders: tr[data-slug="captain-widgets-kit"]
		 *   > .deactivate > a
		 * ────────────────────────────────────────────────────── */
		$( document ).on(
			'click',
			'tr[data-slug="captain-widgets-kit"] .deactivate a',
			function ( e ) {
				e.preventDefault();
				deactivateHref = $( this ).attr( 'href' );
				openModal();
			}
		);

		/* ── Open / Close / Redirect ────────────────────────── */

		function openModal() {
			$( '#cwk-deactivate-overlay' ).fadeIn( 200 );
		}

		function closeModal() {
			$( '#cwk-deactivate-overlay' ).fadeOut( 150 );
		}

		function doRedirect() {
			window.location.href = deactivateHref;
		}

		/* X button — close modal only, no API, no redirect */
		$( document ).on( 'click', '#cwk-modal-close', function () {
			closeModal();
		} );

		/* Click outside modal — close modal only, no API, no redirect */
		$( document ).on( 'click', '#cwk-deactivate-overlay', function ( e ) {
			if ( $( e.target ).is( '#cwk-deactivate-overlay' ) ) {
				closeModal();
			}
		} );

		/* ── Thumb Toggle ───────────────────────────────────── */

		$( document ).on( 'click', '.cwk-thumb-btn', function () {
			$( '.cwk-thumb-btn' ).removeClass( 'cwk-thumb-active' );
			$( this ).addClass( 'cwk-thumb-active' );

			if ( $( this ).data( 'val' ) === 'notlike' ) {
				$( '#cwk-like-section' ).slideUp( 180 );
				$( '#cwk-reason-section' ).slideDown( 200 );
			} else {
				$( '#cwk-reason-section' ).slideUp( 180 );
				$( '#cwk-message-wrap' ).slideUp( 150 );
				$( 'input[name="cwk_reason"]' ).prop( 'checked', false );
				$( '.cwk-reason-label' ).removeClass( 'cwk-reason-selected' );
				$( '#cwk-message' ).val( '' );
				$( '#cwk-like-section' ).slideDown( 200 );
			}
		} );

		/* ── Radio Selection ────────────────────────────────── */

		$( document ).on( 'change', 'input[name="cwk_reason"]', function () {
			$( '.cwk-reason-label' ).removeClass( 'cwk-reason-selected' );
			$( this ).closest( '.cwk-reason-label' ).addClass( 'cwk-reason-selected' );

			if ( $( this ).val() === 'other' ) {
				$( '#cwk-message-wrap' ).slideDown( 180 );
			} else {
				$( '#cwk-message-wrap' ).slideUp( 150 );
				$( '#cwk-message' ).val( '' );
			}
		} );

		/* ── Submit Button ──────────────────────────────────── */

		$( document ).on( 'click', '#cwk-submit-btn', function () {
			var isNotLike = $( '#cwk-thumb-notlike' ).hasClass( 'cwk-thumb-active' );
			var message   = '';

			if ( isNotLike ) {
				var reason = $( 'input[name="cwk_reason"]:checked' ).val();
				if ( reason ) {
					message = ( reason === 'other' ) ? $.trim( $( '#cwk-message' ).val() ) : reason;
				}
			} else {
				message = $.trim( $( '#cwk-like-message' ).val() );
			}

			setLoading( '#cwk-submit-btn', true );

			// Wait for API to complete before redirecting so the call
			// is not aborted by a page unload.
			if ( isNotLike ) {
				$.when( ajaxCount(), ajaxDetail( message ) ).always( function () {
					doRedirect();
				} );
			} else {
				ajaxCount().always( function () {
					doRedirect();
				} );
			}
		} );

		/* ── Skip Button ────────────────────────────────────── */

		$( document ).on( 'click', '#cwk-skip-btn', function () {
			setLoading( '#cwk-skip-btn', true );

			// Wait for count API to complete before redirecting so the
			// call is not aborted by a page unload.
			ajaxCount().always( function () {
				doRedirect();
			} );
		} );

		/* ── WordPress AJAX Helpers ─────────────────────────── */

		/**
		 * Fire the count-only deactivation AJAX action.
		 * Maps to: wp_ajax_cwk_deactive_count
		 *
		 * @return {jqXHR}
		 */
		function ajaxCount() {
			return $.post( ajaxUrl, {
				action: 'cwk_deactive_count',
				nonce:  nonce,
			} );
		}

		/**
		 * Fire the full deactivation detail AJAX action.
		 * Maps to: wp_ajax_cwk_deactive_detail
		 *
		 * @param {string} message  Selected reason or custom text.
		 *
		 * @return {jqXHR}
		 */
		function ajaxDetail( message ) {
			return $.post( ajaxUrl, {
				action:  'cwk_deactive_detail',
				nonce:   nonce,
				message: message,
			} );
		}

		/**
		 * Toggle loading state on a button.
		 *
		 * @param {string}  selector  jQuery selector for the button.
		 * @param {boolean} state     True = disable; false = re-enable.
		 */
		function setLoading( selector, state ) {
			$( selector ).prop( 'disabled', state );
		}

	} );

} )( jQuery );
