/**
 * Deployment Configuration Management JavaScript
 */
document.addEventListener('DOMContentLoaded', function() {
	const form = document.getElementById('configMethodForm');
	
	if (!form) {
		return;
	}
	
	const radioButtons = form.querySelectorAll('input[name="configuration_method"]');
	const saveBtn = document.getElementById('saveConfigBtn');
	const confirmAutoBtn = document.getElementById('confirmAutoBtn');
	const autoOption = document.getElementById('configAuto');
	const manualOption = document.getElementById('configManual');
	
	const config = window.deploymentConfigManagement || {};
	const currentMethod = config.currentMethod || '';
	const endpoint = config.endpoint || '';
	const nonce = config.nonce || '';
	const confirmMessage = config.confirmMessage || 'Are you sure you want to enable automatic configuration?';
	const errorMessage = config.errorMessage || 'Error saving configuration method';
	
	let selectedMethod = currentMethod;

	function updateButtonVisibility() {
		const newSelection = form.querySelector('input[name="configuration_method"]:checked')?.value;
		
		if (newSelection !== currentMethod) {
			if (newSelection === 'auto') {
				// Show confirmation button for auto mode
				saveBtn.style.display = 'none';
				confirmAutoBtn.style.display = '';
			} else {
				// Show regular save button for manual mode
				saveBtn.style.display = '';
				confirmAutoBtn.style.display = 'none';
			}
		} else {
			// No change, hide buttons
			saveBtn.style.display = 'none';
			confirmAutoBtn.style.display = 'none';
		}
	}

	function updateCardStyles() {
		const selected = form.querySelector('input[name="configuration_method"]:checked')?.value;
		
		// Update auto card
		const autoCard = autoOption.closest('.form-check');
		if (autoCard) {
			if (selected === 'auto') {
				autoCard.style.borderColor = '#d4edda';
				autoCard.style.backgroundColor = '#f8fff9';
			} else {
				autoCard.style.borderColor = '#dee2e6';
				autoCard.style.backgroundColor = '#f8f9fa';
			}
		}
		
		// Update manual card
		const manualCard = manualOption.closest('.form-check');
		if (manualCard) {
			if (selected === 'manual') {
				manualCard.style.borderColor = '#d1ecf1';
				manualCard.style.backgroundColor = '#f8f9ff';
			} else {
				manualCard.style.borderColor = '#dee2e6';
				manualCard.style.backgroundColor = '#f8f9fa';
			}
		}
	}

	// Event listeners for radio buttons
	radioButtons.forEach(radio => {
		radio.addEventListener('change', function() {
			selectedMethod = this.value;
			updateButtonVisibility();
			updateCardStyles();
		});
	});

	// Save button handler (for manual or no change)
	if (saveBtn) {
		saveBtn.addEventListener('click', function(e) {
			e.preventDefault();
			saveConfiguration(selectedMethod);
		});
	}

	// Confirmation button handler (for auto mode)
	if (confirmAutoBtn) {
		confirmAutoBtn.addEventListener('click', function(e) {
			e.preventDefault();
			
			const confirmed = confirm(confirmMessage);
			
			if (confirmed) {
				saveConfiguration('auto');
			}
		});
	}

	function saveConfiguration(method) {
		if (!endpoint || !nonce) {
			console.error('Missing endpoint or nonce for AJAX request');
			alert(errorMessage + ': Missing configuration');
			return;
		}
		
		// Disable buttons during save
		if (saveBtn) saveBtn.disabled = true;
		if (confirmAutoBtn) confirmAutoBtn.disabled = true;
		
		fetch(endpoint, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'X-WP-Nonce': nonce
			},
			body: JSON.stringify({
				configuration_method: method
			})
		})
		.then(response => response.json())
		.then(data => {
			if (data.success) {
				// Reload page to update the refresh button visibility
				window.location.reload();
			} else {
				alert(errorMessage + ': ' + (data.message || 'Unknown error'));
				// Revert selection
				const revertRadio = form.querySelector(`input[value="${currentMethod}"]`);
				if (revertRadio) {
					revertRadio.checked = true;
				}
				selectedMethod = currentMethod;
				updateButtonVisibility();
				updateCardStyles();
			}
		})
		.catch(error => {
			console.error('Error:', error);
			alert(errorMessage);
			// Revert selection
			const revertRadio = form.querySelector(`input[value="${currentMethod}"]`);
			if (revertRadio) {
				revertRadio.checked = true;
			}
			selectedMethod = currentMethod;
			updateButtonVisibility();
			updateCardStyles();
		})
		.finally(() => {
			// Re-enable buttons
			if (saveBtn) saveBtn.disabled = false;
			if (confirmAutoBtn) confirmAutoBtn.disabled = false;
		});
	}

	// Initial setup
	updateButtonVisibility();
	updateCardStyles();
});
