( function () {
	'use strict';

	var settings = window.heinAdmin || {};
	var i18n = settings.i18n || {};
	var formats = settings.vatFormats || {};

	function normalize( value ) {
		return value.toUpperCase().replace( /[^A-Z0-9]/g, '' );
	}

	// An unrecognised prefix is not an EU VAT number at all, so it must never be reported as one
	function isValid( value ) {
		var pattern = formats[ value.slice( 0, 2 ) ];

		return pattern ? new RegExp( pattern ).test( value ) : false;
	}

	function feedback( input ) {
		var region = input.parentNode.querySelector( '.hein-vat-feedback' );

		if ( ! region ) {
			return;
		}

		var value = normalize( input.value );
		var empty = i18n.empty || {};

		if ( '' === value ) {
			region.textContent = empty[ input.getAttribute( 'data-hein-vat-context' ) || 'order' ] || '';
			region.className = 'description hein-vat-feedback';
			return;
		}

		var valid = isValid( value );

		region.textContent = valid ? i18n.valid || '' : i18n.invalid || '';
		region.className = 'description hein-vat-feedback ' + ( valid ? 'hein-valid' : 'hein-invalid' );
	}

	// Generate is a plain link, so an admin who edits the fields and clicks it loses those edits
	// without a word; the form itself is owned elsewhere, so warn rather than submit
	function guard() {
		var metabox = document.querySelector( '.hein-metabox' );

		if ( ! metabox ) {
			return;
		}

		var inputs = metabox.querySelectorAll( '#hein_vat_number, #hein_po_reference' );
		var saved = Array.prototype.map.call( inputs, function ( input ) {
			return input.value;
		} );

		Array.prototype.forEach.call( metabox.querySelectorAll( '.hein-actions a' ), function ( link ) {
			link.addEventListener( 'click', function ( event ) {
				var dirty = Array.prototype.some.call( inputs, function ( input, index ) {
					return input.value !== saved[ index ];
				} );

				if ( dirty && ! window.confirm( i18n.unsaved || '' ) ) {
					event.preventDefault();
				}
			} );
		} );
	}

	function bind() {
		var inputs = document.querySelectorAll( '.hein-vat-input' );

		Array.prototype.forEach.call( inputs, function ( input ) {
			input.addEventListener( 'input', function () {
				feedback( input );
			} );
			feedback( input );
		} );

		guard();
	}

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