<?php
/**
 * Deactivation Feedback Functionality
 *
 * Handles deactivation feedback form customization, validation, and UI enhancements.
 *
 * @since   4.4.1
 * @package Extra_Product_Options_For_WooCommerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Customize deactivation feedback reasons and add required text field to ALL options.
 *
 * @since 4.4.1
 *
 * @param array  $reasons Array of deactivation reasons.
 * @param object $fs      Freemius instance.
 *
 * @return array Modified reasons array.
 */
add_filter( 'fs_deactivation_feedback_reason', 'epofw_customize_deactivation_reasons', 10, 2 );

/**
 * Customize deactivation feedback reasons.
 *
 * @since 4.4.1
 *
 * @param array  $reasons Array of deactivation reasons.
 * @param object $fs      Freemius instance.
 *
 * @return array Modified reasons array.
 */
function epofw_customize_deactivation_reasons( $reasons, $fs ) {

	if ( $fs->get_slug() !== 'extra-product-options-for-woocommerce' ) {
		return $reasons;
	}

	// Exclude reasons that already have input fields.
	$excluded_reasons = array( 'other', 'better-plugin', 'found-better-plugin' );

	// Add required text input to reasons (except excluded ones).
	foreach ( $reasons as $key => &$reason ) {
		// Skip if this reason is excluded (they already have input fields).
		if ( in_array( $key, $excluded_reasons, true ) ) {
			continue;
		}

		// Set input type to textfield for all other reasons.
		$reason['input_type'] = 'textfield';

		// Set meaningful placeholder based on reason type, or use default.
		if ( ! isset( $reason['placeholder'] ) || empty( $reason['placeholder'] ) ) {
			switch ( $key ) {
				case 'broken':
				case '4':
					$reason['placeholder'] = __( 'Example: White screen error, PHP fatal error, or specific issue you encountered...', 'extra-product-options-for-woocommerce' );
					break;
				case 'plugin-suddenly-stopped-working':
				case '5':
					$reason['placeholder'] = __( 'Example: Plugin was working yesterday but stopped today, or specific error message...', 'extra-product-options-for-woocommerce' );
					break;
				case 'temporary-deactivation':
				case '15':
					$reason['placeholder'] = __( 'Example: Testing site speed, checking plugin conflicts, or specific issue you\'re investigating...', 'extra-product-options-for-woocommerce' );
					break;
				case 'no-longer-needed':
				case '1':
					$reason['placeholder'] = __( 'Example: Changed business model, no longer selling products, or specific reason...', 'extra-product-options-for-woocommerce' );
					break;
				case '3':
					$reason['placeholder'] = __( 'Example: One-time project completed, temporary need fulfilled, or specific duration...', 'extra-product-options-for-woocommerce' );
					break;
				default:
					$reason['placeholder'] = __( 'Please provide more details about your reason for deactivating...', 'extra-product-options-for-woocommerce' );
					break;
			}
		} else {
			// Remove asterisk from placeholder (we add it to label instead).
			$reason['placeholder'] = str_replace( ' *', '', $reason['placeholder'] );
			$reason['placeholder'] = str_replace( '*', '', $reason['placeholder'] );
		}

		// Mark as required.
		$reason['required'] = true;
	}
	unset( $reason ); // Unset reference.

	// Add new "How we can improve" reason with textarea.
	$reasons['how-can-we-improve'] = array(
		'id'          => 'how-can-we-improve',
		'text'        => __( 'How we can improve our plugin', 'extra-product-options-for-woocommerce' ),
		'input_type'  => 'textarea',
		'placeholder' => __( 'Example: Add new features, improve performance, better documentation, or any suggestions...', 'extra-product-options-for-woocommerce' ),
		'required'    => true,
	);

	return $reasons;
}

/**
 * Validate deactivation feedback form data - make text field compulsory.
 *
 * Note: This filter may not exist in all Freemius versions.
 * If it doesn't work, the JavaScript validation will handle it.
 *
 * @since 4.4.1
 *
 * @param array  $form_data Form data submitted.
 * @param object $fs        Freemius instance.
 *
 * @return array|WP_Error Validated form data or WP_Error if validation fails.
 */
add_filter( 'fs_deactivation_feedback_form_data', 'epofw_validate_deactivation_feedback', 10, 2 );

/**
 * Validate deactivation feedback form data.
 *
 * @since 4.4.1
 *
 * @param array  $form_data Form data submitted.
 * @param object $fs        Freemius instance.
 *
 * @return array|WP_Error Validated form data or WP_Error if validation fails.
 */
function epofw_validate_deactivation_feedback( $form_data, $fs ) {

	if ( $fs->get_slug() !== 'extra-product-options-for-woocommerce' ) {
		return $form_data;
	}

	// Check if reason_id is set and feedback text is empty.
	if ( isset( $form_data['reason_id'] ) && ! empty( $form_data['reason_id'] ) ) {
		$feedback_text = isset( $form_data['reason_info'] ) ? trim( $form_data['reason_info'] ) : '';

		if ( empty( $feedback_text ) ) {
			return new WP_Error(
				'epofw_feedback_required',
				__( 'Please provide feedback. The feedback field is required to help us improve the plugin.', 'extra-product-options-for-woocommerce' )
			);
		}
	}

	return $form_data;
}

/**
 * Add JavaScript and CSS to make deactivation feedback text field required.
 *
 * @since 4.4.1
 */
add_action( 'admin_footer', 'epofw_deactivation_feedback_scripts' );

/**
 * Enqueue deactivation feedback scripts and styles.
 *
 * @since 4.4.1
 */
function epofw_deactivation_feedback_scripts() {
	$screen = get_current_screen();

	// Only add script on plugins page.
	if ( ! $screen || 'plugins' !== $screen->id ) {
		return;
	}

	// Get translatable strings for JavaScript.
	$js_strings = array(
		'error'                    => __( 'Error:', 'extra-product-options-for-woocommerce' ),
		'feedback_required'        => __( 'Please provide feedback. The feedback field is required to help us improve the plugin.', 'extra-product-options-for-woocommerce' ),
		'select_reason'            => __( 'Please select a reason for deactivating.', 'extra-product-options-for-woocommerce' ),
		'feedback_required_short'  => __( 'Please provide feedback. The feedback field is required.', 'extra-product-options-for-woocommerce' ),
		'feedback_in_field'        => __( 'Please provide feedback in the text field.', 'extra-product-options-for-woocommerce' ),
		'heading_text'             => __( 'Your feedback helps us improve! Please share why you\'re deactivating:', 'extra-product-options-for-woocommerce' ),
		'placeholder_broke'        => __( 'Example: White screen error, PHP fatal error, or specific issue you encountered...', 'extra-product-options-for-woocommerce' ),
		'placeholder_stopped'      => __( 'Example: Plugin was working yesterday but stopped today, or specific error message...', 'extra-product-options-for-woocommerce' ),
		'placeholder_temporary'    => __( 'Example: Testing site speed, checking plugin conflicts, or specific issue you\'re investigating...', 'extra-product-options-for-woocommerce' ),
		'placeholder_no_longer'    => __( 'Example: Changed business model, no longer selling products, or specific reason...', 'extra-product-options-for-woocommerce' ),
		'placeholder_short_period' => __( 'Example: One-time project completed, temporary need fulfilled, or specific duration...', 'extra-product-options-for-woocommerce' ),
		'placeholder_improve'      => __( 'Example: Add new features, improve performance, better documentation, or any suggestions...', 'extra-product-options-for-woocommerce' ),
		'placeholder_default'      => __( 'Please provide more details about your reason for deactivating...', 'extra-product-options-for-woocommerce' ),
	);

	?>
	<style type="text/css">
		.fs-modal .button-primary:disabled,
		.fs-modal .button-primary.disabled,
		.fs-modal button[type="submit"]:disabled,
		.fs-modal button.button-primary:disabled,
		.fs-modal button.button-primary.disabled {
			opacity: 0.5 !important;
			cursor: not-allowed !important;
			pointer-events: none !important;
			background-color: #ccc !important;
			border-color: #ccc !important;
		}

		.fs-modal .button-primary:disabled:hover,
		.fs-modal .button-primary.disabled:hover,
		.fs-modal button[type="submit"]:disabled:hover,
		.fs-modal button.button-primary:disabled:hover,
		.fs-modal button.button-primary.disabled:hover {
			opacity: 0.5 !important;
			cursor: not-allowed !important;
		}

		.fs-modal .reason-input input[type="text"]::placeholder,
		.fs-modal .reason-input textarea::placeholder {
			color: #999 !important;
			opacity: 1 !important;
		}

		.fs-modal .reason-input input[type="text"]::-webkit-input-placeholder,
		.fs-modal .reason-input textarea::-webkit-input-placeholder {
			color: #999 !important;
			opacity: 1 !important;
		}

		.fs-modal .reason-input input[type="text"]::-moz-placeholder,
		.fs-modal .reason-input textarea::-moz-placeholder {
			color: #999 !important;
			opacity: 1 !important;
		}

		.fs-modal .reason-input input[type="text"]:-ms-input-placeholder,
		.fs-modal .reason-input textarea:-ms-input-placeholder {
			color: #999 !important;
			opacity: 1 !important;
		}
	</style>
	<script type="text/javascript">
		jQuery( document ).ready( function ( $ ) {
			var formValidationAdded = false;
			var epofwStrings        = <?php echo wp_json_encode( $js_strings ); ?>;

			// Function to update submit button state (globally accessible).
			function updateSubmitButtonState () {
				// Try multiple selectors to find the submit button.
				var $submitButton = $( '.fs-modal .button-primary, .fs-modal button.button-primary, .fs-modal button[type="submit"], .fs-modal .fs-modal-footer .button-primary, .fs-modal .fs-modal-footer button, .fs-modal input[type="submit"]' );

				if ( $submitButton.length === 0 ) {
					return; // Button not found yet.
				}

				var $selectedReason = $( '.fs-modal input[name="selected-reason"]:checked' );

				if ( $selectedReason.length === 0 ) {
					// No reason selected - disable button.
					$submitButton.prop( 'disabled', true ).addClass( 'disabled' );
					return;
				}

				var reasonValue     = $selectedReason.val();
				var excludedReasons = ['other', 'better-plugin', 'found-better-plugin'];

				// If excluded reason, let Freemius handle it (enable button).
				if ( excludedReasons.indexOf( reasonValue ) !== -1 ) {
					$submitButton.prop( 'disabled', false ).removeClass( 'disabled' );
					return;
				}

				// Check if input field has value - check both our custom input AND Freemius native input.
				var $selectedLi = $selectedReason.closest( 'li.reason' );
				// Check for our custom input fields first.
				var $inputField = $selectedLi.find( '.reason-input input[type="text"], .reason-input textarea' );

				// If no custom input, check for Freemius native input fields.
				if ( $inputField.length === 0 ) {
					$inputField = $selectedLi.find( 'input[type="text"], textarea, input[type="hidden"] + input[type="text"]' );
				}

				// Also check for any input/textarea directly in the li.reason element.
				if ( $inputField.length === 0 ) {
					$inputField = $selectedLi.find( 'input, textarea' ).not( 'input[type="radio"]' );
				}

				if ( $inputField.length > 0 ) {
					var feedbackValue = $inputField.val().trim();
					if ( feedbackValue === '' ) {
						// Force disable button.
						$submitButton.prop( 'disabled', true ).addClass( 'disabled' );
						$submitButton.attr( 'disabled', 'disabled' );
					} else {
						$submitButton.prop( 'disabled', false ).removeClass( 'disabled' );
						$submitButton.removeAttr( 'disabled' );
					}
				} else {
					// Input field doesn't exist yet - disable button.
					$submitButton.prop( 'disabled', true ).addClass( 'disabled' );
					$submitButton.attr( 'disabled', 'disabled' );
				}
			}

			function ensureAllReasonsHaveInput () {
				// Excluded reasons that already have input fields.
				var excludedReasons = ['other', 'better-plugin', 'found-better-plugin'];

				// Ensure reason list items have input fields (except excluded ones).
				$( '.fs-modal li.reason' ).each( function () {
					var $li         = $( this );
					var $radio      = $li.find( 'input[name="selected-reason"]' );
					var reasonValue = $radio.val();

					// Skip if this reason is excluded (they already have input fields).
					if ( excludedReasons.indexOf( reasonValue ) !== -1 ) {
						return; // Skip this reason.
					}

					var $reasonInput = $li.find( '.reason-input' );

					// If this reason doesn't have an input field, add one.
					if ( $reasonInput.length === 0 ) {
						// Get meaningful placeholder based on reason type.
						var placeholder = $li.data( 'input-placeholder' );

						// If no placeholder from data attribute, set context-specific placeholders.
						if ( ! placeholder ) {
							var $labelSpan = $li.find( 'label span' ).last();
							var reasonText = (
								$labelSpan.length > 0 && $labelSpan.text()
							) ? $labelSpan.text().toLowerCase() : '';

							// Map reason values and text to meaningful placeholders.
							if ( reasonValue === '4' || (
								reasonText && (
												reasonText.indexOf( 'broke' ) !== -1 || reasonText.indexOf( 'broke my site' ) !== -1
											)
							) ) {
								placeholder = epofwStrings.placeholder_broke;
							} else if ( reasonValue === '5' || (
								reasonText && (
												reasonText.indexOf( 'suddenly stopped' ) !== -1 || reasonText.indexOf( 'stopped working' ) !== -1
											)
							) ) {
								placeholder = epofwStrings.placeholder_stopped;
							} else if ( reasonValue === '15' || (
								reasonText && (
												reasonText.indexOf( 'temporary' ) !== -1 || reasonText.indexOf( 'troubleshooting' ) !== -1
											)
							) ) {
								placeholder = epofwStrings.placeholder_temporary;
							} else if ( reasonValue === '1' || (
								reasonText && reasonText.indexOf( 'no longer need' ) !== -1
							) ) {
								placeholder = epofwStrings.placeholder_no_longer;
							} else if ( reasonValue === '3' || (
								reasonText && reasonText.indexOf( 'short period' ) !== -1
							) ) {
								placeholder = epofwStrings.placeholder_short_period;
							} else if ( reasonValue === 'how-can-we-improve' || (
								reasonText && reasonText.indexOf( 'improve' ) !== -1
							) ) {
								placeholder = epofwStrings.placeholder_improve;
							} else {
								placeholder = epofwStrings.placeholder_default;
							}
						}

						// Check if this is the "how-can-we-improve" option (use textarea).
						var inputType = 'text';
						var inputTag  = '<input type="text" maxlength="200" placeholder="' + placeholder + '">';

						// Get reason text again for textarea check (with safety check).
						var $labelSpanCheck = $li.find( 'label span' ).last();
						var reasonTextCheck = (
							$labelSpanCheck.length > 0 && $labelSpanCheck.text()
						) ? $labelSpanCheck.text().toLowerCase() : '';

						// Check if reason value matches "how-can-we-improve" or text contains "improve".
						if ( reasonValue === 'how-can-we-improve' || (
							reasonTextCheck && reasonTextCheck.indexOf( 'improve' ) !== -1
						) ) {
							inputType = 'textarea';
							inputTag  = '<textarea rows="4" maxlength="500" placeholder="' + placeholder + '"></textarea>';
						}

						// Add the input field structure (hidden initially).
						var $inputDiv = $( '<div class="reason-input" style="display: none;"><span class="message"></span>' + inputTag + '</div>' );
						$li.append( $inputDiv );

						// Mark as having input.
						$li.addClass( 'has-input' );
						$li.attr( 'data-input-type', inputType === 'textarea' ? 'textarea' : 'textfield' );
					} else {
						// Hide existing input fields initially (unless this reason is selected).
						if ( ! $radio.is( ':checked' ) ) {
							$reasonInput.hide();
						}
					}
				} );
			}

			function updateModalHeading () {
				// Update the modal heading to be more friendly and encouraging.
				var $heading     = $( '.fs-modal h3, .fs-modal .fs-modal-panel h3, .fs-modal-panel h3 strong' );
				var headingTexts = [
					'If you have a moment, please let us know why you are deactivating:',
					'If you have a moment, please let us know why you are deactivating',
					'Why are you deactivating?',
					'Please let us know why you are deactivating:'
				];

				// Try multiple selectors to find the heading.
				var $possibleHeadings = $( '.fs-modal h3, .fs-modal .fs-modal-panel h3, .fs-modal-panel h3 strong, .fs-modal strong' );

				$possibleHeadings.each( function () {
					var $h          = $( this );
					var currentText = $h.text().trim();

					// Check if this is the heading we want to change.
					if ( headingTexts.indexOf( currentText ) !== -1 ||
						currentText.toLowerCase().indexOf( 'why you are deactivating' ) !== -1 ||
						currentText.toLowerCase().indexOf( 'why you\'re deactivating' ) !== -1 ||
						(
							currentText.toLowerCase().indexOf( 'deactivating' ) !== -1 && currentText.length < 100
						) ) {
						// Update to more friendly and encouraging message.
						var newText = epofwStrings.heading_text;
						if ( $h.is( 'strong' ) ) {
							$h.text( newText );
						} else {
							$h.html( '<strong>' + newText + '</strong>' );
						}
					}
				} );
			}

			function setupFeedbackValidation () {
				// Update modal heading first.
				updateModalHeading();

				// First, ensure all reasons have input fields.
				ensureAllReasonsHaveInput();

				// Hide all custom input fields initially (exclude reasons that already have inputs).
				var excludedReasons = ['other', 'better-plugin', 'found-better-plugin'];
				$( '.fs-modal li.reason' ).each( function () {
					var $li         = $( this );
					var $radio      = $li.find( 'input[name="selected-reason"]' );
					var reasonValue = $radio.val();

					// Only hide our custom input fields, not excluded ones.
					if ( excludedReasons.indexOf( reasonValue ) === -1 ) {
						$li.find( '.reason-input' ).hide();
					}
				} );

				// If a reason is already selected, show its input field (if not excluded).
				var $selectedReason = $( '.fs-modal input[name="selected-reason"]:checked' );
				if ( $selectedReason.length > 0 ) {
					var reasonValue = $selectedReason.val();
					if ( excludedReasons.indexOf( reasonValue ) === -1 ) {
						var $selectedLi    = $selectedReason.closest( 'li.reason' );
						var $selectedInput = $selectedLi.find( '.reason-input' );
						if ( $selectedInput.length > 0 ) {
							$selectedInput.show();
						}
					}
				}

				// Find ALL feedback input fields and textareas in .reason-input divs (excluding excluded reasons).
				var excludedReasons = ['other', 'better-plugin', 'found-better-plugin'];
				var $feedbackInputs = $( '.fs-modal .reason-input input[type="text"], .fs-modal .reason-input textarea' );

				// Filter out excluded reasons.
				$feedbackInputs = $feedbackInputs.filter( function () {
					var $li         = $( this ).closest( 'li.reason' );
					var $radio      = $li.find( 'input[name="selected-reason"]' );
					var reasonValue = $radio.val();
					return excludedReasons.indexOf( reasonValue ) === -1;
				} );

				if ( $feedbackInputs.length > 0 ) {
					// Make all inputs and textareas required.
					$feedbackInputs.each( function () {
						var $input      = $( this );
						var $li         = $input.closest( 'li.reason' );
						var $label      = $li.find( 'label span' ).last();
						var $radio      = $li.find( 'input[name="selected-reason"]' );
						var reasonValue = $radio.val();

						$input.attr( 'required', 'required' );
						$input.attr( 'aria-required', 'true' );

						// Add required asterisk to the label (better position).
						if ( $label.length > 0 && $label.text().indexOf( '*' ) === -1 ) {
							$label.append( ' <span style="color: red; font-weight: bold; margin-left: 3px;">*</span>' );
						}

						// Ensure placeholder is set (if not already set or empty).
						var currentPlaceholder = $input.attr( 'placeholder' ) || '';
						if ( ! currentPlaceholder || currentPlaceholder.trim() === '' ) {
							// Set placeholder based on reason type.
							var $labelSpan = $li.find( 'label span' ).last();
							var reasonText = (
								$labelSpan.length > 0 && $labelSpan.text()
							) ? $labelSpan.text().toLowerCase() : '';

							if ( reasonValue === '4' || (
								reasonText && (
												reasonText.indexOf( 'broke' ) !== -1 || reasonText.indexOf( 'broke my site' ) !== -1
											)
							) ) {
								currentPlaceholder = epofwStrings.placeholder_broke;
							} else if ( reasonValue === '5' || (
								reasonText && (
												reasonText.indexOf( 'suddenly stopped' ) !== -1 || reasonText.indexOf( 'stopped working' ) !== -1
											)
							) ) {
								currentPlaceholder = epofwStrings.placeholder_stopped;
							} else if ( reasonValue === '15' || (
								reasonText && (
												reasonText.indexOf( 'temporary' ) !== -1 || reasonText.indexOf( 'troubleshooting' ) !== -1
											)
							) ) {
								currentPlaceholder = epofwStrings.placeholder_temporary;
							} else if ( reasonValue === '1' || (
								reasonText && reasonText.indexOf( 'no longer need' ) !== -1
							) ) {
								currentPlaceholder = epofwStrings.placeholder_no_longer;
							} else if ( reasonValue === '3' || (
								reasonText && reasonText.indexOf( 'short period' ) !== -1
							) ) {
								currentPlaceholder = epofwStrings.placeholder_short_period;
							} else if ( reasonValue === 'how-can-we-improve' || (
								reasonText && reasonText.indexOf( 'improve' ) !== -1
							) ) {
								currentPlaceholder = epofwStrings.placeholder_improve;
							} else {
								currentPlaceholder = epofwStrings.placeholder_default;
							}

							$input.attr( 'placeholder', currentPlaceholder );
						} else {
							// Remove asterisk from placeholder if present (cleaner).
							if ( currentPlaceholder.indexOf( ' *' ) !== -1 ) {
								$input.attr( 'placeholder', currentPlaceholder.replace( ' *', '' ) );
							} else if ( currentPlaceholder.indexOf( '*' ) !== -1 ) {
								$input.attr( 'placeholder', currentPlaceholder.replace( '*', '' ) );
							}
						}

						// Watch for input changes to enable/disable submit button.
						$input.on( 'input keyup paste change', function () {
							updateSubmitButtonState();
						} );
					} );

					// Also attach listeners to ALL input/textarea fields in the modal (including Freemius native ones).
					$( '.fs-modal li.reason input[type="text"], .fs-modal li.reason textarea' ).off( 'input.epofw-feedback keyup.epofw-feedback paste.epofw-feedback change.epofw-feedback' );
					$( '.fs-modal li.reason input[type="text"], .fs-modal li.reason textarea' ).on( 'input.epofw-feedback keyup.epofw-feedback paste.epofw-feedback change.epofw-feedback', function () {
						updateSubmitButtonState();
					} );

					// Initial button state update.
					updateSubmitButtonState();

					// Update button state when reason changes - check multiple times to catch delayed input field creation.
					$( document ).on( 'change', '.fs-modal input[name="selected-reason"]', function () {
						// Immediate check.
						updateSubmitButtonState();

						// Check again after short delay (input field might be created by Freemius).
						setTimeout( function () {
							updateSubmitButtonState();
						}, 100 );

						// Check again after longer delay (in case Freemius takes longer).
						setTimeout( function () {
							updateSubmitButtonState();
						}, 300 );

						// Check one more time after input field is shown.
						setTimeout( function () {
							updateSubmitButtonState();
						}, 500 );
					} );

					// Add validation on form submit (only once).
					if ( ! formValidationAdded ) {
						formValidationAdded = true;

						// Find the form or modal body using the first input or modal.
						var $firstInput = $feedbackInputs.first();
						var $form       = $firstInput.closest( 'form' );
						if ( $form.length === 0 ) {
							$form = $( '.fs-modal-body, .fs-modal-content, .fs-modal' ).first();
						}

						// Prevent form submission if button is disabled.
						if ( $form.length > 0 ) {
							$form.off( 'submit.epofw-feedback-form' );
							$form.on( 'submit.epofw-feedback-form', function ( e ) {
								var $submitButton = $( '.fs-modal .button-primary, .fs-modal button.button-primary, .fs-modal button[type="submit"]' );

								if ( $submitButton.length > 0 && (
									$submitButton.prop( 'disabled' ) || $submitButton.hasClass( 'disabled' )
								) ) {
									e.preventDefault();
									e.stopPropagation();
									e.stopImmediatePropagation();
									return false;
								}

								// Also check validation before allowing submit.
								var $selectedReason = $( '.fs-modal input[name="selected-reason"]:checked' );
								if ( $selectedReason.length === 0 ) {
									e.preventDefault();
									e.stopPropagation();
									e.stopImmediatePropagation();
									alert( epofwStrings.select_reason );
									return false;
								}

								var reasonValue     = $selectedReason.val();
								var excludedReasons = ['other', 'better-plugin', 'found-better-plugin'];

								if ( excludedReasons.indexOf( reasonValue ) === -1 ) {
									var $selectedLi = $selectedReason.closest( 'li.reason' );
									var $inputField = $selectedLi.find( '.reason-input input[type="text"], .reason-input textarea' );

									if ( $inputField.length > 0 ) {
										var feedbackValue = $inputField.val().trim();
										if ( feedbackValue === '' ) {
											e.preventDefault();
											e.stopPropagation();
											e.stopImmediatePropagation();
											alert( epofwStrings.feedback_required_short );
											$inputField.focus();
											return false;
										}
									}
								}
							} );
						}

						// Also listen to the submit button click and form submit.
						$( document ).off( 'click.epofw-feedback-submit', '.fs-modal .button-primary, .fs-modal button.button-primary, .fs-modal button[type="submit"]' );
						$( document ).on( 'click.epofw-feedback-submit', '.fs-modal .button-primary, .fs-modal button.button-primary, .fs-modal button[type="submit"]', function ( e ) {
							var $button = $( this );

							// If button is disabled, prevent submission.
							if ( $button.prop( 'disabled' ) || $button.hasClass( 'disabled' ) ) {
								e.preventDefault();
								e.stopPropagation();
								e.stopImmediatePropagation();
								return false;
							}

							// Check if any reason is selected.
							var $selectedReason = $( '.fs-modal input[name="selected-reason"]:checked' );

							if ( $selectedReason.length === 0 ) {
								// No reason selected - prevent submission.
								e.preventDefault();
								e.stopPropagation();
								e.stopImmediatePropagation();
								alert( epofwStrings.select_reason );
								return false;
							}

							var $selectedLi = $selectedReason.closest( 'li.reason' );
							var reasonValue = $selectedReason.val();

							// Excluded reasons that already have input fields - skip validation.
							var excludedReasons = ['other', 'better-plugin', 'found-better-plugin'];
							if ( excludedReasons.indexOf( reasonValue ) !== -1 ) {
								// This reason already has its own input field, let Freemius handle it.
								return true;
							}

							// Ensure this reason has input field (in case it wasn't added yet).
							ensureAllReasonsHaveInput();

							// Check for both input and textarea fields.
							var $inputField = $selectedLi.find( '.reason-input input[type="text"], .reason-input textarea' );

							// Make sure the input field is visible (show it if hidden).
							if ( $inputField.length > 0 && ! $inputField.closest( '.reason-input' ).is( ':visible' ) ) {
								$inputField.closest( '.reason-input' ).show();
							}

							// If input field exists (should exist for all reasons now).
							if ( $inputField.length > 0 ) {
								var feedbackValue = $inputField.val().trim();

								// If feedback is empty, prevent submission.
								if ( feedbackValue === '' ) {
									e.preventDefault();
									e.stopPropagation();
									e.stopImmediatePropagation();

									// Show error message.
									var $errorMsg = $( '<div class="epofw-feedback-error" style="margin: 10px 0; padding: 10px; background: #f8d7da; border-left: 4px solid #dc3545; border-radius: 4px;"><p style="margin: 0; color: #721c24;"><strong>' + epofwStrings.error + '</strong> ' + epofwStrings.feedback_required + '</p></div>' );

									// Remove existing error if any.
									$( '.epofw-feedback-error' ).remove();

									// Insert error before the reasons list or input field.
									var $reasonsList = $selectedLi.closest( '#reasons-list, ul' );
									if ( $reasonsList.length > 0 ) {
										$reasonsList.after( $errorMsg );
									} else {
										$inputField.closest( '.reason-input' ).before( $errorMsg );
									}

									// Highlight input field.
									$inputField.css( {
										'border-color' : '#dc3545',
										'border-width' : '2px'
									} );
									$inputField.focus();

									// Scroll to error.
									$( 'html, body' ).animate( {
										scrollTop : $errorMsg.offset().top - 100
									}, 300 );

									// Remove border color after input.
									$inputField.off( 'input.epofw-clear-error' );
									$inputField.on( 'input.epofw-clear-error', function () {
										$( this ).css( {
											'border-color' : '',
											'border-width' : ''
										} );
										$( '.epofw-feedback-error' ).fadeOut( 300, function () {
											$( this ).remove();
										} );
									} );

									return false;
								}
							} else {
								// Input field should exist but doesn't - this shouldn't happen, but validate anyway.
								// Force show the input field if it's hidden.
								if ( $selectedLi.find( '.reason-input' ).length === 0 || ! $selectedLi.find( '.reason-input' ).is( ':visible' ) ) {
									// Try to trigger the input field to appear.
									$selectedLi.addClass( 'has-input' );
									$selectedLi.attr( 'data-input-type', 'textfield' );

									// Wait a bit and check again.
									setTimeout( function () {
										var $newInput = $selectedLi.find( '.reason-input input[type="text"]' );
										if ( $newInput.length === 0 ) {
											// Still no input, show error.
											e.preventDefault();
											e.stopPropagation();
											alert( epofwStrings.feedback_in_field );
											return false;
										}
									}, 100 );
								}
							}
						} );
					}
				}
			}

			// Watch for when reason radio buttons are clicked (input field appears).
			$( document ).on( 'change', '.fs-modal input[name="selected-reason"]', function () {
				var reasonValue     = $( this ).val();
				var excludedReasons = ['other', 'better-plugin', 'found-better-plugin'];

				// Hide ALL custom input fields first (but not excluded ones - they handle themselves).
				$( '.fs-modal li.reason' ).each( function () {
					var $li           = $( this );
					var $radio        = $li.find( 'input[name="selected-reason"]' );
					var liReasonValue = $radio.val();

					// Only hide our custom input fields, not excluded ones.
					if ( excludedReasons.indexOf( liReasonValue ) === -1 ) {
						$li.find( '.reason-input' ).hide();
					}
				} );

				var $selectedLi = $( this ).closest( 'li.reason' );

				// Skip if this is an excluded reason (they handle their own input fields).
				if ( excludedReasons.indexOf( reasonValue ) === -1 ) {
					// Ensure this reason has input field.
					ensureAllReasonsHaveInput();

					// Show the input field for selected reason only.
					var $inputField = $selectedLi.find( '.reason-input' );
					if ( $inputField.length > 0 ) {
						// Ensure placeholder is set before showing.
						var $input = $inputField.find( 'input[type="text"], textarea' );
						if ( $input.length > 0 ) {
							var currentPlaceholder = $input.attr( 'placeholder' ) || '';
							if ( ! currentPlaceholder || currentPlaceholder.trim() === '' ) {
								// Set placeholder based on reason type.
								var $labelSpan = $selectedLi.find( 'label span' ).last();
								var reasonText = (
									$labelSpan.length > 0 && $labelSpan.text()
								) ? $labelSpan.text().toLowerCase() : '';

								if ( reasonValue === '4' || (
									reasonText && (
													reasonText.indexOf( 'broke' ) !== -1 || reasonText.indexOf( 'broke my site' ) !== -1
												)
								) ) {
									currentPlaceholder = epofwStrings.placeholder_broke;
								} else if ( reasonValue === '5' || (
									reasonText && (
													reasonText.indexOf( 'suddenly stopped' ) !== -1 || reasonText.indexOf( 'stopped working' ) !== -1
												)
								) ) {
									currentPlaceholder = epofwStrings.placeholder_stopped;
								} else if ( reasonValue === '15' || (
									reasonText && (
													reasonText.indexOf( 'temporary' ) !== -1 || reasonText.indexOf( 'troubleshooting' ) !== -1
												)
								) ) {
									currentPlaceholder = epofwStrings.placeholder_temporary;
								} else if ( reasonValue === '1' || (
									reasonText && reasonText.indexOf( 'no longer need' ) !== -1
								) ) {
									currentPlaceholder = epofwStrings.placeholder_no_longer;
								} else if ( reasonValue === '3' || (
									reasonText && reasonText.indexOf( 'short period' ) !== -1
								) ) {
									currentPlaceholder = epofwStrings.placeholder_short_period;
								} else if ( reasonValue === 'how-can-we-improve' || (
									reasonText && reasonText.indexOf( 'improve' ) !== -1
								) ) {
									currentPlaceholder = epofwStrings.placeholder_improve;
								} else {
									currentPlaceholder = epofwStrings.placeholder_default;
								}

								$input.attr( 'placeholder', currentPlaceholder );
							}
						}

						$inputField.show();
						setTimeout( function () {
							// Focus on input or textarea.
							var $focusElement = $inputField.find( 'input, textarea' );
							if ( $focusElement.length > 0 ) {
								$focusElement.focus();
							}
						}, 50 );
					}
				}

				setTimeout( function () {
					setupFeedbackValidation();
					// Update button state after validation setup.
					if ( typeof updateSubmitButtonState === 'function' ) {
						updateSubmitButtonState();
					}
				}, 100 );
			} );

			// Watch for modal appearance via mutation observer.
			if ( typeof MutationObserver !== 'undefined' ) {
				var observer = new MutationObserver( function ( mutations ) {
					mutations.forEach( function ( mutation ) {
						if ( mutation.addedNodes.length > 0 ) {
							$( mutation.addedNodes ).each( function () {
								var $node = $( this );
								if ( $node.hasClass( 'fs-modal' ) || $node.find( '.fs-modal' ).length > 0 || $node.hasClass( 'reason-input' ) ) {
									setTimeout( function () {
										updateModalHeading();
										setupFeedbackValidation();
										updateSubmitButtonState();
									}, 200 );
								}
							} );
						}

						// Also watch for attribute changes (when reason-input becomes visible).
						if ( mutation.type === 'attributes' && mutation.attributeName === 'style' ) {
							var $target = $( mutation.target );
							if ( $target.hasClass( 'reason-input' ) && $target.is( ':visible' ) ) {
								setTimeout( function () {
									setupFeedbackValidation();
									updateSubmitButtonState();
								}, 100 );
							}
						}
					} );
				} );

				observer.observe( document.body, {
					childList       : true,
					subtree         : true,
					attributes      : true,
					attributeFilter : ['style', 'class']
				} );
			}

			// Watch for click on deactivate button.
			$( document ).on( 'click', '.fs-deactivate-plugin, [data-plugin="extra-product-options-for-woocommerce/extra-product-options-for-woocommerce.php"] .deactivate a', function () {
				formValidationAdded = false;
				setTimeout( function () {
					// Update modal heading first.
					updateModalHeading();
					// Hide all input fields when modal first opens.
					$( '.fs-modal .reason-input' ).hide();
					setupFeedbackValidation();
					// Disable submit button initially.
					updateSubmitButtonState();
				}, 500 );
			} );

			// Check periodically when modal is visible - enforce button state.
			var checkInterval = setInterval( function () {
				if ( $( '.fs-modal' ).is( ':visible' ) ) {
					updateModalHeading();
					setupFeedbackValidation();

					// Continuously enforce button state (prevent Freemius from re-enabling).
					var $submitButton = $( '.fs-modal .button-primary, .fs-modal button.button-primary, .fs-modal button[type="submit"], .fs-modal input[type="submit"]' );
					if ( $submitButton.length > 0 ) {
						var $selectedReason = $( '.fs-modal input[name="selected-reason"]:checked' );

						if ( $selectedReason.length === 0 ) {
							// No reason selected - force disable.
							$submitButton.prop( 'disabled', true ).addClass( 'disabled' );
							$submitButton.attr( 'disabled', 'disabled' );
						} else {
							var reasonValue     = $selectedReason.val();
							var excludedReasons = ['other', 'better-plugin', 'found-better-plugin'];

							if ( excludedReasons.indexOf( reasonValue ) === -1 ) {
								// Check if feedback is provided - check both custom and Freemius native inputs.
								var $selectedLi = $selectedReason.closest( 'li.reason' );
								// Check for our custom input fields first.
								var $inputField = $selectedLi.find( '.reason-input input[type="text"], .reason-input textarea' );

								// If no custom input, check for Freemius native input fields.
								if ( $inputField.length === 0 ) {
									$inputField = $selectedLi.find( 'input[type="text"], textarea, input[type="hidden"] + input[type="text"]' );
								}

								// Also check for any input/textarea directly in the li.reason element.
								if ( $inputField.length === 0 ) {
									$inputField = $selectedLi.find( 'input, textarea' ).not( 'input[type="radio"]' );
								}

								if ( $inputField.length > 0 ) {
									var feedbackValue = $inputField.val().trim();
									if ( feedbackValue === '' ) {
										// Force disable if no feedback.
										$submitButton.prop( 'disabled', true ).addClass( 'disabled' );
										$submitButton.attr( 'disabled', 'disabled' );
									} else {
										// Enable only if feedback exists.
										$submitButton.prop( 'disabled', false ).removeClass( 'disabled' );
										$submitButton.removeAttr( 'disabled' );
									}
								} else {
									// Input field doesn't exist - force disable.
									$submitButton.prop( 'disabled', true ).addClass( 'disabled' );
									$submitButton.attr( 'disabled', 'disabled' );
								}
							}
						}
					}

					updateSubmitButtonState();
				}
			}, 200 ); // Check more frequently (every 200ms).

			// Clean up interval after 60 seconds (longer for modal interactions).
			setTimeout( function () {
				clearInterval( checkInterval );
			}, 60000 );
		} );
	</script>
	<?php
}

