/**
 * Injects a "Staff Email" input alongside the Radius Booking toggle
 * in the Classified Listing Form Builder frontend.
 *
 * Shows only when Enable Booking is ON. Required field.
 *
 * @package RadiusTheme\RadiusBooking
 */
(function () {
	'use strict';

	var config = window.rtrbClForm || {};
	var injected = false;
	var emailFieldEl = null;
	var bookingContainer = null;

	// Strict gating happens inside tryInject() once we can read the rtrb
	// element's actual settings from the rendered form. We don't bail at
	// module load: on new-listing pages the form (and therefore its
	// rtrb_mapping_mode / rtrb_staff_email_enabled) is unknown until CL
	// renders the chosen form's fields.

	/**
	 * Look up the rtrb element's settings (rtrb_mapping_mode +
	 * rtrb_staff_email_enabled) for the rendered form.
	 *
	 * CL localizes window.rtclFB on the listing-form page with `form` (the
	 * active form when editing) and `forms` (every published form when
	 * adding a new listing). We match the rendered wrapper's data-id (the
	 * field uuid) against fields in those forms.
	 *
	 * @param {HTMLElement} wrap The .rtcl-fb-field-wrap wrapper.
	 * @returns {{mapping: string, staffEmail: boolean}|null}
	 */
	function resolveFieldSettings(wrap) {
		if (!wrap) return null;
		var uuid = wrap.getAttribute('data-id');
		if (!uuid) return null;

		var fb = window.rtclFB || {};
		var formsToScan = [];
		if (fb.form) formsToScan.push(fb.form);
		if (fb.forms && fb.forms.length) formsToScan = formsToScan.concat(fb.forms);

		function matchInFields(fields) {
			if (!fields) return null;
			if (Array.isArray(fields)) {
				for (var i = 0; i < fields.length; i++) {
					if (fields[i] && fields[i].uuid === uuid) return fields[i];
				}
				return null;
			}
			if (typeof fields === 'object') {
				if (fields[uuid]) return fields[uuid];
				for (var k in fields) {
					if (fields[k] && fields[k].uuid === uuid) return fields[k];
				}
			}
			return null;
		}

		for (var i = 0; i < formsToScan.length; i++) {
			var f = formsToScan[i];
			if (!f) continue;
			var match = matchInFields(f.fields);
			if (match) {
				return {
					mapping: match.rtrb_mapping_mode || 'use_global',
					staffEmail: match.rtrb_staff_email_enabled === true
						|| match.rtrb_staff_email_enabled === 'yes'
						|| match.rtrb_staff_email_enabled === 1
						|| match.rtrb_staff_email_enabled === '1'
				};
			}
		}
		return null;
	}

	/**
	 * Strict gate: inject only when the form's rtrb element is in 'staff'
	 * mapping AND its Staff Email Field toggle is on.
	 *
	 * 'use_global' mapping defers to config.isStaffMode (the global mode,
	 * resolved server-side). Service mode → returns false → no injection.
	 *
	 * @param {HTMLElement} wrap
	 * @returns {boolean}
	 */
	function shouldInject(wrap) {
		var settings = resolveFieldSettings(wrap);
		var staffMode;
		var staffEmail;

		if (settings) {
			if (settings.mapping === 'staff') {
				staffMode = true;
			} else if (settings.mapping === 'service') {
				staffMode = false;
			} else {
				staffMode = !!config.isStaffMode;
			}
			staffEmail = settings.staffEmail;
		} else {
			// Couldn't resolve form data — fall back to PHP-localized values.
			staffMode = !!config.isStaffMode;
			staffEmail = !!config.staffEmailEnabled;
		}
		return staffMode && staffEmail;
	}

	/**
	 * Build the staff email field HTML.
	 */
	function buildStaffEmailField() {
		var wrapper = document.createElement('div');
		wrapper.className = 'rtcl-fb-field-wrap rtrb-staff-email-field';
		wrapper.style.display = 'none'; // Hidden by default until booking is enabled.

		var inner = document.createElement('div');
		inner.className = 'rtcl-fb-field';

		var labelWrap = document.createElement('div');
		labelWrap.className = 'rtcl-fb-field-label';

		var label = document.createElement('label');
		label.className = 'rtcl-field-label';
		label.textContent = config.staffEmailLabel || 'Staff Email';
		label.setAttribute('for', 'rtrb-staff-email');

		var required = document.createElement('span');
		required.className = 'required';
		required.textContent = '*';

		labelWrap.appendChild(label);
		labelWrap.appendChild(required);

		var contentWrap = document.createElement('div');
		contentWrap.className = 'rtcl-fb-field-content';

		var input = document.createElement('input');
		input.type = 'email';
		input.id = 'rtrb-staff-email';
		input.name = '_rtrb_staff_email';
		input.className = 'form-control';
		input.placeholder = config.staffEmailPlaceholder || 'staff@example.com';
		input.value = config.currentStaffEmail || '';
		input.required = true;

		contentWrap.appendChild(input);

		// Error message container (hidden initially).
		var errorWrap = document.createElement('div');
		errorWrap.className = 'rtcl-fb-errors rtrb-email-error';
		errorWrap.style.display = 'none';
		var errorMsg = document.createElement('div');
		errorMsg.className = 'rtcl-error';
		errorMsg.textContent = config.staffEmailRequired || 'Staff email is required.';
		errorWrap.appendChild(errorMsg);
		contentWrap.appendChild(errorWrap);

		if (config.staffEmailHelp) {
			var help = document.createElement('div');
			help.className = 'help-message';
			help.textContent = config.staffEmailHelp;
			contentWrap.appendChild(help);
		}

		inner.appendChild(labelWrap);
		inner.appendChild(contentWrap);
		wrapper.appendChild(inner);

		return wrapper;
	}

	/**
	 * Check if the booking switch is currently ON.
	 */
	function isBookingEnabled() {
		if (!bookingContainer) return false;
		// Ant Design Switch adds class "ant-switch-checked" when ON.
		var switchEl = bookingContainer.querySelector('.ant-switch');
		if (switchEl) {
			return switchEl.classList.contains('ant-switch-checked');
		}
		// Fallback: check aria-checked.
		var ariaSwitch = bookingContainer.querySelector('[role="switch"]');
		if (ariaSwitch) {
			return ariaSwitch.getAttribute('aria-checked') === 'true';
		}
		return false;
	}

	/**
	 * Show/hide the email field based on booking toggle state.
	 */
	function updateVisibility() {
		if (!emailFieldEl) return;
		if (isBookingEnabled()) {
			emailFieldEl.style.display = '';
		} else {
			emailFieldEl.style.display = 'none';
		}
	}

	/**
	 * Find the booking toggle field container.
	 *
	 * CL's form-builder frontend wraps our preset in a div with
	 * data-element="rtrb_booking_enabled" (the element type name, not the
	 * generic "switch"). The switch itself is a stateful antd Switch with
	 * no hidden input, so we anchor on the wrapper.
	 */
	function findBookingToggle() {
		var rtrbWrap = document.querySelector('.rtcl-fb-field-wrap[data-element="rtrb_booking_enabled"]');
		if (rtrbWrap) {
			return rtrbWrap;
		}

		// Fallbacks for older / non-React markup.
		var switchWraps = document.querySelectorAll('.rtcl-fb-field-wrap[data-element="switch"]');
		for (var i = 0; i < switchWraps.length; i++) {
			var labelEl = switchWraps[i].querySelector('.rtcl-field-label');
			if (labelEl) {
				var text = labelEl.textContent.trim().toLowerCase();
				if (text.indexOf('booking') !== -1 || text.indexOf('rtrb') !== -1) {
					return switchWraps[i];
				}
			}
		}
		var hiddenInput = document.querySelector('input[name="_rtrb_booking_enabled"]');
		if (hiddenInput) {
			return hiddenInput.closest('.rtcl-fb-field-wrap') || hiddenInput.parentElement;
		}
		return null;
	}

	/**
	 * Try to inject the staff email field and set up toggle watching.
	 */
	function tryInject() {
		if (injected) {
			updateVisibility();
			return;
		}
		if (document.querySelector('.rtrb-staff-email-field')) {
			injected = true;
			return;
		}

		bookingContainer = findBookingToggle();
		if (!bookingContainer) return;

		// Read the rendered form's rtrb element settings and gate strictly:
		// only inject when mapping is 'staff' AND the Staff Email Field
		// toggle is on. Service mode bails here without injecting.
		if (!shouldInject(bookingContainer)) {
			return;
		}

		emailFieldEl = buildStaffEmailField();
		bookingContainer.parentElement.insertBefore(emailFieldEl, bookingContainer.nextSibling);
		injected = true;

		// Set initial visibility.
		updateVisibility();

		// Watch for clicks on the switch to toggle visibility.
		bookingContainer.addEventListener('click', function () {
			setTimeout(updateVisibility, 50);
		});
	}

	/**
	 * Validate before submission.
	 */
	function validateEmail() {
		if (!emailFieldEl || emailFieldEl.style.display === 'none') return true;
		var input = document.getElementById('rtrb-staff-email');
		var errorEl = emailFieldEl.querySelector('.rtrb-email-error');
		if (!input || !input.value.trim()) {
			if (errorEl) errorEl.style.display = '';
			if (input) input.style.borderColor = '#dc3545';
			return false;
		}
		if (errorEl) errorEl.style.display = 'none';
		if (input) input.style.borderColor = '';
		return true;
	}

	/**
	 * Intercept XMLHttpRequest to append staff email + validate.
	 */
	var originalXHRSend = XMLHttpRequest.prototype.send;
	XMLHttpRequest.prototype.send = function (data) {
		if (data instanceof FormData) {
			var action = data.get('action');
			if (action === 'rtcl_update_listing' || action === 'rtcl_post_new_listing') {
				if (!validateEmail()) {
					// Don't block submission — CL handles errors its own way.
					// Just show the error UI.
				}
				var emailInput = document.getElementById('rtrb-staff-email');
				if (emailInput && emailInput.value) {
					data.append('_rtrb_staff_email', emailInput.value);
				}
			}
		}
		return originalXHRSend.apply(this, arguments);
	};

	if (window.fetch) {
		var originalFetch = window.fetch;
		window.fetch = function (input, init) {
			if (init && init.body instanceof FormData) {
				var action = init.body.get('action');
				if (action === 'rtcl_update_listing' || action === 'rtcl_post_new_listing') {
					validateEmail();
					var emailInput = document.getElementById('rtrb-staff-email');
					if (emailInput && emailInput.value) {
						init.body.append('_rtrb_staff_email', emailInput.value);
					}
				}
			}
			return originalFetch.apply(this, arguments);
		};
	}

	// MutationObserver to detect React rendering.
	var observer = new MutationObserver(function () {
		tryInject();
	});

	function init() {
		tryInject();
		var target = document.getElementById('rtcl-post-form')
			|| document.querySelector('.rtcl-post-form')
			|| document.body;
		observer.observe(target, { childList: true, subtree: true });
		setTimeout(function () { observer.disconnect(); }, 30000);
	}

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