/**
 * Confirmation prompt for destructive bulk actions on AffiliateWP admin list tables.
 *
 * @since 2.33.0
 */
( function () {
	'use strict';

	const data   = window.affwpBulkConfirmData || {};
	const labels = data.labels || {};

	function fmt( template, value ) {
		return String( template || '' ).replace( /%[ds]/, String( value ) );
	}

	const FORM_CONFIGS = {
		'affwp-payouts-filter': {
			checkboxName: 'payout_id[]',
			singularKey:  'confirmPayoutSingular',
			pluralKey:    'confirmPayoutPlural'
		},
		'affwp-payout-batches-filter': {
			checkboxName: 'batch_id[]',
			singularKey:  'confirmBatchSingular',
			pluralKey:    'confirmBatchPlural'
		},
		'affwp-referrals-filter-form': {
			checkboxName: 'referral_id[]',
			singularKey:  'confirmReferralSingular',
			pluralKey:    'confirmReferralPlural'
		}
	};

	function shouldProceed( form, cfg ) {
		// WP renders two action selects (top + bottom); take whichever is non-default.
		const action1 = ( form.querySelector( 'select[name="action"]' )  || { value: '-1' } ).value;
		const action2 = ( form.querySelector( 'select[name="action2"]' ) || { value: '-1' } ).value;
		const action  = action1 !== '-1' ? action1 : action2;

		if ( 'delete' !== action ) {
			return true;
		}

		const checked = form.querySelectorAll( 'input[type="checkbox"][name="' + cfg.checkboxName + '"]:checked' ).length;

		if ( 0 === checked ) {
			return true;
		}

		const template = checked === 1 ? labels[ cfg.singularKey ] : labels[ cfg.pluralKey ];
		return window.confirm( fmt( template, checked ) );
	}

	function bind( form, cfg ) {
		form.addEventListener( 'submit', function ( e ) {
			if ( ! shouldProceed( form, cfg ) ) {
				e.preventDefault();
				e.stopPropagation();
			}
		}, true );
	}

	function init() {
		Object.keys( FORM_CONFIGS ).forEach( function ( formId ) {
			const form = document.getElementById( formId );
			if ( form ) {
				bind( form, FORM_CONFIGS[ formId ] );
			}
		} );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
