/**
 * Ultimate Security - Password Strength Meter
 * Real-time password validation with visual strength indicator
 * @param $
 */
( function ( $ ) {
	'use strict';

	// Track if styles have been injected
	let stylesInjected = false;

	// Password policies from server (will be populated via localized script)
	const policies = window.ultimateSecurityPolicies || {
		min_length: 12,
		ui_rules_mix_case: '0',
		ui_rules_numeric: '0',
		ui_rules_special_chars: '0',
	};

	/**
	 * Inject CSS styles into the page head (only once)
	 */
	function injectStyles() {
		if ( stylesInjected ) {
			return;
		}
		stylesInjected = true;

		const css = `
            .us-password-strength-meter {
                margin-top: 10px;
                padding: 12px;
                background: #f8f9fa;
                border-radius: 6px;
                border: 1px solid #e0e0e0;
            }
            .us-pw-strength-bar-container {
                height: 8px;
                background: #e0e0e0;
                border-radius: 4px;
                overflow: hidden;
                margin-bottom: 8px;
            }
            .us-pw-strength-bar {
                height: 100%;
                transition: width 0.3s ease, background-color 0.3s ease;
                border-radius: 4px;
            }
            .us-pw-strength-bar.weak { background: #dc3545; }
            .us-pw-strength-bar.fair { background: #fd7e14; }
            .us-pw-strength-bar.good { background: #ffc107; }
            .us-pw-strength-bar.strong { background: #28a745; }
            .us-pw-strength-label {
                font-size: 13px;
                font-weight: 600;
                margin-bottom: 10px;
            }
            .us-pw-strength-text.weak { color: #dc3545; }
            .us-pw-strength-text.fair { color: #fd7e14; }
            .us-pw-strength-text.good { color: #856404; }
            .us-pw-strength-text.strong { color: #28a745; }
            .us-pw-requirements {
                display: flex;
                flex-direction: column;
                gap: 6px;
            }
            .us-pw-requirement {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 12px;
                color: #666;
            }
            .us-pw-check-icon {
                font-size: 12px;
                width: 16px;
                text-align: center;
            }
            .us-pw-requirement.passed .us-pw-check-icon {
                color: #28a745;
            }
            .us-pw-requirement:not(.passed) .us-pw-check-icon {
                color: #dc3545;
            }
            .us-pw-requirement.passed {
                color: #28a745;
            }
        `;

		const styleElement = document.createElement( 'style' );
		styleElement.type = 'text/css';
		styleElement.id = 'us-password-strength-styles';
		styleElement.appendChild( document.createTextNode( css ) );
		document.head.appendChild( styleElement );
	}

	/**
	 * Calculate password strength based on policies
	 * @param {string} password
	 * @return {Object} { score: 0-100, level: 'weak'|'fair'|'good'|'strong', checks: {} }
	 */
	function calculateStrength( password ) {
		const checks = {
			length: false,
			mixCase: false,
			numeric: false,
			special: false,
		};

		let score = 0;
		const maxScore = 100;

		// Check minimum length
		const minLength = parseInt( policies.min_length ) || 8;
		if ( password.length >= minLength ) {
			checks.length = true;
			score += 25;
		} else if ( password.length >= minLength * 0.75 ) {
			score += 15;
		} else if ( password.length >= minLength * 0.5 ) {
			score += 10;
		}

		// Extra points for longer passwords
		if ( password.length >= minLength + 4 ) {
			score += 10;
		}
		if ( password.length >= minLength + 8 ) {
			score += 10;
		}

		// Check mixed case
		const hasLower = /[a-z]/.test( password );
		const hasUpper = /[A-Z]/.test( password );
		if ( hasLower && hasUpper ) {
			checks.mixCase = true;
			score += 20;
		} else if ( hasLower || hasUpper ) {
			score += 10;
		}

		// Check numeric
		if ( /[0-9]/.test( password ) ) {
			checks.numeric = true;
			score += 20;
		}

		// Check special characters
		if ( /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?`~]/.test( password ) ) {
			checks.special = true;
			score += 15;
		}

		// Cap score at 100
		score = Math.min( score, maxScore );

		// Determine level
		let level = 'weak';
		if ( score >= 80 ) {
			level = 'strong';
		} else if ( score >= 60 ) {
			level = 'good';
		} else if ( score >= 40 ) {
			level = 'fair';
		}

		return { score, level, checks };
	}

	/**
	 * Get requirement text based on policies
	 * @return {Array}
	 */
	function getRequirements() {
		const reqs = [];
		const minLength = parseInt( policies.min_length ) || 8;

		reqs.push( {
			key: 'length',
			text: 'At least ' + minLength + ' characters',
			required: true,
		} );

		if ( policies.ui_rules_mix_case === '1' ) {
			reqs.push( {
				key: 'mixCase',
				text: 'Uppercase and lowercase letters',
				required: true,
			} );
		}

		if ( policies.ui_rules_numeric === '1' ) {
			reqs.push( {
				key: 'numeric',
				text: 'At least one number (0-9)',
				required: true,
			} );
		}

		if ( policies.ui_rules_special_chars === '1' ) {
			reqs.push( {
				key: 'special',
				text: 'At least one special character (!@#$%^&*)',
				required: true,
			} );
		}

		return reqs;
	}

	/**
	 * Create strength meter HTML (without styles - they're injected separately)
	 * @return {string}
	 */
	function createMeterHTML() {
		const requirements = getRequirements();
		let reqHTML = '';

		requirements.forEach( function ( req ) {
			reqHTML +=
				'<div class="us-pw-requirement" data-req="' +
				req.key +
				'">' +
				'<span class="us-pw-check-icon">✗</span>' +
				'<span class="us-pw-check-text">' +
				req.text +
				'</span>' +
				'</div>';
		} );

		return (
			'<div class="us-password-strength-meter">' +
			'<div class="us-pw-strength-bar-container">' +
			'<div class="us-pw-strength-bar" style="width: 0%"></div>' +
			'</div>' +
			'<div class="us-pw-strength-label">' +
			'<span class="us-pw-strength-text"></span>' +
			'</div>' +
			'<div class="us-pw-requirements">' +
			reqHTML +
			'</div>' +
			'</div>'
		);
	}

	/**
	 * Update strength meter display
	 * @param {jQuery} $meter
	 * @param {Object} result
	 */
	function updateMeter( $meter, result ) {
		const $bar = $meter.find( '.us-pw-strength-bar' );
		const $label = $meter.find( '.us-pw-strength-text' );

		// Update bar
		$bar.css( 'width', result.score + '%' );
		$bar.removeClass( 'weak fair good strong' ).addClass( result.level );

		// Update label
		const labels = {
			weak: 'Weak',
			fair: 'Fair',
			good: 'Good',
			strong: 'Strong',
		};
		$label.text( labels[ result.level ] || '' );
		$label.removeClass( 'weak fair good strong' ).addClass( result.level );

		// Update requirements
		Object.keys( result.checks ).forEach( function ( key ) {
			const $req = $meter.find( '[data-req="' + key + '"]' );
			const $icon = $req.find( '.us-pw-check-icon' );
			if ( result.checks[ key ] ) {
				$req.addClass( 'passed' );
				$icon.html( '✓' );
			} else {
				$req.removeClass( 'passed' );
				$icon.html( '✗' );
			}
		} );
	}

	/**
	 * Initialize strength meter on a password field
	 * @param {jQuery} $field
	 */
	function initStrengthMeter( $field ) {
		// Don't initialize twice
		if ( $field.data( 'us-strength-init' ) ) {
			return;
		}
		$field.data( 'us-strength-init', true );

		// Inject styles first
		injectStyles();

		// Create and insert meter
		const $meter = $( createMeterHTML() );

		// Find the best place to insert - right after the password input wrapper
		let inserted = false;

		// WordPress Admin Profile page - insert after .wp-pwd wrapper
		const $wpPwd = $field.closest( '.wp-pwd' );
		if ( $wpPwd.length ) {
			$wpPwd.after( $meter );
			inserted = true;
		}

		// WordPress Admin - insert after user-pass1-wrap
		if ( ! inserted ) {
			const $userPass1Wrap = $field.closest( '.user-pass1-wrap' );
			if ( $userPass1Wrap.length ) {
				$userPass1Wrap.after( $meter );
				inserted = true;
			}
		}

		// WooCommerce forms
		if ( ! inserted ) {
			const $wooRow = $field.closest( '.form-row, .woocommerce-form-row' );
			if ( $wooRow.length ) {
				$wooRow.after( $meter );
				inserted = true;
			}
		}

		// WordPress login/reset form
		if ( ! inserted ) {
			const $formRow = $field.closest( 'p, .form-row' );
			if ( $formRow.length ) {
				$formRow.after( $meter );
				inserted = true;
			}
		}

		// Fallback - insert directly after the field
		if ( ! inserted ) {
			$field.after( $meter );
		}

		// Hide initially
		$meter.hide();

		// Bind input event
		$field.on( 'input focus', function () {
			const password = $( this ).val();

			if ( password.length > 0 ) {
				$meter.show();
				const result = calculateStrength( password );
				updateMeter( $meter, result );
			} else {
				$meter.hide();
			}
		} );

		// Also check on page load if field has value
		if ( $field.val().length > 0 ) {
			$meter.show();
			updateMeter( $meter, calculateStrength( $field.val() ) );
		}
	}

	/**
	 * Initialize on document ready
	 */
	$( document ).ready( function () {
		// WooCommerce Edit Account form
		const $wooEditForm = $( 'form.woocommerce-EditAccountForm' );
		if ( $wooEditForm.length ) {
			const $password1 = $wooEditForm.find( '#password_1' );
			if ( $password1.length ) {
				initStrengthMeter( $password1 );
			}
		}

		// WooCommerce Reset Password form
		const $wooResetForm = $( 'form.woocommerce-ResetPassword.lost_reset_password' );
		if ( $wooResetForm.length ) {
			const $passwordField = $wooResetForm.find( 'input[type="password"]' ).first();
			if ( $passwordField.length ) {
				initStrengthMeter( $passwordField );
			}
		}

		// WordPress Reset Password form - exclude to avoid conflicts with generate password button
		// const $wpResetForm = $('#resetpassform, form[name="resetpassform"]');
		// if ($wpResetForm.length) {
		//     const $pass1 = $wpResetForm.find('#pass1, input[name="pass1"]');
		//     if ($pass1.length) {
		//         initStrengthMeter($pass1);
		//     }
		// }

		// WordPress Profile Edit (admin)
		const $profileForm = $( '#your-profile' );
		if ( $profileForm.length ) {
			const $pass1 = $profileForm.find( '#pass1' );
			if ( $pass1.length ) {
				initStrengthMeter( $pass1 );
			}
		}

		// WordPress User Edit (admin)
		const $userEditForm = $( '#createuser, #edituserform' );
		if ( $userEditForm.length ) {
			const $pass1 = $userEditForm.find( '#pass1' );
			if ( $pass1.length ) {
				initStrengthMeter( $pass1 );
			}
		}
	} );
} )( jQuery );
