(function( $ ) {
	'use strict';
	/**
	 * Admin-facing JavaScript source
	 */

	/**
	 * Set the user's clipboard contents.
	 *
	 * @param string data: Text to copy to clipboard.
	 * @param object $el: jQuery element to trigger copy events on. (Default: document)
	 */

	function coSetClipboard( data, $el ) {
		if ( 'undefined' === typeof $el ) {
			$el = jQuery( document );
		}
		var $temp_input = jQuery( '<textarea style="opacity:0">' );
		jQuery( 'body' ).append( $temp_input );
		$temp_input.val( data ).select();

		$el.trigger( 'beforecopy' );
		try {
			document.execCommand( 'copy' );
			$el.trigger( 'aftercopy' );
		} catch ( err ) {
			console.log( err );
			$el.trigger( 'aftercopyfailure' );
		}

		$temp_input.remove();
	}

	/**
	 * Clear the user's clipboard.
	 */
	function coClearClipboard() {
		coSetClipboard( '' );
	}
	
	var coStatus = {
		// Track previous payment provider value
		previousPaymentProvider: null,

		// Initialize events.
		init: function() {
			$( document )
				.on( "click", ".copy-action-btn", this.copyShortcode )
				.on( 'click', 'a.help_tip, a.card-oracle-help-tip', this.preventTipTipClick )
				.on( 'click', 'a.debug-report', this.generateReport )
				.on( 'click', '#copy-for-support', this.copyReport )
				.on( 'click', '#demo_data_button', this.disableButton)
				.on( 'aftercopy', '#copy-for-support', this.copySuccess )
				.on( 'aftercopyfailure', '#copy-for-support', this.copyFail )
				.on( 'change', '#_co_question_layout', this.updateLayout)
				.on( 'click', '.card-oracle-layout-selector .layout-option', this.selectLayoutOption)
				.on( 'change', '#error_rows', this.submitErrorRows )
				.on( 'change', '#_co_deck_layout', this.toggleCircularDiameter)
				.on( 'change', '#card_oracle_payment_provider', this.togglePaymentProviderSections)
				.on( 'change', '#card_oracle_integration', this.toggleIntegrationSections);

			// Initialize circular diameter field visibility on page load
			this.initCircularDiameter();
			// Initialize payment provider sections on page load
			this.initPaymentProviderSections();
			// Initialize integration sections on page load
			this.initIntegrationSections();
		},

		// Copy Shortcodes to user clipboard.
		copyShortcode: function(e) {
			e.preventDefault();
			var copyText = this.value;
			
			// Try modern clipboard API first
			if (navigator.clipboard && window.isSecureContext) {
				navigator.clipboard.writeText(copyText).then(function() {
					// Success - could add visual feedback here
					console.log('Shortcode copied to clipboard');
				}).catch(function(err) {
					// Fallback to older method
					coStatus.fallbackCopyShortcode(copyText);
				});
			} else {
				// Fallback for older browsers or non-secure contexts
				coStatus.fallbackCopyShortcode(copyText);
			}
		},
		
		// Fallback copy method for older browsers
		fallbackCopyShortcode: function(copyText) {
			var $tempElement = $( "<input>" );
			$( "body" ).append( $tempElement );
			$tempElement.val( copyText ).select();
			try {
				document.execCommand( "copy" );
				console.log('Shortcode copied to clipboard (fallback)');
			} catch (err) {
				console.error('Failed to copy shortcode:', err);
			}
			$tempElement.remove();
		},
	
		/**
		 * Disable the the Demo Data button to prevent mulitple clicks.
		 */
		disableButton: function() {
			log.console( 'Disable Button' );
			setTimeout( function() {
				$( this ).prop( "disabled", true );
			}, 500);
		},

		/**
		 * Prevent anchor behavior when click on TipTip.
		 *
		 * @return {Bool}
		 */
		preventTipTipClick: function() {
			return false;
		},
		
		/**
		 * Update the Layout demo on the admin page to use the new display before having to save.
		 *
		 */
		updateLayout: function() {
			$( '#card-oracle-display-layout' ).attr( 'class', this.value );
		},

		/**
		 * Handle visual layout selector button click.
		 * Combines layout type (stacked/inline) with alignment (left/center/right).
		 */
		selectLayoutOption: function() {
			var $button = $( this );
			var $selector = $button.closest( '.card-oracle-layout-selector' );
			var $container = $button.closest( '.card-oracle-grid-content' );

			// Update selected state within this group only.
			$selector.find( '.layout-option' ).removeClass( 'selected' );
			$button.addClass( 'selected' );

			// Get current selections from both groups.
			var layoutType = $container.find( '[data-group="layout"] .layout-option.selected' ).data( 'value' ) || 'stacked';
			var alignment = $container.find( '[data-group="alignment"] .layout-option.selected' ).data( 'value' ) || 'left';

			// Build the combined value.
			var combinedValue;
			if ( layoutType === 'inline' ) {
				combinedValue = 'card-oracle-form-inline-' + alignment;
			} else {
				combinedValue = 'card-oracle-form-' + alignment;
			}

			// Update hidden input.
			$container.siblings( 'input[type="hidden"]' ).val( combinedValue );

			// Update the layout preview.
			$( '#card-oracle-display-layout' ).attr( 'class', combinedValue );
		},


		/**
		 * Toggle payment provider sections based on dropdown selection.
		 */
		togglePaymentProviderSections: function() {
			var newProvider = $( this ).val();
			var previousProvider = coStatus.previousPaymentProvider;

			// Check if switching from one provider to another (not from empty)
			if ( previousProvider && previousProvider !== newProvider && newProvider ) {
				// Check if the previous provider has any filled fields
				var hasFilledFields = coStatus.providerHasFilledFields( previousProvider );

				if ( hasFilledFields ) {
					var confirmMessage = coStatus.getProviderClearConfirmMessage( previousProvider );
					if ( ! confirm( confirmMessage ) ) {
						// User cancelled - revert to previous value
						$( this ).val( previousProvider );
						return;
					}
					// User confirmed - clear the previous provider's fields
					coStatus.clearProviderFields( previousProvider );
				}
			}

			coStatus.previousPaymentProvider = newProvider;
			coStatus.updatePaymentProviderSections( newProvider );
		},

		/**
		 * Check if a provider has any filled fields.
		 */
		providerHasFilledFields: function( provider ) {
			var fieldIds = coStatus.getProviderFieldIds( provider );
			var hasFilled = false;

			fieldIds.forEach( function( fieldId ) {
				var $field = $( '#' + fieldId );
				if ( $field.length ) {
					if ( $field.is( ':checkbox' ) || $field.is( ':radio' ) ) {
						if ( $field.is( ':checked' ) ) {
							hasFilled = true;
						}
					} else if ( $field.val() && $field.val().trim() !== '' ) {
						hasFilled = true;
					}
				}
			});

			return hasFilled;
		},

		/**
		 * Get field IDs for a payment provider.
		 */
		getProviderFieldIds: function( provider ) {
			if ( 'paypal' === provider ) {
				return [
					'card_oracle_paypal_email',
					'card_oracle_paypal_country',
					'card_oracle_paypal_sandbox'
				];
			} else if ( 'stripe' === provider ) {
				return [
					'card_oracle_stripe_live_secret_key',
					'card_oracle_stripe_live_publishable_key',
					'card_oracle_stripe_test_secret_key',
					'card_oracle_stripe_test_publishable_key',
					'card_oracle_stripe_sandbox'
				];
			}
			return [];
		},

		/**
		 * Get confirmation message for clearing provider fields.
		 */
		getProviderClearConfirmMessage: function( provider ) {
			if ( 'paypal' === provider ) {
				return 'Switching providers will clear your PayPal settings. Continue?';
			} else if ( 'stripe' === provider ) {
				return 'Switching providers will clear your Stripe settings. Continue?';
			}
			return 'Switching providers will clear the previous provider settings. Continue?';
		},

		/**
		 * Clear all fields for a payment provider.
		 */
		clearProviderFields: function( provider ) {
			var fieldIds = coStatus.getProviderFieldIds( provider );

			fieldIds.forEach( function( fieldId ) {
				var $field = $( '#' + fieldId );
				if ( $field.length ) {
					if ( $field.is( ':checkbox' ) || $field.is( ':radio' ) ) {
						$field.prop( 'checked', false );
					} else if ( $field.is( 'select' ) ) {
						$field.val( $field.find( 'option:first' ).val() );
					} else {
						$field.val( '' );
					}
				}
			});
		},

		/**
		 * Apply provider visibility state.
		 */
		updatePaymentProviderSections: function( provider ) {
			var $providerSelect = $( '#card_oracle_payment_provider' );
			if ( $providerSelect.length === 0 ) {
				return;
			}

			if ( 'undefined' === typeof provider ) {
				provider = $providerSelect.val();
			}

			// Find cards within the same form as the payment dropdown
			var $form = $providerSelect.closest( 'form' );
			var $cards = $form.find( '.co-settings-card[data-provider]' );

			$cards.removeClass( 'is-active' );
			if ( provider ) {
				$cards.filter( '[data-provider=\"' + provider + '\"]' ).addClass( 'is-active' );
			}
		},

		/**
		 * Initialize provider sections on page load.
		 */
		initPaymentProviderSections: function() {
			// Only run if provider cards exist on the page
			if ( $( '.co-settings-card[data-provider]' ).length > 0 ) {
				var $providerSelect = $( '#card_oracle_payment_provider' );
				if ( $providerSelect.length > 0 ) {
					// Store initial provider value
					coStatus.previousPaymentProvider = $providerSelect.val();
					coStatus.updatePaymentProviderSections( $providerSelect.val() );
				}
			}
		},

		/**
		 * Toggle integration provider sections based on dropdown selection.
		 */
		toggleIntegrationSections: function() {
			coStatus.updateIntegrationSections( $( this ).val() );
		},

		/**
		 * Apply provider visibility state for integrations.
		 */
		updateIntegrationSections: function( provider ) {
			var $integrationSelect = $( '#card_oracle_integration' );
			if ( $integrationSelect.length === 0 ) {
				return;
			}

			if ( 'undefined' === typeof provider ) {
				provider = $integrationSelect.val();
			}

			// Find cards within the same form as the integration dropdown
			var $form = $integrationSelect.closest( 'form' );
			var $cards = $form.find( '.co-settings-card[data-provider]' );

			$cards.removeClass( 'is-active' );
			if ( provider ) {
				$cards.filter( '[data-provider="' + provider + '"]' ).addClass( 'is-active' );
			}
		},

		/**
		 * Initialize integration sections on page load.
		 */
		initIntegrationSections: function() {
			// Only run if integration cards exist on the page
			if ( $( '.co-settings-card[data-provider]' ).length > 0 ) {
				var $integrationSelect = $( '#card_oracle_integration' );
				if ( $integrationSelect.length > 0 ) {
					coStatus.updateIntegrationSections( $integrationSelect.val() );
				}
			}
		},

		/**
		 * Toggle the circular diameter field visibility based on deck layout selection.
		 */
		toggleCircularDiameter: function() {
			var selectedLayout = this.value;
			var $circularField = $( '.circular-diameter-field' ).closest( '.card-oracle-grid-row' );
			
			if ( selectedLayout === 'circular' ) {
				$circularField.show();
			} else {
				$circularField.hide();
			}
		},

		/**
		 * Initialize circular diameter field visibility on page load.
		 */
		initCircularDiameter: function() {
			var selectedLayout = $( '#_co_deck_layout' ).val();
			var $circularField = $( '.circular-diameter-field' ).closest( '.card-oracle-grid-row' );
			
			if ( selectedLayout === 'circular' ) {
				$circularField.show();
			} else {
				$circularField.hide();
			}
		},

		/**
		 * Generate system status report.
		 *
		 * @return {Bool}
		 */
		generateReport: function() {
			var report = '';

			$( '.card_oracle_status_table thead, .card_oracle_status_table tbody' ).each( function() {
				if ( $( this ).is( 'thead' ) ) {
					var label = $( this ).find( 'th:eq(0)' ).data( 'export-label' ) || $( this ).text();
					report = report + '\n### ' + $.trim( label ) + ' ###\n\n';
				} else {
					$( 'tr', $( this ) ).each( function() {
						var label       = $( this ).find( 'td:eq(0)' ).data( 'export-label' ) || $( this ).find( 'td:eq(0)' ).text();
						var the_name    = $.trim( label ).replace( /(<([^>]+)>)/ig, '' ); // Remove HTML.

						// Find value
						var $value_html = $( this ).find( 'td:eq(2)' ).clone();
						$value_html.find( '.private' ).remove();
						$value_html.find( '.dashicons-yes' ).replaceWith( '&#10004;' );
						$value_html.find( '.dashicons-no-alt, .dashicons-warning' ).replaceWith( '&#10060;' );

						// Format value
						var the_value   = $.trim( $value_html.text() );
						var value_array = the_value.split( ', ' );

						if ( value_array.length > 1 ) {
							// If value have a list of plugins ','.
							// Split to add new line.
							var temp_line ='';
							$.each( value_array, function( key, line ) {
								temp_line = temp_line + line + '\n';
							});

							the_value = temp_line;
						}

						report = report + '' + the_name + ': ' + the_value + '\n';
					});
				}
			});

			try {
				// Try to open email client first
				var domain = $( this ).data( 'domain' ) || 'unknown-domain';
				var subject = 'Card Oracle system report for ' + domain;
				var body = encodeURIComponent( report );
				var mailtoLink = 'mailto:support@chillichalli.com?subject=' + encodeURIComponent( subject ) + '&body=' + body;
				
				// Attempt to open email client
				var emailWindow = window.open( mailtoLink );
				
				// Check if email client opened (this is not foolproof but provides some indication)
				setTimeout( function() {
					if ( emailWindow ) {
						emailWindow.close();
					}
					// Always show the fallback option
					$( '#debug-report' ).slideDown();
					$( '#debug-report' ).find( 'textarea' ).val( '`' + report + '`' ).focus().select();
					$( '.debug-report' ).fadeOut();
				}, 1000 );
				
				return false;
			} catch ( e ) {
				// Fallback to original behavior if email fails
				$( '#debug-report' ).slideDown();
				$( '#debug-report' ).find( 'textarea' ).val( '`' + report + '`' ).focus().select();
				$( this ).fadeOut();
				console.log( e );
			}

			return false;
		},

		/**
		 * Copy for report.
		 *
		 * @param {Object} evt Copy event.
		 */
		copyReport: function( evt ) {
			coClearClipboard();
			coSetClipboard( $( '#debug-report' ).find( 'textarea' ).val(), $( this ) );
			evt.preventDefault();
		},

		/**
		 * Display a "Copied!" tip when success copying
		 */
		copySuccess: function() {
			$( '.copy-success' ).removeClass( 'hidden' );
			$( '.copy-success' ).addClass( 'card-oracle-copy-visible' );
			$( '#debug-report' ).find( 'textarea' ).focus().select();
		},

		/**
		 * Displays the copy error message when failure copying.
		 */
		copyFail: function() {
			$( '.copy-error' ).removeClass( 'hidden' );
			$( '#debug-report' ).find( 'textarea' ).focus().select();
		},

		submitErrorRows: function() {
			$( "#error_rows_form" ).submit();
		}
	};

	// Wait for DOM to be ready before initializing
	$( document ).ready( function() {
		coStatus.init();
	});

})( jQuery );
