/**
 * TrustLens Card-Testing Defense — admin page JS.
 * Handles panic-button activate / deactivate via admin-ajax, and remembers the
 * admin's last-used freeze duration across page loads.
 *
 * @since 1.4.0
 */
( function ( $ ) {
	'use strict';

	var DURATION_KEY = 'tl_ct_panic_duration';

	// localStorage access can throw (private mode / disabled). Guard both ways
	// so a storage failure never breaks the panic controls.
	function readStoredDuration() {
		try {
			return window.localStorage ? window.localStorage.getItem( DURATION_KEY ) : null;
		} catch ( e ) {
			return null;
		}
	}

	function storeDuration( value ) {
		try {
			if ( window.localStorage ) {
				window.localStorage.setItem( DURATION_KEY, value );
			}
		} catch ( e ) {}
	}

	// Restore the admin's last-used freeze duration. The <select> always renders
	// with "15 min" preselected, so without this it resets on every page load.
	var $duration = $( '#tl-ct-panic-duration' );
	if ( $duration.length ) {
		var saved = readStoredDuration();
		// Only apply if the stored value is still a valid option.
		if ( saved && $duration.find( 'option[value="' + saved + '"]' ).length ) {
			$duration.val( saved );
		}
		$duration.on( 'change', function () {
			storeDuration( $( this ).val() );
		} );
	}

	function minutesLabel( seconds ) {
		var mins = Math.round( seconds / 60 );
		return mins + ( 1 === mins ? ' minute' : ' minutes' );
	}

	$( document ).on( 'click', '#tl-ct-panic-activate', function () {
		var $btn     = $( this );
		var origText = $btn.text();
		var nonce    = $btn.data( 'nonce' );
		var duration = parseInt( $( '#tl-ct-panic-duration' ).val(), 10 ) || 900;

		if ( ! window.confirm( 'Activate Panic Freeze for ' + minutesLabel( duration ) + '?\n\nThis blocks ALL new checkouts until it expires. Customers already in checkout finish normally.' ) ) {
			return;
		}

		$btn.prop( 'disabled', true ).text( 'Activating…' );

		$.post( ajaxurl, {
			action:   'trustlens_panic_activate',
			_wpnonce: nonce,
			duration: duration
		}, function ( resp ) {
			if ( resp && resp.success ) {
				window.location.reload();
			} else {
				window.alert( 'Failed to activate: ' + ( resp && resp.message ? resp.message : 'unknown error' ) );
				$btn.prop( 'disabled', false ).text( origText );
			}
		} );
	} );

	$( document ).on( 'click', '#tl-ct-panic-deactivate', function () {
		var $btn     = $( this );
		var origText = $btn.text();
		var nonce    = $btn.data( 'nonce' );

		$btn.prop( 'disabled', true ).text( 'Deactivating…' );

		$.post( ajaxurl, {
			action:   'trustlens_panic_deactivate',
			_wpnonce: nonce
		}, function ( resp ) {
			if ( resp && resp.success ) {
				window.location.reload();
			} else {
				window.alert( 'Failed to deactivate.' );
				$btn.prop( 'disabled', false ).text( origText );
			}
		} );
	} );
} )( jQuery );
