/**
 * Signup Block — frontend password strength meter.
 *
 * Runs only on the signup form (not the login form).
 * No build step required: plain ES5-compatible vanilla JS.
 */
( function () {
	document.addEventListener( 'DOMContentLoaded', function () {
		/* Scroll to the login form when the invite link targets it directly. */
		var params = new URLSearchParams( window.location.search );
		if ( params.get( 'ambh_form' ) === 'login' ) {
			var loginBox = document.getElementById( 'ambh-auth-box-login' );
			if ( loginBox ) {
				loginBox.scrollIntoView( { behavior: 'smooth', block: 'start' } );
				var firstInput = loginBox.querySelector( 'input[type="email"]' );
				if ( firstInput ) firstInput.focus();
			}
		}

		var input = document.getElementById( 'ambh-signup-password' );
		if ( ! input ) return;

		var rules = [
			{
				key:   'length',
				label: 'At least 8 characters',
				test:  function ( v ) { return v.length >= 8; },
			},
			{
				key:   'upper',
				label: 'One uppercase letter (A–Z)',
				test:  function ( v ) { return /[A-Z]/.test( v ); },
			},
			{
				key:   'number',
				label: 'One number (0–9)',
				test:  function ( v ) { return /[0-9]/.test( v ); },
			},
			{
				key:   'special',
				label: 'One special character (!@#$ …)',
				test:  function ( v ) { return /[^A-Za-z0-9]/.test( v ); },
			},
		];

		/* ── build the strength widget ── */
		var widget = document.createElement( 'div' );
		widget.className = 'ambh-pw-strength';

		/* bars */
		var barsEl = document.createElement( 'div' );
		barsEl.className = 'ambh-pw-bars';
		for ( var b = 0; b < rules.length; b++ ) {
			barsEl.appendChild( document.createElement( 'span' ) );
		}

		/* rule checklist */
		var listEl = document.createElement( 'ul' );
		listEl.className = 'ambh-pw-rules';
		rules.forEach( function ( rule ) {
			var li = document.createElement( 'li' );
			li.dataset.rule  = rule.key;
			li.textContent   = rule.label;
			listEl.appendChild( li );
		} );

		widget.appendChild( barsEl );
		widget.appendChild( listEl );
		input.parentNode.insertBefore( widget, input.nextSibling );

		var allBars = barsEl.querySelectorAll( 'span' );

		var levelClass = [ '', 'ambh-pw-bar--weak', 'ambh-pw-bar--fair', 'ambh-pw-bar--good', 'ambh-pw-bar--strong' ];

		/* ── live update ── */
		input.addEventListener( 'input', function () {
			var v     = input.value;
			var score = 0;

			rules.forEach( function ( rule ) {
				var li  = listEl.querySelector( '[data-rule="' + rule.key + '"]' );
				var met = rule.test( v );
				li.classList.toggle( 'ambh-pw-rule--met', met );
				if ( met ) score++;
			} );

			allBars.forEach( function ( bar, i ) {
				bar.className = i < score ? levelClass[ score ] : '';
			} );
		} );
	} );
} )();
