/**
 * Password Protect Master — Public / Frontend JS
 *
 * @package PasswordProtectMaster
 */

(function () {
	'use strict';

	document.addEventListener('DOMContentLoaded', function () {

		/* ----- Eye Toggle (show / hide password) ----- */
		var eyeButtons = document.querySelectorAll('.ppmstr-eye-toggle');

		eyeButtons.forEach(function (btn) {
			btn.addEventListener('click', function () {
				var wrap = btn.closest('.ppmstr-form-input-wrap');
				if (!wrap) return;

				var input     = wrap.querySelector('.ppmstr-form-input');
				var eyeOpen   = btn.querySelector('.ppmstr-eye-open');
				var eyeClosed = btn.querySelector('.ppmstr-eye-closed');

				if (!input) return;

				if ('password' === input.type) {
					input.type = 'text';
					if (eyeOpen)   eyeOpen.style.display   = 'none';
					if (eyeClosed) eyeClosed.style.display  = 'block';
				} else {
					input.type = 'password';
					if (eyeOpen)   eyeOpen.style.display   = 'block';
					if (eyeClosed) eyeClosed.style.display  = 'none';
				}
			});
		});

		/* ----- Focus the password input on page load (full-page only) ----- */
		var fullPageInput = document.querySelector('.ppmstr-fullpage-wrap .ppmstr-form-input');
		if (fullPageInput) {
			fullPageInput.focus();
		}

		/* ----- Countdown Timer ----- */
		var countdowns = document.querySelectorAll('.ppmstr-countdown');
		countdowns.forEach(function (cd) {
			var unlockUTC = parseInt(cd.getAttribute('data-unlock'), 10) * 1000;
			if (!unlockUTC) return;
			var valSpan = cd.querySelector('.ppmstr-cd-val');
			
			var timer = setInterval(function() {
				var now = Date.now();
				var diff = unlockUTC - now;

				if (diff <= 0) {
					clearInterval(timer);
					valSpan.innerHTML = 'Unlocked!';
					// Auto reload since the content should now be visible
					setTimeout(function() { window.location.reload(); }, 1500);
					return;
				}

				var d = Math.floor(diff / (1000 * 60 * 60 * 24));
				var h = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
				var m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
				var s = Math.floor((diff % (1000 * 60)) / 1000);

				var str = '';
				if (d > 0) str += d + 'd ';
				str += (h < 10 ? '0' : '') + h + 'h ';
				str += (m < 10 ? '0' : '') + m + 'm ';
				str += (s < 10 ? '0' : '') + s + 's';

				if (valSpan) valSpan.innerHTML = str;
			}, 1000);
		});

	/* ----- AJAX Form Submission ----- */
		if (typeof ppmstrPublic !== 'undefined' && ppmstrPublic.ajaxUrl) {
			var forms = document.querySelectorAll('.ppmstr-password-form');
			forms.forEach(function (form) {
				form.addEventListener('submit', function (e) {
					e.preventDefault();

					var submitBtn = form.querySelector('.ppmstr-form-submit');
					var errorDiv  = form.querySelector('.ppmstr-form-error');
					var originalText = submitBtn ? submitBtn.innerHTML : '';

					// Defensive: ALWAYS wrap in try-catch to prevent permanent freeze
					try {
						if (submitBtn) {
							submitBtn.disabled = true;
							submitBtn.innerHTML = '...';
						}

						if (!errorDiv) {
							errorDiv = document.createElement('div');
							errorDiv.className = 'ppmstr-form-error';
							errorDiv.setAttribute('role', 'alert');
							errorDiv.style.display = 'none';
							var headerOrInput = form.querySelector('.ppmstr-form-input-wrap') || form.querySelector('input') || form.firstChild;
							if (headerOrInput && headerOrInput.parentNode) {
								headerOrInput.parentNode.insertBefore(errorDiv, headerOrInput);
							} else {
								form.appendChild(errorDiv);
							}
						}

						var formData = new FormData(form);
						formData.append('action', 'ppmstr_unlock');

						fetch(ppmstrPublic.ajaxUrl, {
							method: 'POST',
							body: formData,
							headers: {
								'Accept': 'application/json'
							}
						})
						.then(function(response) {
							if (!response.ok) {
								throw new Error('Server returned ' + response.status);
							}
							return response.json();
						})
						.then(function(data) {
							if (data && data.success) {
								var wrap = form.closest('.ppmstr-form-wrap') || form;
								wrap.style.transition = 'opacity 0.4s ease';
								wrap.style.opacity = '0';
								if (submitBtn) submitBtn.innerHTML = 'Unlocked!';
								
								setTimeout(function() {
									if (data.data && data.data.redirect) {
										window.location.href = data.data.redirect;
									} else {
										window.location.reload();
									}
								}, 400);
							} else {
								// Handle logical error (wrong password)
								if (submitBtn) {
									submitBtn.disabled = false;
									submitBtn.innerHTML = originalText;
								}
								errorDiv.innerHTML = (data && data.data && data.data.message) ? data.data.message : 'Invalid password.';
								errorDiv.style.display = 'block';
								form.classList.add('ppmstr-shake');
								setTimeout(function(){ form.classList.remove('ppmstr-shake'); }, 500);
							}
						})
						.catch(function(err) {
							console.error('[PPMSTR] AJAX Error:', err);
							if (submitBtn) {
								submitBtn.disabled = false;
								submitBtn.innerHTML = originalText;
							}
							errorDiv.innerHTML = 'Connection error. Please try again.';
							errorDiv.style.display = 'block';
						});

					} catch (err) {
						console.error('[PPMSTR] Critical Crash:', err);
						if (submitBtn) {
							submitBtn.disabled = false;
							submitBtn.innerHTML = originalText;
						}
					}
				});
			});
		}

	});
})();
