/**
 * @file assets/js/adminjs/admin-validation.js
 * Standalone ISBN-13, ASIN, and price field validation for the Format / Pricing repeater.
 * @package MyBookShowroom
 * @since   1.0.0
 */

(function( MBS, $, undefined ) {
	'use strict';

	const { __ } = wp.i18n;

	MBS.Validation = {
		init: function() {
			this.bindISBNValidation();
			this.bindASINValidation();
			this.bindPriceValidation();
			// BUG-05: ISBN fields loaded from DB contain raw digits (no hyphens).
			// The blur handler reformats on user interaction, but on initial page
			// load existing rows are displayed unformatted.  Apply format + validity
			// class to all ISBN fields that already have a value on DOM ready.
			this.initISBNDisplay();
		},

		/**
		 * BUG-05: Format and validate any ISBN-13 fields that already have a value
		 * when the page loads (existing saved rows).  Mirrors the blur branch of
		 * bindISBNValidation() but runs once at init rather than on user interaction.
		 */
		initISBNDisplay: function() {
			$( '.mbs-isbn-field' ).each( function() {
				const $field   = $( this );
				const $errSpan = $field.siblings( '.mbs-isbn-error' );
				const raw      = $field.val();
				if ( ! raw ) { return; }
				const clean = raw.trim().replace( /[^0-9]/g, '' );
				if ( clean.length !== 13 ) {
					$field.addClass( 'mbs-error' );
					$errSpan.text( __( 'Must be 13 digits starting with 978 or 979 with a valid check digit.', 'my-book-showroom' ) ).show();
					return;
				}
				if ( clean.slice( 0, 3 ) !== '978' && clean.slice( 0, 3 ) !== '979' ) {
					$field.addClass( 'mbs-error' );
					$errSpan.text( __( 'Must be 13 digits starting with 978 or 979 with a valid check digit.', 'my-book-showroom' ) ).show();
					return;
				}
				let sum = 0;
				for ( let j = 0; j < 12; j++ ) {
					sum += parseInt( clean[ j ], 10 ) * ( j % 2 === 0 ? 1 : 3 );
				}
				if ( ( 10 - ( sum % 10 ) ) % 10 !== parseInt( clean[ 12 ], 10 ) ) {
					$field.addClass( 'mbs-error' );
					$errSpan.text( __( 'Must be 13 digits starting with 978 or 979 with a valid check digit.', 'my-book-showroom' ) ).show();
					return;
				}
				$field.removeClass( 'mbs-error' ).addClass( 'mbs-valid' );
				$errSpan.text( '' ).hide();
				$field.val( clean.replace( /^(\d{3})(\d)(\d{2})(\d{6})(\d)$/, '$1-$2-$3-$4-$5' ) );
			} );
		},

		bindISBNValidation: function() {
			// ISBN-13 — FV-010: check digit, FV-011: 3-1-2-6-1 hyphenation.
			$(document).on('input blur keyup', '.mbs-isbn-field', function() {
				const $field   = $(this);
				const $errSpan = $field.siblings('.mbs-isbn-error');
				const clean    = $field.val().trim().replace(/[^0-9]/g, '');

				if (clean.length === 0) {
					$field.removeClass('mbs-error mbs-valid');
					$errSpan.text('').hide();
					return;
				}
				if (clean.length !== 13 || (clean.slice(0,3) !== '978' && clean.slice(0,3) !== '979')) {
					$field.addClass('mbs-error').removeClass('mbs-valid');
					$errSpan.text(__( 'Must be 13 digits starting with 978 or 979 with a valid check digit.', 'my-book-showroom' )).show();
					return;
				}
				// FV-010: mod-10 check digit validation.
				let sum = 0;
				for (let j = 0; j < 12; j++) {
					sum += parseInt(clean[j], 10) * (j % 2 === 0 ? 1 : 3);
				}
				if ((10 - (sum % 10)) % 10 !== parseInt(clean[12], 10)) {
					$field.addClass('mbs-error').removeClass('mbs-valid');
					$errSpan.text(__( 'Must be 13 digits starting with 978 or 979 with a valid check digit.', 'my-book-showroom' )).show();
					return;
				}
				$field.removeClass('mbs-error').addClass('mbs-valid');
				$errSpan.text('').hide();
				if (!$(this).is(':focus')) {
					$field.val(clean.replace(/^(\d{3})(\d)(\d{2})(\d{6})(\d)$/, '$1-$2-$3-$4-$5'));
				}
			});
		},

		bindASINValidation: function() {
			// ASIN — FV-005: exactly 10 alphanumeric chars, auto-uppercase.
			$(document).on('input blur keyup', 'input[name^="mbs_asin"], .mbs-asin-field', function() {
				const $field   = $(this);
				const $errSpan = $field.siblings('.mbs-asin-error');
				const clean    = $field.val().trim().replace(/[^A-Za-z0-9]/g, '').toUpperCase();

				if (clean.length === 0) {
					$field.removeClass('mbs-error mbs-valid');
					$errSpan.text('').hide();
					return;
				}
				if (clean.length === 10) {
					if (!$(this).is(':focus')) { $field.val(clean); }
					$field.removeClass('mbs-error').addClass('mbs-valid');
					$errSpan.text('').hide();
				} else {
					$field.addClass('mbs-error').removeClass('mbs-valid');
					$errSpan.text(__( 'Must be exactly 10 alphanumeric characters.', 'my-book-showroom' )).show();
				}
			});
		},

		bindPriceValidation: function() {
			// FV-003:  Commas rejected outright.
			// FV-004:  Max 999.99 for standard currencies (XXX.XX per spec).
			// FV-015:  Zero-decimal currencies (JPY, KRW, etc.) use integer-only
			//          validation and a per-currency max from MBS_PriceConfig.
			// PRICE-V-1: Leading/trailing currency symbol stripped on blur.
			$(document).on('input blur keyup', 'input[name^="mbs_price"]', function() {
				const $field    = $(this);
				const raw       = $field.val().trim();
				const cfg       = (typeof MBS_PriceConfig !== 'undefined') ? MBS_PriceConfig : {};
				const isZeroDec = !!cfg.isZeroDecimal;
				const maxPrice  = isZeroDec ? (parseInt(cfg.maxPrice, 10) || 999999) : 999;

				if (raw.length === 0) {
					$field.removeClass('mbs-error mbs-valid');
					return;
				}

				// Strip one leading or trailing currency symbol.
				const noSymbol = raw.replace(/^[^\d\s,.]+|[^\d\s,.]+$/, '');

				// FV-003: Reject any comma.
				if (noSymbol.indexOf(',') !== -1) {
					$field.addClass('mbs-error').removeClass('mbs-valid');
					return;
				}

				if (isZeroDec) {
					// FV-015: Zero-decimal — integers only, no decimal point allowed.
					const clean = noSymbol.replace(/[^0-9]/g, '');
					if (clean.length === 0 || !/^\d+$/.test(clean)) {
						$field.addClass('mbs-error').removeClass('mbs-valid');
						return;
					}
					const num = parseInt(clean, 10);
					if (num > maxPrice) {
						$field.addClass('mbs-error').removeClass('mbs-valid');
						return;
					}
					$field.removeClass('mbs-error').addClass('mbs-valid');
					if (!$(this).is(':focus')) {
						$field.val(String(num)); // strip symbol, no decimal places
					}
				} else {
					// Standard currency: FV-004 XXX.XX — at most 3 digits before decimal.
					const clean = noSymbol.replace(/[^0-9.]/g, '');
					if (!/^\d{1,3}(\.\d{0,2})?$/.test(clean)) {
						$field.addClass('mbs-error').removeClass('mbs-valid');
						return;
					}
					const num = parseFloat(clean) || 0;
					if (num >= 1000) {
						$field.addClass('mbs-error').removeClass('mbs-valid');
						return;
					}
					$field.removeClass('mbs-error').addClass('mbs-valid');
					if (!$(this).is(':focus')) {
						$field.val(num.toFixed(2)); // strip symbol, pad to 2dp
					}
				}
			});
		}
	};

	// FV-009: Auto-initialize on DOM ready so standalone fields outside the
	// repeater (e.g. future header fields, import preview) also get validation.
	$(function() {
		if (typeof MBS !== 'undefined' && MBS.Validation) {
			MBS.Validation.init();
		}
	});

})( window.MBS = window.MBS || {}, jQuery );
