jQuery( function( $ ) {
	let filenameValidationTimer = null;
	let filenameValidationXhr   = null;

	$( '#wpo-wcpdf-settings #filename' ).on( 'input', function() {
		let elem = $( this );
		let $row = elem.closest( 'tr' );
		let $td  = $row.find( 'td' );

		// Clear any pending validation
		if ( filenameValidationTimer ) {
			clearTimeout( filenameValidationTimer );
		}

		// Abort any pending AJAX request
		if ( filenameValidationXhr ) {
			filenameValidationXhr.abort();
			filenameValidationXhr = null;
		}

		// Clear existing warnings and spinner.
		$row.removeClass( 'setting-warning' ).find( '.filename-warning, .filename-validating' ).remove();

		// Validate after a short delay.
		filenameValidationTimer = setTimeout( function() {
			validateFilename( elem, $row, $td );
		}, 300 );

	} ).trigger('input');

	function validateFilename( elem, $row, $td ) {
		let filename          = elem.val();
		let document_type     = elem.closest( '#wpo-wcpdf-settings' ).find( "input[name='option_page']" ).val().replace("wpo_wcpdf_documents_settings_", "");
		let language          = elem.attr( 'name' ).replace("wpo_wcpdf_documents_settings_"+document_type+"[filename]", "").replace('[', '').replace(']', '');
		let filename_warnings = [];

		if ( filename.length === 0 ) {
			return;
		}

		// Check if one curly bracket is using instead of a pair
		// e.g. {order_number} or {{order_number} or {order_number}}
		let open_brace_count  = ( filename.match(/{/g) || [] ).length;
		let close_brace_count = ( filename.match(/}/g) || [] ).length;

		if ( open_brace_count % 2 !== 0 || close_brace_count % 2 !== 0 || open_brace_count !== close_brace_count ) {
			filename_warnings.push( wpo_wcpdf_pro_settings.incorrect_brace_warning );
		}
		// If no unique identifier is used, display unique identifier warning
		else if ( ! filename.match( /{{\s*[a-zA-Z_]+\s*}}/ ) ) {
			filename_warnings.push( wpo_wcpdf_pro_settings.unique_identifier_warning );
		}

		// Show spinner while checking for duplicates.
		$td.css( 'position', 'relative' );
		$td.append( '<span style="position: absolute; right: 0; top: 0;" class="filename-validating spinner is-active"></span>' );

		// Check for duplicate filenames (async)
		filenameValidationXhr = filename_existence_check( filename, document_type, language, function( duplicate_warning ) {
			// Remove spinner
			$row.find( '.filename-validating' ).remove();

			if ( duplicate_warning && duplicate_warning.length > 0 ) {
				filename_warnings.push( duplicate_warning );
			}

			// Show warnings if we have them
			if ( filename_warnings.length > 0 ) {
				$row.addClass( 'setting-warning' );
				$.each( filename_warnings, function( index, warning_text ) {
					$td.append( '<div class="notice notice-error inline notice-wpo filename-warning"><p>' + warning_text + '</p></div>' );
				} );
			}
		} );
	}

	// check if another document is using this filename
	function filename_existence_check( filename, document_type, language, callback ) {
		return $.ajax({
			url:  ajaxurl,
			data: {
				action:        'wcpdf_pro_filename_existence_check',
				nonce:         wpo_wcpdf_pro_settings.nonce,
				filename:      filename,
				document_type: document_type,
				language:      language,
			},
			type: 'POST',
			cache: false,
			success: function( response ) {
				callback( response.error );
			},
			error: function( xhr, status, error ) {
				// Don't log or callback if request was aborted
				if ( status === 'abort' ) {
					return;
				}
				console.log( error );
				callback( null );
			},
		});
	}

	// Disable 'Always use most current settings' checkbox when 'Keep PDF' is active
	// Check if keep PDF is active on page load
	if($('input#archive_pdf').prop("checked") == true){
		$( 'input#use_latest_settings' ).prop( 'disabled', true );
	}
	// Disable/enable 'Always use most current settings' checkbox when 'Keep PDF' checkbox changes
	$('input#archive_pdf').on('click', function(){
		if($(this).prop("checked") == true){
			$( 'input#use_latest_settings' ).prop( 'disabled', true );
		}
		else if($(this).prop("checked") == false){
			$( 'input#use_latest_settings' ).prop( 'disabled', false );
		}
	});

	// don't allow status selection  from 'auto_generate_for_statuses' if present in 'disable_for_statuses'
	$( '#wpo-wcpdf-settings #disable_for_statuses' ).on( 'change', function() {
		let disabled_statuses    = $( this ).val();
		let $enable_for_statuses = $( '#wpo-wcpdf-settings #auto_generate_for_statuses' );

		$.each( $enable_for_statuses.find( 'option' ), function( index, option ) {
			let disable_option_status = $.inArray( $( option ).val(), disabled_statuses ) !== -1;

			if( disable_option_status ) {
				if ( $( option ).is( ':selected' ) ) {
					$( option ).prop( 'selected', false );
				}
				$( option ).prop( 'disabled', true );
			} else {
				$( option ).prop( 'disabled', false );
			}
		} );

		$enable_for_statuses.selectWoo().trigger( 'change' );
	} ).trigger( 'change' );

	// Show disable for requirement field
	$('td').on('change', 'select#disable_for', function() { 
		let requirement = $(this).val();
		let $requirements_panel = $(this).next('.requirements');
		// Show panel
		$requirements_panel.show();
		// Show field
		$requirements_panel.find('div[data-requirement_id="' + requirement + '"]').show();
		// Disable selected value from dropdown
		$(this).find('option[value="' + requirement + '"]').prop('disabled', true);
		// Set to default
		$(this).val('');
		// Show or hide certain panel elements
		show_or_hide_requirement_panel_elements( $requirements_panel );
	});

	// Remove disable for requirement field
	$('select#disable_for').next('.requirements').on('click', '.remove-requirement', function() { 
		let $requirement = $(this).closest('div');
		let requirementId = $requirement.data('requirement_id');
		let $requirements_select = $(this).closest('td').find('select#disable_for');
		let $requirements_panel = $(this).closest('td').find('.requirements');
		// Clear select2
		$requirement.find('select').val('').trigger('change');
		// Hide restriction field
		$requirement.hide();
		// Enable restiction option in dropdown
		$requirements_select.find('option[value="' + requirementId + '"]').removeAttr('disabled');
		// Show or hide certain panel elements
		show_or_hide_requirement_panel_elements( $requirements_panel );
	});

	function show_or_hide_requirement_panel_elements( $requirements_panel ) {
		let active_requirements = 0;

		$('.requirement').each(function( index ) {
			if( $(this).data('requirement_id') !== 'disable_for_require' && $(this).is(':visible') ) {
				active_requirements++;
			}
		});

		if ( active_requirements === 0 ) {
			$requirements_panel.hide();
		} else if ( active_requirements === 1 ) {
			$requirements_panel.find('div[data-requirement_id="disable_for_require"]').hide();
		} else if ( active_requirements >= 2 ) {
			$requirements_panel.find('div[data-requirement_id="disable_for_require"]').show();
		}
	}

	// show/hide order number warning
	$( '[name="wpo_wcpdf_documents_settings_packing-slip[display_number]"], [name="wpo_wcpdf_documents_settings_proforma[display_number]"]' ).on( 'change', function ( event ) {
		if ( 'order_number' === $( this ).val() ) {
			$( this ).closest( 'td' ).find( '.description' ).slideDown();
			$( this ).closest( 'tr' ).next( 'tr' ).hide();
		} else {
			$( this ).closest( 'td' ).find( '.description' ).hide();
			$( this ).closest( 'tr' ).next( 'tr' ).show();
		}
	} ).trigger( 'change' );
	
	// add a click event listener to the unlink button to add the delete_refresh_token query parameter
	$( '#unlink-button' ).on( 'click', function( e ) {
		let unlink_url           = $( this ).attr( 'href' );
		let delete_refresh_token = $( '#delete_refresh_token' ).is( ':checked' ) ? '1' : '0';
		unlink_url              += '&delete_refresh_token=' + delete_refresh_token;
		$( this ).attr( 'href', unlink_url );
	} );
	
	// Copy content when copy button clicked.
	$( '.wpo-wcpdf-copy-button' ).on( 'click', function ( event ) {
		event.preventDefault();

		const $button     = $( this );
		const $copyValue  = $button.siblings( '.wpo-wcpdf-copy-value' );
		const copyText    = $copyValue.text();
		const buttonTitle = $button.attr( 'title' );

		navigator.clipboard.writeText( copyText ).then( function () {
			$button
				.addClass( 'copied' )
				.attr( 'title', wpo_wcpdf_pro_settings.copied );
			$copyValue.text( wpo_wcpdf_pro_settings.copied );

			setTimeout( function () {
				$button
					.removeClass( 'copied' )
					.attr( 'title', buttonTitle );
				$copyValue.text( copyText );
			}, 1000 );
		} );
	} );

	function generalAccordion() {
		// Collapse all
		$( '.wpo-wcpdf-accordion .content' ).hide();

		// Toggle on click.
		$( '.wpo-wcpdf-accordion .header' ).on( 'click', function () {
			$( this ).toggleClass( 'active' )
					 .next( '.content' )
					 .slideToggle( 'fast' );
		} );
	}

	generalAccordion();

} );
