/**
 * 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 like_it    = isNotLike ? 'not_like' : 'like';
			var message    = '';
			var issue_type = '';

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

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

			// Always call detail API (sends like_it, issue_type, message).
			// For "Not Like it" also call count. Wait for both before redirect.
			if ( isNotLike ) {
				$.when( ajaxCount(), ajaxDetail( like_it, message, issue_type ) ).always( function () {
					doRedirect();
				} );
			} else {
				ajaxDetail( like_it, message, issue_type ).always( function () {
					doRedirect();
				} );
			}
		} );

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

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

			// Skip = like, no message, no issue_type.
			ajaxDetail( 'like', '', '' ).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} like_it     'like' or 'not_like'.
		 * @param {string} message     Custom message or selected reason text.
		 * @param {string} issue_type  Selected reason value.
		 *
		 * @return {jqXHR}
		 */
		function ajaxDetail( like_it, message, issue_type ) {
			return $.post( ajaxUrl, {
				action:     'cwk_deactive_detail',
				nonce:      nonce,
				like_it:    like_it,
				message:    message,
				issue_type: issue_type,
			} );
		}

		/**
		 * 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 );
