(function() {
	'use strict';

	var config = window.puffergoComments;
	if (!config) return;

	var i18n = config.i18n || {};
	function __(key) { return i18n[key] || key; }

	// ── Cookie helpers ──

	function getCookie(name) {
		var parts = ('; ' + document.cookie).split('; ' + name + '=');
		return parts.length === 2 ? parts.pop().split(';').shift() : '';
	}

	function saveCookies(author, email) {
		var d = new Date();
		d.setFullYear(d.getFullYear() + 1);
		var suffix = '; expires=' + d.toUTCString() + '; path=/; SameSite=Lax';
		document.cookie = 'comment_author_' + config.cookieHash + '=' + encodeURIComponent(author) + suffix;
		document.cookie = 'comment_author_email_' + config.cookieHash + '=' + encodeURIComponent(email) + suffix;
	}

	function restoreFromCookies(form) {
		var authorVal = getCookie('comment_author_' + config.cookieHash);
		var emailVal = getCookie('comment_author_email_' + config.cookieHash);
		var authorInput = form.querySelector('#author');
		var emailInput = form.querySelector('#email');
		if (authorVal && authorInput && !authorInput.value) authorInput.value = decodeURIComponent(authorVal);
		if (emailVal && emailInput && !emailInput.value) emailInput.value = decodeURIComponent(emailVal);
	}

	// ── Validation ──

	function clearFieldError(field) {
		if (!field) return;
		field.classList.remove('error');
		var msg = field.parentNode.querySelector('.field-error-message');
		if (msg) msg.remove();
	}

	function showFieldError(field, message) {
		clearFieldError(field);
		field.classList.add('error');
		var el = document.createElement('div');
		el.className = 'field-error-message';
		el.textContent = message;
		field.parentNode.appendChild(el);
	}

	function validateRequired(field, errorKey) {
		if (!field) return true;
		if (field.value.trim()) { clearFieldError(field); return true; }
		showFieldError(field, __(errorKey));
		return false;
	}

	function validateEmail(field) {
		if (!field) return true;
		var val = field.value.trim();
		if (!val) { showFieldError(field, __('emailRequired')); return false; }
		if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)) { clearFieldError(field); return true; }
		showFieldError(field, __('emailInvalid'));
		return false;
	}

	function validateForm(form) {
		var valid = true;
		if (!validateRequired(form.querySelector('#author'), 'nameRequired')) valid = false;
		if (!validateEmail(form.querySelector('#email'))) valid = false;
		if (!validateRequired(form.querySelector('#comment'), 'commentRequired')) valid = false;
		var commentField = form.querySelector('#comment');
		if (commentField && commentField.value.trim().length < 5) {
			showFieldError(commentField, __('commentTooShort'));
			valid = false;
		}
		return valid;
	}

	// ── Messages ──

	function clearMessages() {
		document.querySelectorAll('.comment-message').forEach(function(el) { el.remove(); });
	}

	function showMessage(type, text, duration) {
		clearMessages();
		var icons = { success: '\u2713', error: '\u2715', info: '\u2139' };
		var el = document.createElement('div');
		el.className = 'comment-message ' + type;
		el.innerHTML = '<span class="message-icon">' + (icons[type] || '\u2139') + '</span>' +
			'<span class="message-text">' + text + '</span>';
		var wrapper = document.querySelector('.blog-detail-page .comment-form-wrapper');
		if (!wrapper) return;
		wrapper.insertBefore(el, wrapper.firstChild);
		if (typeof duration === 'undefined') duration = 5000;
		if (duration > 0) {
			setTimeout(function() {
				el.style.opacity = '0';
				setTimeout(function() { el.remove(); }, 300);
			}, duration);
		}
	}

	// ── Comment insertion ──

	function highlightNewComment(el) {
		el.classList.add('new-comment');
		setTimeout(function() { el.classList.remove('new-comment'); }, 3000);
	}

	function insertComment(html, parentId) {
		if (!html) return;
		var list = document.querySelector('.blog-detail-page .comment-list');
		if (!list) return;
		var temp = document.createElement('div');
		temp.innerHTML = html;
		var node = temp.firstElementChild;
		if (!node) return;
		if (parentId && parentId !== '0') {
			var parent = document.getElementById('comment-' + parentId);
			if (parent) {
				var children = parent.querySelector('.children');
				if (!children) {
					children = document.createElement('ol');
					children.className = 'children';
					parent.appendChild(children);
				}
				children.appendChild(node);
			}
		} else {
			list.insertBefore(node, list.firstChild);
		}
		highlightNewComment(node);
	}

	// ── Form submission ──

	async function handleSubmit(e) {
		e.preventDefault();
		e.stopPropagation();
		var form = e.target;
		var btn = form.querySelector('.submit-button');
		if (!validateForm(form)) return;

		var fd = new FormData(form);
		fd.append('action', config.action);
		fd.append('_wp_nonce', config.nonce);

		btn.disabled = true;
		var originalText = btn.textContent;
		btn.textContent = __('submitting');
		btn.classList.add('loading');
		clearMessages();

		try {
			var resp = await fetch(config.ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' });
			var result = await resp.json();
			if (result.success) {
				var authorInput = form.querySelector('#author');
				var emailInput = form.querySelector('#email');
				if (authorInput && emailInput) saveCookies(authorInput.value, emailInput.value);
				var msg = result.data.is_moderated ? __('commentAwaitingModeration') : __('commentSuccess');
				showMessage('success', msg, 0);
				form.reset();
				insertComment(result.data.comment_html, result.data.comment_parent);
				setTimeout(function() {
					var el = document.querySelector('.comment-message.success');
					if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
				}, 100);
			} else {
				showMessage('error', result.data || __('submitFailed'));
			}
		} catch (err) {
			console.error('Comment submit error:', err);
			showMessage('error', __('networkError'));
		} finally {
			btn.disabled = false;
			btn.textContent = originalText;
			btn.classList.remove('loading');
		}
	}

	// ── Init ──

	function init() {
		var form = document.querySelector('.blog-detail-page .comment-form');
		if (!form) return;
		form.setAttribute('action', 'javascript:void(0);');
		restoreFromCookies(form);
		form.addEventListener('submit', handleSubmit);
		var author = form.querySelector('#author');
		var email = form.querySelector('#email');
		var comment = form.querySelector('#comment');
		if (author) author.addEventListener('blur', function() { validateRequired(author, 'nameRequired'); });
		if (email) email.addEventListener('blur', function() { validateEmail(email); });
		if (comment) comment.addEventListener('blur', function() { validateRequired(comment, 'commentRequired'); });
	}

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