(function () {
	'use strict';

	function setRowsVisible(rows, visible) {
		rows.forEach(function (row) {
			row.style.display = visible ? '' : 'none';
		});
	}

	function getConfig() {
		return window.solarDawnWidgetAdmin || {
			ajaxUrl: '',
			nonce: '',
			selectedState: '',
			selectedCity: '',
			i18n: {}
		};
	}

	function getSelectedOption(select) {
		return select && select.options ? select.options[select.selectedIndex] : null;
	}

	function setValue(id, value) {
		var field = document.getElementById(id);

		if (field && value !== undefined && value !== null && value !== '') {
			field.value = value;
		}
	}

	function syncFieldsFromOption(option) {
		if (!option) {
			return;
		}

		setValue('solardawn-lat', option.getAttribute('data-lat'));
		setValue('solardawn-lon', option.getAttribute('data-lon'));
		setValue('solardawn-timezone', option.getAttribute('data-timezone'));
		setValue('solardawn-location-name', option.getAttribute('data-location-name') || option.value);
	}

	function requestLocation(action, payload) {
		var config = getConfig();
		var body = new URLSearchParams();

		body.append('action', action);
		body.append('nonce', config.nonce || '');

		Object.keys(payload || {}).forEach(function (key) {
			body.append(key, payload[key]);
		});

		return fetch(config.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
			},
			body: body.toString()
		}).then(function (response) {
			return response.json();
		});
	}

	function addOption(select, item, selectedValue) {
		var option = document.createElement('option');
		var name = item.name || '';

		option.value = name;
		option.textContent = name;
		option.setAttribute('data-lat', item.lat || '');
		option.setAttribute('data-lon', item.lon || '');
		option.setAttribute('data-timezone', item.timezone || '');
		option.setAttribute('data-location-name', name);

		if (selectedValue && selectedValue.toLowerCase() === name.toLowerCase()) {
			option.selected = true;
		}

		select.appendChild(option);
	}

	function setPlaceholder(select, label) {
		var option = document.createElement('option');

		option.value = '';
		option.textContent = label;
		select.appendChild(option);
	}

	function populateSelect(select, items, placeholder, selectedValue, emptyLabel) {
		select.innerHTML = '';

		if (!items || !items.length) {
			setPlaceholder(select, emptyLabel || placeholder);
			select.disabled = true;
			return;
		}

		setPlaceholder(select, placeholder);
		items.forEach(function (item) {
			addOption(select, item, selectedValue);
		});
		select.disabled = false;
	}

	function initSolarDawnAdmin() {
		var config = getConfig();
		var mode = document.getElementById('solardawn-location-mode');
		var country = document.getElementById('solardawn-country');
		var state = document.getElementById('solardawn-state');
		var city = document.getElementById('solardawn-city');
		var countryRows = Array.prototype.slice.call(document.querySelectorAll('.solardawn-field-country'));
		var locationRows = Array.prototype.slice.call(document.querySelectorAll('.solardawn-field-location'));
		var manualRows = Array.prototype.slice.call(document.querySelectorAll('.solardawn-field-manual'));
		var privacyNote = document.querySelector('.solardawn-privacy-note');
		var i18n = config.i18n || {};

		if (!mode || !country || !state || !city) {
			return;
		}

		function updateVisibility() {
			var value = mode.value;

			setRowsVisible(countryRows, value === 'country' || value === 'detect');
			setRowsVisible(locationRows, value === 'country');
			setRowsVisible(manualRows, value === 'manual');

			if (privacyNote) {
				privacyNote.style.display = value === 'detect' ? 'block' : 'none';
			}
		}

		function loadCities(selectedCity) {
			var selectedState = getSelectedOption(state);

			if (!state.value) {
				populateSelect(city, [], i18n.selectCity || 'Select a city', '', i18n.noCities || 'No cities found for this state');
				return;
			}

			syncFieldsFromOption(selectedState);
			populateSelect(city, [], i18n.loading || 'Loading...', '', i18n.loading || 'Loading...');

			requestLocation('solardawn_sun_widget_get_cities', {
				country: country.value,
				state: state.value
			}).then(function (response) {
				var data = response && response.success ? response.data : {};

				populateSelect(city, data.cities || [], i18n.selectCity || 'Select a city', selectedCity || '', i18n.noCities || 'No cities found for this state');

				if (selectedCity) {
					syncFieldsFromOption(getSelectedOption(city));
				}
			}).catch(function () {
				populateSelect(city, [], i18n.selectCity || 'Select a city', '', i18n.noCities || 'No cities found for this state');
			});
		}

		function loadStates(selectedState, selectedCity) {
			syncFieldsFromOption(getSelectedOption(country));
			populateSelect(state, [], i18n.loading || 'Loading...', '', i18n.loading || 'Loading...');
			populateSelect(city, [], i18n.selectCity || 'Select a city', '', i18n.noCities || 'No cities found for this state');

			requestLocation('solardawn_sun_widget_get_states', {
				country: country.value
			}).then(function (response) {
				var data = response && response.success ? response.data : {};

				populateSelect(state, data.states || [], i18n.selectState || 'Select a state or region', selectedState || '', i18n.noStates || 'No states found for this country');

				if (selectedState) {
					loadCities(selectedCity || '');
				}
			}).catch(function () {
				populateSelect(state, [], i18n.selectState || 'Select a state or region', '', i18n.noStates || 'No states found for this country');
			});
		}

		mode.addEventListener('change', updateVisibility);

		country.addEventListener('change', function () {
			config.selectedState = '';
			config.selectedCity = '';

			if (mode.value === 'country') {
				loadStates('', '');
			} else {
				syncFieldsFromOption(getSelectedOption(country));
			}
		});

		state.addEventListener('change', function () {
			config.selectedCity = '';
			loadCities('');
		});

		city.addEventListener('change', function () {
			syncFieldsFromOption(getSelectedOption(city));
		});

		updateVisibility();

		if (mode.value === 'country' && state.options.length <= 1) {
			loadStates(config.selectedState || '', config.selectedCity || '');
		}
	}

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