/**
 * Kramar Account Flow — frontend script.
 *
 * Handles:
 *  - Post-checkout opt-in account creation form (checkbox → show button → AJAX)
 *  - Reorder button (AJAX → add to cart → redirect)
 *  - Email-first login form (classic checkout only)
 *  - Login redirect custom-URL field show/hide in admin settings
 *
 * No jQuery. No inline scripts. All config via wp_localize_script (kramarAccountFlow).
 */
(function () {
	'use strict';

	var cfg = window.kramarAccountFlow || {};
	var i18n = cfg.i18n || {};

	// -------------------------------------------------------------------------
	// Post-checkout opt-in account creation
	// -------------------------------------------------------------------------

	function initAccountCta() {
		var form = document.getElementById('kramar-create-account-form');
		if (!form) {
			return;
		}

		var checkbox = document.getElementById('kramar-account-optin');
		var btn      = document.getElementById('kramar-account-cta-btn');
		var result   = document.getElementById('kramar-account-cta-result');

		if (!checkbox || !btn || !result) {
			return;
		}

		// Show button only when user actively ticks the checkbox.
		checkbox.addEventListener('change', function () {
			btn.style.display = checkbox.checked ? '' : 'none';
		});

		form.addEventListener('submit', function (e) {
			e.preventDefault();

			if (!checkbox.checked) {
				return;
			}

			var orderId = btn.getAttribute('data-order-id');
			var nonce   = btn.getAttribute('data-nonce');

			btn.disabled = true;
			btn.textContent = i18n.creating || 'Creating account…';
			result.style.display = 'none';

			var body = new URLSearchParams();
			body.append('action', cfg.actionCreate || 'kramar_create_account');
			body.append('order_id', orderId);
			body.append('nonce', nonce);

			fetch(cfg.ajaxUrl || '', {
				method: 'POST',
				headers: { 'X-Requested-With': 'XMLHttpRequest' },
				body: body
			})
				.then(function (r) { return r.json(); })
				.then(function (d) {
					result.style.display = '';
					if (d && d.success) {
						result.style.color = '#197a1d';
						result.textContent = (d.data && d.data.message) ? d.data.message : (i18n.success || 'Done!');
						btn.style.display  = 'none';
						checkbox.disabled  = true;
					} else {
						result.style.color = '#c0392b';
						result.textContent = (d && d.data && d.data.message) ? d.data.message : (i18n.error || 'Something went wrong.');
						btn.disabled       = false;
						btn.textContent    = 'Account aanmaken';
					}
				})
				.catch(function () {
					result.style.display = '';
					result.style.color   = '#c0392b';
					result.textContent   = i18n.error || 'Something went wrong.';
					btn.disabled         = false;
					btn.textContent      = 'Account aanmaken';
				});
		});
	}

	// -------------------------------------------------------------------------
	// Reorder buttons
	// -------------------------------------------------------------------------

	function initReorder() {
		document.addEventListener('click', function (e) {
			var btn = e.target.closest('.kramar-reorder-btn');
			if (!btn) {
				return;
			}

			e.preventDefault();

			var orderId = btn.getAttribute('data-order-id');
			var nonce   = btn.getAttribute('data-nonce');

			if (!orderId || !nonce) {
				return;
			}

			btn.disabled    = true;
			var origText    = btn.textContent;
			btn.textContent = i18n.reordering || 'Adding to cart…';

			var body = new URLSearchParams();
			body.append('action', cfg.actionReorder || 'kramar_reorder');
			body.append('order_id', orderId);
			body.append('nonce', nonce);

			fetch(cfg.ajaxUrl || '', {
				method: 'POST',
				headers: { 'X-Requested-With': 'XMLHttpRequest' },
				body: body
			})
				.then(function (r) { return r.json(); })
				.then(function (d) {
					if (d && d.success && d.data && d.data.cart_url) {
						window.location.href = d.data.cart_url;
					} else {
						var msg = (d && d.data && d.data.message) ? d.data.message : (i18n.error || 'Error');
						window.alert(msg);
						btn.disabled    = false;
						btn.textContent = origText;
					}
				})
				.catch(function () {
					window.alert(i18n.error || 'Something went wrong.');
					btn.disabled    = false;
					btn.textContent = origText;
				});
		});
	}

	// -------------------------------------------------------------------------
	// Email-first login (classic checkout only)
	// -------------------------------------------------------------------------

	function initEmailFirst() {
		if (!cfg.emailFirstEnabled) {
			return;
		}

		var emailInput = document.getElementById('kramar-login-email');
		var statusEl   = document.getElementById('kramar-email-first-status');

		if (!emailInput || !statusEl) {
			return;
		}

		var nonce = emailInput.getAttribute('data-nonce') || '';

		// When the user leaves the email field, check if account exists.
		emailInput.addEventListener('blur', function () {
			var email = emailInput.value.trim();
			if (!email || !email.includes('@')) {
				return;
			}

			statusEl.style.display = '';
			statusEl.style.color   = '#50575e';
			statusEl.textContent   = i18n.checkingEmail || 'Checking…';

			var body = new URLSearchParams();
			body.append('action', cfg.actionEmailCheck || 'kramar_email_check');
			body.append('email', email);
			body.append('nonce', nonce);

			fetch(cfg.ajaxUrl || '', {
				method: 'POST',
				headers: { 'X-Requested-With': 'XMLHttpRequest' },
				body: body
			})
				.then(function (r) { return r.json(); })
				.then(function (d) {
					if (!d || !d.success) {
						statusEl.style.display = 'none';
						return;
					}
					statusEl.style.display = '';
					if (d.data && d.data.has_account) {
						statusEl.style.color = '#197a1d';
						statusEl.textContent = i18n.hasAccount || 'Welcome back! Enter your password below.';
					} else {
						statusEl.style.color = '#50575e';
						statusEl.textContent = i18n.noAccount || 'No account found. You can register below.';
					}
				})
				.catch(function () {
					statusEl.style.display = 'none';
				});
		});
	}

	// -------------------------------------------------------------------------
	// Admin: show/hide custom URL field for login redirect
	// -------------------------------------------------------------------------

	function initAdminRedirectToggle() {
		var radios = document.querySelectorAll('input[name*="[login_redirect]"]');
		var panel  = document.getElementById('kramar-account-flow-custom-url');

		if (!radios.length || !panel) {
			return;
		}

		radios.forEach(function (r) {
			r.addEventListener('change', function () {
				panel.style.display = r.value === 'custom' ? '' : 'none';
			});
		});
	}

	// -------------------------------------------------------------------------
	// Init
	// -------------------------------------------------------------------------

	function init() {
		initAccountCta();
		initReorder();
		initEmailFirst();
		initAdminRedirectToggle();
	}

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