/**
 * Live earning/redemption preview on the Rewards Settings page.
 *
 * Reads the current rate inputs and the sample amounts (data attributes set by
 * PHP) and updates the preview numbers in place. All visible wording lives in
 * the PHP-rendered, translatable markup — this script only writes numbers.
 */
( function () {
	'use strict';

	function nf( value ) {
		try {
			return new Intl.NumberFormat().format( value );
		} catch ( e ) {
			return String( value );
		}
	}

	var earnBox = document.getElementById( 'acrwd-earning-calc' );
	var earnPer = document.getElementById( 'acrwd_earn_per' );
	var earnPoints = document.getElementById( 'acrwd_earn_points' );
	var earnOut = document.getElementById( 'acrwd-earn-preview' );

	function updateEarn() {
		if ( ! earnBox || ! earnPer || ! earnPoints || ! earnOut ) {
			return;
		}
		var sample = parseFloat( earnBox.getAttribute( 'data-sample' ) ) || 0;
		var per = parseFloat( earnPer.value ) || 1;
		var points = parseFloat( earnPoints.value ) || 0;
		if ( per < 1 ) {
			per = 1;
		}
		earnOut.textContent = nf( Math.floor( sample * ( points / per ) ) );
	}

	var redeemBox = document.getElementById( 'acrwd-redeem-calc' );
	var redeemRate = document.getElementById( 'redemption_rate' );
	var redeemOut = document.getElementById( 'acrwd-redeem-preview' );

	function updateRedeem() {
		if ( ! redeemBox || ! redeemRate || ! redeemOut ) {
			return;
		}
		var symbol = redeemBox.getAttribute( 'data-currency' ) || '';
		var points = parseFloat( redeemBox.getAttribute( 'data-points' ) ) || 0;
		var rate = parseFloat( redeemRate.value ) || 1;
		if ( rate < 1 ) {
			rate = 1;
		}
		var worth = Math.round( ( points / rate ) * 100 ) / 100;
		redeemOut.textContent = symbol + nf( worth );
	}

	if ( earnPer ) {
		earnPer.addEventListener( 'input', updateEarn );
	}
	if ( earnPoints ) {
		earnPoints.addEventListener( 'input', updateEarn );
	}
	if ( redeemRate ) {
		redeemRate.addEventListener( 'input', updateRedeem );
	}

	updateEarn();
	updateRedeem();
} )();
