/**
 * Admin JavaScript for FoodOrd Delivery page.
 *
 * @package Foodord
 */

(function($) {
	'use strict';

	let wrcLocationRowCounter = 0;
	let wrcRadiusZoneCounter = 0;
	let wrcRadiusMapInstance = null;
	let wrcRadiusMapMarker = null;
	let wrcRadiusMapLegend = null;
	let wrcRadiusMapCircles = [];
	let wrcRadiusMapPromise = null;
	let wrcRadiusMapContainer = null;
	let wrcRadiusMapApiKey = '';
	let wrcRadiusMapCenter = null;
	let wrcRadiusMapRefreshTimer = null;

	$(document).ready(function() {
		// Auto hide only success notices after saving (after 5 seconds)
		const $successNotice = $('.notice.notice-success.is-dismissible');
		if ($successNotice.length > 0) {
			setTimeout(function() {
				$successNotice.fadeOut(500, function() {
					$(this).remove();
				});
			}, 5000);
		}

		// Add day toggle functionality
		$('.wrc-closed-label input[type="checkbox"]').on('change', function() {
			const row = $(this).closest('.wrc-day-row');
			const timeInputs = row.find('.wrc-time-input');

			if ($(this).is(':checked')) {
				timeInputs.prop('disabled', true);
			} else {
				timeInputs.prop('disabled', false);
			}
		});

		// Initialize state based on existing values
		$('.wrc-closed-label input[type="checkbox"]').each(function() {
			const row = $(this).closest('.wrc-day-row');
			const timeInputs = row.find('.wrc-time-input');

			if ($(this).is(':checked')) {
				timeInputs.prop('disabled', true);
			}
		});

		// Custom hours modal functionality
		$('#wrc-add-custom-hour-btn').on('click', function() {
			$('#wrc-custom-hours-modal').addClass('is-open');
			$('body').css('overflow', 'hidden');
		});

		$('#wrc-modal-close-btn, #wrc-modal-cancel-btn').on('click', function() {
			wrcCloseCustomHoursModal();
		});

		$('#wrc-modal-save-btn').on('click', function() {
			wrcSaveCustomHours();
		});

		$('#custom-closed').on('change', function() {
			wrcToggleCustomTimeInputs(this);
		});

		// Load custom hours on page load
		wrcLoadCustomHours();

		// Initialize radius zones UI
		wrcInitRadiusZones();

		// Initialize location based fee UI
		wrcInitLocationBasedFee();

		// Initialize delivery mode toggle
		wrcInitDeliveryModeToggle();

		// Initialize preorder toggle functionality
		wrcInitPreorderToggle();

		// Initialize scheduled date toggle functionality
		wrcInitScheduledDateToggle();

		// Update hidden input before form submission
		$('form').on('submit', function() {
			if ($(this).find('#wrc_custom_hours').length) {
				wrcUpdateCustomHoursInput();
			}

			if ($(this).find('#wrc_delivery_locations').length) {
				wrcUpdateDeliveryLocationsInput();
			}

			if ($(this).find('#wrc_radius_zones').length) {
				wrcUpdateRadiusZonesInput();
			}
		});

		// Close modal when clicking outside
		$(document).on('click', function(e) {
			if (e.target.id === 'wrc-custom-hours-modal') {
				wrcCloseCustomHoursModal();
			}
		});
	});

	function wrcInitLocationBasedFee() {
		const locationContainer = document.getElementById('wrc-location-based');
		const addLocationBtn = document.getElementById('wrc-add-location-btn');
		const feeRadios = document.querySelectorAll('input[name="wrc_delivery_fee_type"]');
		const fixedAmountInput = document.getElementById('wrc_delivery_fee_fixed');

		wrcLoadDeliveryLocations();

		if (addLocationBtn) {
			addLocationBtn.addEventListener('click', function() {
				const newRow = wrcAddLocationRow();
				if (newRow) {
					const cityInput = newRow.querySelector('.wrc-location-input--city');
					if (cityInput) {
						cityInput.focus();
					}
				}
			});
		}

		feeRadios.forEach(function(radio) {
			radio.addEventListener('change', function() {
				wrcToggleFeeTypeUI(radio.value, locationContainer, fixedAmountInput);
			});
		});

		const checkedRadio = document.querySelector('input[name="wrc_delivery_fee_type"]:checked');
		if (checkedRadio) {
			wrcToggleFeeTypeUI(checkedRadio.value, locationContainer, fixedAmountInput);
		}
	}

	function wrcInitDeliveryModeToggle() {
		const modeRadios = document.querySelectorAll('input[name="wrc_delivery_mode"]');
		const modeSections = document.querySelectorAll('[data-wrc-mode-section]');
		const modeOptions = document.querySelectorAll('[data-wrc-mode-option]');
		const locationContainer = document.getElementById('wrc-location-based');
		const addLocationBtn = document.getElementById('wrc-add-location-btn');

		if (!modeRadios.length) {
			return;
		}

		const sync = function() {
			const checked = document.querySelector('input[name="wrc_delivery_mode"]:checked');
			const activeMode = checked ? checked.value : 'postal';

			modeSections.forEach(function(section) {
				const sectionMode = section.getAttribute('data-wrc-mode-section');
				section.classList.toggle('is-mode-active', sectionMode === activeMode);
			});

			modeOptions.forEach(function(option) {
				const optionMode = option.getAttribute('data-wrc-mode-option');
				option.classList.toggle('is-selected', optionMode === activeMode);
			});

			if (locationContainer) {
				locationContainer.classList.toggle('is-active', 'postal' === activeMode);
				const inputs = locationContainer.querySelectorAll('.wrc-location-input');
				inputs.forEach(function(input) {
					input.disabled = ('postal' !== activeMode);
				});
			}

			if (addLocationBtn) {
				addLocationBtn.disabled = ('postal' !== activeMode);
			}
			if ('radius' === activeMode) {
				wrcRefreshRadiusMapDebounced();
			}
		};

		modeRadios.forEach(function(radio) {
			radio.addEventListener('change', sync);
		});

		sync();
	}

	function wrcGetRadiusZoneConfig(container) {
		const el = container || document.getElementById('wrc-radius-zones');
		return {
			radiusLabel: el ? el.getAttribute('data-radius-label') || 'Radius (km)' : 'Radius (km)',
			radiusPlaceholder: el ? el.getAttribute('data-radius-placeholder') || 'e.g. 5' : 'e.g. 5',
			minimumLabel: el ? el.getAttribute('data-minimum-label') || 'Minimum order' : 'Minimum order',
			minimumPlaceholder: el ? el.getAttribute('data-minimum-placeholder') || 'e.g. 10.00' : 'e.g. 10.00',
			feeLabel: el ? el.getAttribute('data-fee-label') || 'Delivery fee' : 'Delivery fee',
			feePlaceholder: el ? el.getAttribute('data-fee-placeholder') || 'e.g. 1.50' : 'e.g. 1.50',
			labelLabel: el ? el.getAttribute('data-label-label') || 'Label (optional)' : 'Label (optional)',
			labelPlaceholder: el ? el.getAttribute('data-label-placeholder') || '' : '',
			removeLabel: el ? el.getAttribute('data-remove-label') || 'Remove zone' : 'Remove zone',
			removeText: el ? el.getAttribute('data-remove-text') || 'Remove' : 'Remove',
			titlePlaceholder: el ? el.getAttribute('data-title-placeholder') || 'Radius zone' : 'Radius zone'
		};
	}

	function wrcUpdateRadiusZoneTitle(row, config) {
		const cfg = config || wrcGetRadiusZoneConfig();
		const title = row.querySelector('.wrc-radius-zone-title');
		const radiusInput = row.querySelector('.wrc-radius-zone-input--radius');
		if (!title || !radiusInput) {
			return;
		}
		const raw = radiusInput.value ? radiusInput.value.toString().trim().replace(',', '.') : '';
		const num = parseFloat(raw);
		if (Number.isFinite(num) && num > 0) {
			title.textContent = '≤ ' + num + ' km';
		} else {
			title.textContent = cfg.titlePlaceholder;
		}
	}

	function wrcLoadGoogleMaps(apiKey) {
		if (window.google && window.google.maps) {
			return Promise.resolve(window.google.maps);
		}
		if (window._wrcGoogleMapsLoader) {
			return window._wrcGoogleMapsLoader;
		}
		window._wrcGoogleMapsLoader = new Promise(function(resolve, reject) {
			const script = document.createElement('script');
		const lang = window.foodordDeliveryVars && window.foodordDeliveryVars.google_maps_language ? window.foodordDeliveryVars.google_maps_language : '';
		let src = 'https://maps.googleapis.com/maps/api/js?key=' + encodeURIComponent(apiKey) + '&libraries=maps';
		if (lang) {
			src += '&language=' + encodeURIComponent(lang);
		}
		script.src = src;
			script.async = true;
			script.defer = true;
			script.onload = function() {
				if (window.google && window.google.maps) {
					resolve(window.google.maps);
				} else {
					reject(new Error('Google Maps failed to load'));
				}
			};
			script.onerror = function() {
				reject(new Error('Google Maps script error'));
			};
			document.head.appendChild(script);
		});
		return window._wrcGoogleMapsLoader;
	}

	function wrcCollectRadiusZonesForMap() {
		const list = document.getElementById('wrc-radius-zone-list');
		if (!list) {
			return [];
		}
		const rows = list.querySelectorAll('.wrc-radius-zone-item');
		const zones = [];
		rows.forEach(function(row) {
			const radiusInput = row.querySelector('.wrc-radius-zone-input--radius');
			const minimumInput = row.querySelector('.wrc-radius-zone-input--minimum');
			const feeInput = row.querySelector('.wrc-radius-zone-input--fee');
			const labelInput = row.querySelector('.wrc-radius-zone-input--label');
			const radiusValue = radiusInput ? parseFloat((radiusInput.value || '').toString().trim().replace(',', '.')) : NaN;
			if (!Number.isFinite(radiusValue) || radiusValue <= 0) {
				return;
			}
			const zone = {
				radius: radiusValue,
				minimum: minimumInput ? parseFloat((minimumInput.value || '').toString().trim().replace(',', '.')) || 0 : 0,
				fee: feeInput ? parseFloat((feeInput.value || '').toString().trim().replace(',', '.')) || 0 : 0,
				label: labelInput ? labelInput.value.toString().trim() : ''
			};
			zones.push(zone);
		});
		zones.sort(function(a, b) { return a.radius - b.radius; });
		return zones;
	}

	function wrcFormatNumberForLegend(value) {
		if (!Number.isFinite(value)) {
			return value;
		}
		if (Math.abs(value) >= 1000) {
			return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
		}
		if (value % 1 === 0) {
			return value.toFixed(0);
		}
		return value.toFixed(2);
	}

	function wrcClearRadiusMapCircles() {
		if (!wrcRadiusMapCircles.length) {
			return;
		}
		wrcRadiusMapCircles.forEach(function(circle) {
			if (circle && typeof circle.setMap === 'function') {
				circle.setMap(null);
			}
		});
		wrcRadiusMapCircles = [];
	}

	function wrcUpdateRadiusMapLegend(zones) {
		if (!wrcRadiusMapContainer) {
			return;
		}
		if (!wrcRadiusMapLegend) {
			wrcRadiusMapLegend = document.createElement('div');
			wrcRadiusMapLegend.className = 'wrc-radius-map__legend';
			wrcRadiusMapContainer.appendChild(wrcRadiusMapLegend);
		}
		wrcRadiusMapLegend.innerHTML = '';
		if (!zones.length) {
			wrcRadiusMapLegend.style.display = 'none';
			return;
		}
		wrcRadiusMapLegend.style.display = '';
		const colors = ['#2563eb', '#0ea5e9', '#14b8a6', '#22c55e', '#f97316', '#f59e0b', '#ef4444'];
		zones.forEach(function(zone, index) {
			const color = colors[index % colors.length];
			const item = document.createElement('div');
			item.className = 'wrc-radius-map__legend-item';
			const swatch = document.createElement('span');
			swatch.className = 'wrc-radius-map__legend-swatch';
			swatch.style.backgroundColor = color;
			item.appendChild(swatch);
			const label = document.createElement('span');
			label.className = 'wrc-radius-map__legend-label';
			const value = document.createElement('span');
			value.className = 'wrc-radius-map__legend-value';
			value.textContent = '≤ ' + wrcFormatNumberForLegend(zone.radius) + ' km';
			label.appendChild(value);
			if (zone.label) {
				const custom = document.createElement('span');
				custom.textContent = zone.label;
				label.appendChild(custom);
			}
			if (zone.minimum > 0 || zone.fee > 0) {
				const details = document.createElement('span');
				details.textContent = '(' + (zone.minimum > 0 ? 'Min ' + wrcFormatNumberForLegend(zone.minimum) : 'No min') + ' / ' + (zone.fee > 0 ? 'Fee ' + wrcFormatNumberForLegend(zone.fee) : 'Free') + ')';
				label.appendChild(details);
			}
			item.appendChild(label);
			wrcRadiusMapLegend.appendChild(item);
		});
	}

	function wrcEnsureRadiusMap(center) {
		if (!wrcRadiusMapContainer) {
			return Promise.reject(new Error('No map container'));
		}
		wrcRadiusMapCenter = center || wrcRadiusMapCenter;
		if (!wrcRadiusMapCenter || !Number.isFinite(wrcRadiusMapCenter.lat) || !Number.isFinite(wrcRadiusMapCenter.lng)) {
			return Promise.reject(new Error('Missing coordinates'));
		}
		if (wrcRadiusMapInstance) {
			if (wrcRadiusMapMarker && typeof wrcRadiusMapMarker.setPosition === 'function') {
				wrcRadiusMapMarker.setPosition(wrcRadiusMapCenter);
			}
			return Promise.resolve(window.google.maps);
		}
		if (!wrcRadiusMapApiKey) {
			return Promise.reject(new Error('Missing API key'));
		}
		wrcRadiusMapPromise = wrcRadiusMapPromise || wrcLoadGoogleMaps(wrcRadiusMapApiKey).then(function(maps) {
			wrcRadiusMapInstance = new maps.Map(wrcRadiusMapContainer, {
				center: wrcRadiusMapCenter,
				zoom: 12,
				streetViewControl: false,
				mapTypeControl: false,
				fullscreenControl: false
			});
			wrcRadiusMapMarker = new maps.Marker({
				map: wrcRadiusMapInstance,
				position: wrcRadiusMapCenter,
				title: wrcRadiusMapContainer.getAttribute('data-store-address') || ''
			});
			wrcRadiusMapContainer.classList.add('is-ready');
			return maps;
		});
		return wrcRadiusMapPromise;
	}

	function wrcRefreshRadiusMap(force) {
		if (!wrcRadiusMapContainer) {
			return;
		}
		const placeholder = wrcRadiusMapContainer.querySelector('.wrc-radius-map__placeholder');
	const latAttr = wrcRadiusMapContainer.getAttribute('data-center-lat');
	const lngAttr = wrcRadiusMapContainer.getAttribute('data-center-lng');
	const lat = latAttr ? parseFloat(latAttr) : NaN;
	const lng = lngAttr ? parseFloat(lngAttr) : NaN;
		if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
			if (placeholder) {
				placeholder.textContent = 'Store coordinates unavailable. Save settings after configuring your store address and API key.';
			}
			return;
		}
		if (!wrcRadiusMapApiKey) {
			if (placeholder) {
				placeholder.textContent = 'Enter a Google Maps API key and save changes to view the delivery coverage map.';
			}
			return;
		}
		if (placeholder && !force) {
			placeholder.textContent = 'Loading map preview…';
		}
		wrcEnsureRadiusMap({ lat: lat, lng: lng }).then(function(maps) {
			const zones = wrcCollectRadiusZonesForMap();
			wrcClearRadiusMapCircles();
			if (!zones.length) {
				wrcUpdateRadiusMapLegend([]);
				return;
			}
			const colors = ['#2563eb', '#0ea5e9', '#14b8a6', '#22c55e', '#f97316', '#f59e0b', '#ef4444'];
			const bounds = new maps.LatLngBounds();
			bounds.extend(wrcRadiusMapCenter);
			zones.forEach(function(zone, index) {
				const color = colors[index % colors.length];
				const circle = new maps.Circle({
					map: wrcRadiusMapInstance,
					center: wrcRadiusMapCenter,
					radius: zone.radius * 1000,
					strokeColor: color,
					strokeOpacity: 0.65,
					strokeWeight: 1.5,
					fillColor: color,
					fillOpacity: 0.12
				});
				wrcRadiusMapCircles.push(circle);
				const latOffset = zone.radius / 111;
				const latRad = wrcRadiusMapCenter.lat * Math.PI / 180;
				const cosLat = Math.cos(latRad);
				const lngOffset = zone.radius / (111 * (cosLat === 0 ? 0.0001 : cosLat));
				bounds.extend(new maps.LatLng(wrcRadiusMapCenter.lat + latOffset, wrcRadiusMapCenter.lng + lngOffset));
				bounds.extend(new maps.LatLng(wrcRadiusMapCenter.lat - latOffset, wrcRadiusMapCenter.lng - lngOffset));
			});
			try {
				wrcRadiusMapInstance.fitBounds(bounds);
			} catch (e) {
				void e;
			}
			wrcUpdateRadiusMapLegend(zones);
		}).catch(function(error) {
			if (placeholder) {
				placeholder.textContent = error && error.message ? error.message : 'Unable to load map preview.';
			}
		});
	}

	function wrcRefreshRadiusMapDebounced() {
		if (wrcRadiusMapRefreshTimer) {
			clearTimeout(wrcRadiusMapRefreshTimer);
		}
		wrcRadiusMapRefreshTimer = setTimeout(function() {
			wrcRadiusMapRefreshTimer = null;
			wrcRefreshRadiusMap(true);
		}, 200);
	}

	function wrcInitRadiusMapSection() {
		wrcRadiusMapContainer = document.getElementById('wrc-radius-map');
		if (!wrcRadiusMapContainer) {
			return;
		}
		wrcRadiusMapApiKey = wrcRadiusMapContainer.getAttribute('data-api-key') || '';
		const placeholder = wrcRadiusMapContainer.querySelector('.wrc-radius-map__placeholder');
		if (!wrcRadiusMapApiKey) {
			if (placeholder) {
				placeholder.textContent = 'Enter a Google Maps API key and save to preview your delivery coverage.';
			}
			return;
		}
		const latAttr = wrcRadiusMapContainer.getAttribute('data-center-lat');
		const lngAttr = wrcRadiusMapContainer.getAttribute('data-center-lng');
		if (!latAttr || !lngAttr) {
			if (placeholder) {
				placeholder.textContent = 'Store coordinates not found. Save settings after verifying your WooCommerce store address.';
			}
			return;
		}
		const parentSection = wrcRadiusMapContainer.closest('[data-wrc-mode-section]');
		if (parentSection && !parentSection.classList.contains('is-mode-active')) {
			return;
		}
		wrcRefreshRadiusMap();
	}

	function wrcRemoveRadiusZoneRow(row) {
		if (!row) {
			return;
		}
		const list = document.getElementById('wrc-radius-zone-list');
		row.remove();
		wrcUpdateRadiusZoneEmptyState(list);
		wrcRefreshRadiusMapDebounced();
	}

	function wrcCreateRadiusZoneField(options) {
		const field = document.createElement('div');
		field.className = 'wrc-radius-zone-field';
		const label = document.createElement('label');
		label.className = 'wrc-radius-zone-label';
		label.setAttribute('for', options.id);
		label.textContent = options.label;
		const input = document.createElement('input');
		input.type = options.type || 'text';
		input.id = options.id;
		input.className = options.className;
		if (options.placeholder) {
			input.placeholder = options.placeholder;
		}
		if (options.step) {
			input.step = options.step;
		}
		if (typeof options.min !== 'undefined') {
			input.min = options.min;
		}
		if (options.type === 'number') {
			input.inputMode = 'decimal';
		}
		if (typeof options.value !== 'undefined' && options.value !== null && options.value !== '') {
			input.value = options.value;
		}
		field.appendChild(label);
		field.appendChild(input);
		return { field: field, input: input };
	}

	function wrcAddRadiusZoneRow(preset, config) {
		const list = document.getElementById('wrc-radius-zone-list');
		if (!list) {
			return null;
		}
		const cfg = config || wrcGetRadiusZoneConfig();
		wrcRadiusZoneCounter += 1;
		const zoneIndex = wrcRadiusZoneCounter;
		const row = document.createElement('div');
		row.className = 'wrc-radius-zone-item';

		const header = document.createElement('div');
		header.className = 'wrc-radius-zone-header';
		const title = document.createElement('span');
		title.className = 'wrc-radius-zone-title';
		title.textContent = cfg.titlePlaceholder;
		const removeBtn = document.createElement('button');
		removeBtn.type = 'button';
		removeBtn.className = 'wrc-radius-zone-remove';
		removeBtn.textContent = cfg.removeText;
		removeBtn.setAttribute('aria-label', cfg.removeLabel);
		removeBtn.addEventListener('click', function() {
			wrcRemoveRadiusZoneRow(row);
		});
		header.appendChild(title);
		header.appendChild(removeBtn);
		row.appendChild(header);

		const grid = document.createElement('div');
		grid.className = 'wrc-radius-zone-grid';

		const radiusField = wrcCreateRadiusZoneField({
			id: 'wrc-radius-zone-radius-' + zoneIndex,
			label: cfg.radiusLabel,
			type: 'number',
			className: 'wrc-radius-zone-input wrc-radius-zone-input--radius',
			placeholder: cfg.radiusPlaceholder,
			step: '0.1',
			min: '0',
			value: preset && typeof preset.radius !== 'undefined' ? String(preset.radius) : ''
		});
		radiusField.input.addEventListener('input', function() {
			wrcUpdateRadiusZoneTitle(row, cfg);
			wrcRefreshRadiusMapDebounced();
		});

		const minimumField = wrcCreateRadiusZoneField({
			id: 'wrc-radius-zone-minimum-' + zoneIndex,
			label: cfg.minimumLabel,
			type: 'number',
			className: 'wrc-radius-zone-input wrc-radius-zone-input--minimum',
			placeholder: cfg.minimumPlaceholder,
			step: '0.01',
			min: '0',
			value: preset && typeof preset.minimum !== 'undefined' ? String(preset.minimum) : ''
		});
		minimumField.input.addEventListener('input', wrcRefreshRadiusMapDebounced);

		const feeField = wrcCreateRadiusZoneField({
			id: 'wrc-radius-zone-fee-' + zoneIndex,
			label: cfg.feeLabel,
			type: 'number',
			className: 'wrc-radius-zone-input wrc-radius-zone-input--fee',
			placeholder: cfg.feePlaceholder,
			step: '0.01',
			min: '0',
			value: preset && typeof preset.fee !== 'undefined' ? String(preset.fee) : ''
		});
		feeField.input.addEventListener('input', wrcRefreshRadiusMapDebounced);

		const labelField = wrcCreateRadiusZoneField({
			id: 'wrc-radius-zone-label-' + zoneIndex,
			label: cfg.labelLabel,
			type: 'text',
			className: 'wrc-radius-zone-input wrc-radius-zone-input--label',
			placeholder: cfg.labelPlaceholder,
			value: preset && typeof preset.label !== 'undefined' ? String(preset.label) : ''
		});
		labelField.input.addEventListener('input', wrcRefreshRadiusMapDebounced);

		grid.appendChild(radiusField.field);
		grid.appendChild(minimumField.field);
		grid.appendChild(feeField.field);
		grid.appendChild(labelField.field);
		row.appendChild(grid);

		list.appendChild(row);
		wrcUpdateRadiusZoneTitle(row, cfg);
		wrcUpdateRadiusZoneEmptyState(list);
		wrcRefreshRadiusMapDebounced();

		return row;
	}

	function wrcUpdateRadiusZoneEmptyState(listEl) {
		const list = listEl || document.getElementById('wrc-radius-zone-list');
		if (!list) {
			return;
		}
		const existingMessage = list.querySelector('.wrc-radius-zone-empty');
		if (existingMessage) {
			existingMessage.remove();
		}
		const items = list.querySelectorAll('.wrc-radius-zone-item');
		if (!items.length) {
			const message = list.getAttribute('data-empty-message');
			if (message) {
				const emptyEl = document.createElement('p');
				emptyEl.className = 'wrc-radius-zone-empty';
				emptyEl.textContent = message;
				list.appendChild(emptyEl);
			}
		}
	}

	function wrcLoadRadiusZones(hiddenInput, list, config) {
		if (!hiddenInput || !list) {
			return;
		}
		let stored = [];
		if (hiddenInput.value) {
			try {
				stored = JSON.parse(hiddenInput.value);
			} catch {
				stored = [];
			}
		}
		if (Array.isArray(stored) && stored.length) {
			stored.forEach(function(zone) {
				wrcAddRadiusZoneRow({
					radius: typeof zone.radius !== 'undefined' ? zone.radius : '',
					minimum: typeof zone.minimum !== 'undefined' ? zone.minimum : '',
					fee: typeof zone.fee !== 'undefined' ? zone.fee : '',
					label: typeof zone.label !== 'undefined' ? zone.label : ''
				}, config);
			});
		}
		if (!list.querySelector('.wrc-radius-zone-item')) {
			wrcAddRadiusZoneRow(null, config);
		}
	}

	function wrcInitRadiusZones() {
		const hiddenInput = document.getElementById('wrc_radius_zones');
		const list = document.getElementById('wrc-radius-zone-list');
		const addBtn = document.getElementById('wrc-add-radius-zone-btn');
		const container = document.getElementById('wrc-radius-zones');
		if (!hiddenInput || !list || !addBtn || !container) {
			return;
		}
		const config = wrcGetRadiusZoneConfig(container);
		wrcLoadRadiusZones(hiddenInput, list, config);
		wrcUpdateRadiusZoneEmptyState(list);
		addBtn.addEventListener('click', function() {
			const row = wrcAddRadiusZoneRow(null, config);
			if (row) {
				const radiusInput = row.querySelector('.wrc-radius-zone-input--radius');
				if (radiusInput) {
					radiusInput.focus();
				}
			}
		});
		wrcInitRadiusMapSection();
	}

	function wrcUpdateRadiusZonesInput() {
		const hiddenInput = document.getElementById('wrc_radius_zones');
		const list = document.getElementById('wrc-radius-zone-list');
		if (!hiddenInput || !list) {
			return;
		}
		const rows = list.querySelectorAll('.wrc-radius-zone-item');
		const zones = [];
		const toNumber = function(value, decimals) {
			if (typeof value !== 'string') {
				value = String(value || '');
			}
			const normalized = value.trim().replace(',', '.');
			if (!normalized) {
				return null;
			}
			const num = parseFloat(normalized);
			if (!Number.isFinite(num)) {
				return null;
			}
			const positive = num < 0 ? 0 : num;
			if (typeof decimals === 'number') {
				return parseFloat(positive.toFixed(decimals));
			}
			return positive;
		};
		rows.forEach(function(row) {
			const radiusInput = row.querySelector('.wrc-radius-zone-input--radius');
			if (!radiusInput) {
				return;
			}
			const radiusVal = toNumber(radiusInput.value, 3);
			if (radiusVal === null || radiusVal <= 0) {
				return;
			}
			const minimumInput = row.querySelector('.wrc-radius-zone-input--minimum');
			const feeInput = row.querySelector('.wrc-radius-zone-input--fee');
			const labelInput = row.querySelector('.wrc-radius-zone-input--label');
			const minimumVal = minimumInput ? toNumber(minimumInput.value, 2) : null;
			const feeVal = feeInput ? toNumber(feeInput.value, 2) : null;
			const labelVal = labelInput ? labelInput.value.trim() : '';
			zones.push({
				radius: radiusVal,
				minimum: minimumVal !== null ? minimumVal : 0,
				fee: feeVal !== null ? feeVal : 0,
				label: labelVal
			});
		});
		zones.sort(function(a, b) {
			return a.radius - b.radius;
		});
		hiddenInput.value = JSON.stringify(zones);
	}

	function wrcToggleFeeTypeUI(selectedValue, locationContainer, fixedInput) {
		const container = locationContainer || document.getElementById('wrc-location-based');
		const fixedField = fixedInput || document.getElementById('wrc_delivery_fee_fixed');
		let locationInputs = null;

		if ('distance' === selectedValue) {
			if (container) {
				container.classList.add('is-active');
				container.removeAttribute('hidden');
				if (!container.querySelector('.wrc-location-row')) {
					wrcAddLocationRow();
				}
				locationInputs = container.querySelectorAll('.wrc-location-input');
				if (locationInputs) {
					locationInputs.forEach(function(input) {
						input.disabled = false;
					});
				}
				wrcUpdateLocationEmptyState();
			}
			if (fixedField) {
				fixedField.disabled = true;
			}
		} else {
			if (container) {
				container.classList.remove('is-active');
				container.setAttribute('hidden', 'hidden');
				locationInputs = container.querySelectorAll('.wrc-location-input');
				if (locationInputs) {
					locationInputs.forEach(function(input) {
						input.disabled = true;
					});
				}
			}
			if (fixedField) {
				fixedField.disabled = false;
			}
		}
	}

	function wrcGetLocationConfig() {
		const container = document.getElementById('wrc-location-based');
		return {
			cityLabel: container ? container.getAttribute('data-city-label') || 'City' : 'City',
			cityPlaceholder: container ? container.getAttribute('data-city-placeholder') || 'e.g. Ankara' : 'e.g. Ankara',
			feeLabel: container ? container.getAttribute('data-fee-label') || 'Delivery Fee' : 'Delivery Fee',
			feePlaceholder: container ? container.getAttribute('data-fee-placeholder') || 'e.g. 5.00' : 'e.g. 5.00',
			minimumLabel: container ? container.getAttribute('data-minimum-label') || 'Minimum Order amount' : 'Minimum Order amount',
			minimumPlaceholder: container ? container.getAttribute('data-minimum-placeholder') || 'e.g. 10.00' : 'e.g. 10.00',
			removeLabel: container ? container.getAttribute('data-remove-label') || 'Remove location' : 'Remove location',
			removeText: container ? container.getAttribute('data-remove-text') || 'Remove' : 'Remove'
		};
	}

	function wrcAddLocationRow(preset) {
		const list = document.getElementById('wrc-location-list');
		const container = document.getElementById('wrc-location-based');

		if (!list) {
			return null;
		}

		const config = wrcGetLocationConfig();

		// Wrapper accordion item
		const item = document.createElement('div');
		item.className = 'wrc-accordion-item is-open';
		if (preset && typeof preset.postalCode !== 'undefined' && preset.postalCode) {
			item.dataset.postalCode = String(preset.postalCode);
		} else if (item.dataset) {
			delete item.dataset.postalCode;
		}

		// Header button
		const headerBtn = document.createElement('button');
		headerBtn.type = 'button';
		headerBtn.className = 'wrc-accordion-header';
		headerBtn.setAttribute('aria-expanded', 'true');
		const titleSpan = document.createElement('span');
		titleSpan.className = 'wrc-accordion-title';
		titleSpan.textContent = '';
		const chevron = document.createElement('span');
		chevron.className = 'wrc-accordion-chevron';
		headerBtn.appendChild(titleSpan);
		headerBtn.appendChild(chevron);

		// Body container
		const body = document.createElement('div');
		body.className = 'wrc-accordion-body';

		// Existing row markup inside body
		const row = document.createElement('div');
		row.className = 'wrc-location-row';

		wrcLocationRowCounter += 1;
		const cityId = 'wrc-location-city-' + wrcLocationRowCounter;

		const cityField = document.createElement('div');
		cityField.className = 'wrc-location-field';

		const cityLabel = document.createElement('label');
		cityLabel.className = 'wrc-location-label';
		cityLabel.setAttribute('for', cityId);
		cityLabel.textContent = config.cityLabel;

		const cityInput = document.createElement('input');
		cityInput.type = 'text';
		cityInput.id = cityId;
		cityInput.className = 'wrc-location-input wrc-location-input--city';
		cityInput.placeholder = config.cityPlaceholder;
		cityInput.value = preset && preset.city ? preset.city : '';


		const feeField = document.createElement('div');
		feeField.className = 'wrc-location-field wrc-location-field--fee';

		const feeLabel = document.createElement('label');
		feeLabel.className = 'wrc-location-label';
		feeLabel.setAttribute('for', 'wrc-location-fee-' + wrcLocationRowCounter);
		feeLabel.textContent = config.feeLabel;

		const feeInput = document.createElement('input');
		feeInput.type = 'number';
		feeInput.id = 'wrc-location-fee-' + wrcLocationRowCounter;
		feeInput.className = 'wrc-location-input wrc-location-input--fee';
		feeInput.placeholder = config.feePlaceholder;
		feeInput.step = '0.01';
		feeInput.min = '0';
		feeInput.value = preset && preset.fee ? preset.fee : '';

		const minimumField = document.createElement('div');
		minimumField.className = 'wrc-location-field wrc-location-field--minimum';

		const minimumLabel = document.createElement('label');
		minimumLabel.className = 'wrc-location-label';
		minimumLabel.setAttribute('for', 'wrc-location-minimum-' + wrcLocationRowCounter);
		minimumLabel.textContent = config.minimumLabel;

		const minimumInput = document.createElement('input');
		minimumInput.type = 'number';
		minimumInput.id = 'wrc-location-minimum-' + wrcLocationRowCounter;
		minimumInput.className = 'wrc-location-input wrc-location-input--minimum';
		minimumInput.placeholder = config.minimumPlaceholder;
		minimumInput.step = '0.01';
		minimumInput.min = '0';
		minimumInput.value = preset && preset.minimum ? preset.minimum : '';

		const actions = document.createElement('div');
		actions.className = 'wrc-location-actions';

		const removeButton = document.createElement('button');
		removeButton.type = 'button';
		removeButton.className = 'wrc-location-remove';
		removeButton.textContent = config.removeText;
		removeButton.setAttribute('aria-label', config.removeLabel);
		removeButton.addEventListener('click', function() {
			wrcRemoveLocationRow(item);
		});

		actions.appendChild(removeButton);

		cityField.appendChild(cityLabel);
		cityField.appendChild(cityInput);
		feeField.appendChild(feeLabel);
		feeField.appendChild(feeInput);
		minimumField.appendChild(minimumLabel);
		minimumField.appendChild(minimumInput);

		row.appendChild(cityField);
		row.appendChild(feeField);
		row.appendChild(minimumField);
		row.appendChild(actions);

		body.appendChild(row);
		item.appendChild(headerBtn);
		item.appendChild(body);
		list.appendChild(item);

		// Set initial header title
		wrcUpdateAccordionTitle(item, cityInput);

		// Toggle handler
		headerBtn.addEventListener('click', function() {
			const isOpen = item.classList.toggle('is-open');
			headerBtn.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
		});

		// Update header title on input changes
		const titleUpdater = function() { wrcUpdateAccordionTitle(item, cityInput); };
		const handleCityInput = function() {
			titleUpdater();
			if (item && item.dataset && item.dataset.postalCode) {
				delete item.dataset.postalCode;
			}
		};
		cityInput.addEventListener('input', handleCityInput);

		if (container && !container.classList.contains('is-active')) {
			cityInput.disabled = true;
			feeInput.disabled = true;
			minimumInput.disabled = true;
		}

		wrcUpdateLocationEmptyState();

		return item;
	}

	function wrcRemoveLocationRow(rowOrItem) {
		// Support removing either the inner row or the accordion item wrapper
		const item = rowOrItem.closest ? rowOrItem.closest('.wrc-accordion-item') : null;
		if (item) {
			item.remove();
		} else if (rowOrItem && rowOrItem.parentNode) {
			rowOrItem.remove();
		}
		wrcUpdateLocationEmptyState();
	}

	function wrcUpdateLocationEmptyState() {
		const list = document.getElementById('wrc-location-list');
		if (!list) {
			return;
		}

		const existingMessage = list.querySelector('.wrc-location-empty');
		if (existingMessage) {
			existingMessage.remove();
		}

		const rows = list.querySelectorAll('.wrc-location-row');
		if (!rows.length) {
			const message = list.getAttribute('data-empty-message');
			if (message) {
				const emptyElement = document.createElement('p');
				emptyElement.className = 'wrc-location-empty';
				emptyElement.textContent = message;
				list.appendChild(emptyElement);
			}
		}
	}

	function wrcLoadDeliveryLocations() {
		const hiddenInput = document.getElementById('wrc_delivery_locations');
		const list = document.getElementById('wrc-location-list');

		if (!hiddenInput || !list) {
			return;
		}

		let storedLocations = [];
		if (hiddenInput.value) {
			try {
				storedLocations = JSON.parse(hiddenInput.value);
			} catch {
				storedLocations = [];
			}
		}

		if (Array.isArray(storedLocations) && storedLocations.length) {
			storedLocations.forEach(function(location) {
				const item = wrcAddLocationRow({
					city: location.city || '',
					postalCode: location.postal_code || location.postalCode || '',
					fee: location.fee || location.delivery_fee || location.deliveryFee || '',
					minimum: location.minimum || location.minimum_order || ''
				});
				// Collapse loaded items by default to keep page compact
				if (item) {
					item.classList.remove('is-open');
					const header = item.querySelector('.wrc-accordion-header');
					if (header) header.setAttribute('aria-expanded', 'false');
				}
			});
		}

		if (!list.querySelector('.wrc-location-row')) {
			wrcAddLocationRow();
		}

		wrcUpdateLocationEmptyState();
	}

	function wrcUpdateDeliveryLocationsInput() {
		const hiddenInput = document.getElementById('wrc_delivery_locations');
		const list = document.getElementById('wrc-location-list');

		if (!hiddenInput || !list) {
			return;
		}

		const rows = list.querySelectorAll('.wrc-location-row');
		const locations = [];

		rows.forEach(function(row) {
			const cityInput = row.querySelector('.wrc-location-input--city');
			const feeInput = row.querySelector('.wrc-location-input--fee');
			const minimumInput = row.querySelector('.wrc-location-input--minimum');

		if (!cityInput) {
				return;
			}

			const city = cityInput.value.trim();
			const fee = feeInput ? feeInput.value.trim() : '';
			const minimum = minimumInput ? minimumInput.value.trim() : '';

		if (!city) {
				return;
			}

		const parentItem = row.closest('.wrc-accordion-item');
		const storedPostal = parentItem && parentItem.dataset ? (parentItem.dataset.postalCode || '') : '';
		const entry = {
			city: city,
			fee: fee,
			minimum: minimum
		};
		if (storedPostal) {
			entry.postalCode = storedPostal;
		}
		locations.push(entry);
		});

		hiddenInput.value = JSON.stringify(locations);
	}

	function wrcCloseCustomHoursModal() {
		$('#wrc-custom-hours-modal').removeClass('is-open');
		$('body').css('overflow', '');
		// Reset form
		document.getElementById('wrc-custom-hours-form').reset();
		// Reset to default state: toggle OFF = Closed = time inputs hidden
		document.getElementById('custom-time-inputs').style.display = 'none';
		document.querySelectorAll('#custom-time-inputs .wrc-time-input').forEach(function(input) {
			input.disabled = true;
			input.value = '';
		});
		// Reset label to Closed
		document.querySelector('.wrc-toggle-label').textContent = 'Closed';
	}

	function wrcToggleCustomTimeInputs(checkbox) {
		const timeInputs = document.getElementById('custom-time-inputs');
		const inputs = timeInputs.querySelectorAll('.wrc-time-input');
		const label = checkbox.closest('.wrc-toggle-switch').querySelector('.wrc-toggle-label');

		if (checkbox.checked) {
			// Toggle ON = Open = Show time inputs
			timeInputs.style.display = 'block';
			inputs.forEach(function(input) { input.disabled = false; });
			label.textContent = 'Open';
		} else {
			// Toggle OFF = Closed = Hide time inputs
			timeInputs.style.display = 'none';
			inputs.forEach(function(input) {
				input.disabled = true;
				input.value = '';
			});
			label.textContent = 'Closed';
		}
	}

	function wrcSaveCustomHours() {
		const form = document.getElementById('wrc-custom-hours-form');
		const formData = new FormData(form);

		const date = formData.get('custom-date');
		const description = formData.get('custom-description');
		const closed = formData.get('custom-closed');

		if (!date) {
			alert('Please select a date.');
			return;
		}

	// Create custom hours entry
	const customHour = {
		date: date,
		description: description || '',
		closed: !closed, // Toggle ON = Open (false), Toggle OFF = Closed (true)
			morningStart: formData.get('custom-morning-start'),
			morningEnd: formData.get('custom-morning-end'),
			eveningStart: formData.get('custom-evening-start'),
			eveningEnd: formData.get('custom-evening-end')
		};

		// Add to list
		wrcAddCustomHourToList(customHour);

		// Close modal
		wrcCloseCustomHoursModal();
	}

	function wrcAddCustomHourToList(customHour) {
		const list = document.getElementById('wrc-custom-hours-list');

		// Remove empty state if present
		if (list.classList.contains('wrc-empty-state')) {
			list.innerHTML = '';
			list.classList.remove('wrc-empty-state');
		}

		// Create entry element
		const entry = document.createElement('div');
		entry.className = 'wrc-custom-hour-entry';
		entry.dataset.date = customHour.date;
		entry.dataset.description = customHour.description;
		entry.dataset.closed = customHour.closed;
		entry.dataset.morningStart = customHour.morningStart || '';
		entry.dataset.morningEnd = customHour.morningEnd || '';
		entry.dataset.eveningStart = customHour.eveningStart || '';
		entry.dataset.eveningEnd = customHour.eveningEnd || '';

		let timeDisplay = '';
		if (customHour.closed) {
			timeDisplay = '<span class="wrc-closed-text">Closed</span>';
		} else {
			timeDisplay = customHour.morningStart + ' - ' + customHour.morningEnd + ' / ' + customHour.eveningStart + ' - ' + customHour.eveningEnd;
		}

		entry.innerHTML = '<div class="wrc-custom-hour-info">' +
			'<strong>' + customHour.description + '</strong>' +
			'<span class="wrc-custom-date">' + customHour.date + '</span>' +
			'<span class="wrc-custom-time">' + timeDisplay + '</span>' +
			'</div>' +
			'<button type="button" class="wrc-remove-custom-hour">' +
			'<span class="dashicons dashicons-trash"></span>' +
			'</button>';

		// Add remove functionality
		entry.querySelector('.wrc-remove-custom-hour').addEventListener('click', function() {
			wrcRemoveCustomHour(this);
		});

		list.appendChild(entry);
	}

	function wrcRemoveCustomHour(button) {
		const entry = button.closest('.wrc-custom-hour-entry');
		entry.remove();

		// Check if list is empty (only actual entries, not placeholder)
		const list = document.getElementById('wrc-custom-hours-list');
		const actualEntries = list.querySelectorAll('.wrc-custom-hour-entry');
		if (actualEntries.length === 0) {
			list.classList.add('wrc-empty-state');
			list.innerHTML = '<p class="wrc-empty-message">No custom delivery hours added yet. Click the button above to add.</p>';
		}
	}

	function wrcLoadCustomHours() {
		const hiddenInput = document.getElementById('wrc_custom_hours');
		const list = document.getElementById('wrc-custom-hours-list');

		if (!hiddenInput || !list) return;

		try {
			const customHours = JSON.parse(hiddenInput.value);
			if (Array.isArray(customHours) && customHours.length > 0) {
				list.innerHTML = '';
				list.classList.remove('wrc-empty-state');

				customHours.forEach(function(customHour) {
					wrcAddCustomHourToList({
						date: customHour.date,
						description: customHour.description,
						closed: customHour.closed,
						morningStart: customHour.morning_start,
						morningEnd: customHour.morning_end,
						eveningStart: customHour.evening_start,
						eveningEnd: customHour.evening_end
					});
				});
			} else {
				list.classList.add('wrc-empty-state');
				list.innerHTML = '<p class="wrc-empty-message">No custom delivery hours added yet. Click the button above to add.</p>';
			}
		} catch {
			list.classList.add('wrc-empty-state');
			list.innerHTML = '<p class="wrc-empty-message">No custom delivery hours added yet. Click the button above to add.</p>';
		}
	}

	function wrcUpdateCustomHoursInput() {
		const list = document.getElementById('wrc-custom-hours-list');
		const hiddenInput = document.getElementById('wrc_custom_hours');
		const customHours = [];

		const entries = list.querySelectorAll('.wrc-custom-hour-entry');
		entries.forEach(function(entry) {
			const date = entry.dataset.date;
			const description = entry.dataset.description;
			const closed = entry.dataset.closed === 'true';
			const morningStart = entry.dataset.morningStart || '';
			const morningEnd = entry.dataset.morningEnd || '';
			const eveningStart = entry.dataset.eveningStart || '';
			const eveningEnd = entry.dataset.eveningEnd || '';

			customHours.push({
				date: date,
				description: description,
				closed: closed,
				morningStart: morningStart,
				morningEnd: morningEnd,
				eveningStart: eveningStart,
				eveningEnd: eveningEnd
			});
		});

		hiddenInput.value = JSON.stringify(customHours);
	}

	function wrcUpdateAccordionTitle(item, cityInput) {
		const title = item.querySelector('.wrc-accordion-title');
		if (!title) return;
		const city = (cityInput && cityInput.value ? cityInput.value.trim() : '');
		if (city) {
			title.textContent = city;
			return;
		}
		// Fallback to placeholder if nothing entered yet
		const container = document.getElementById('wrc-location-based');
		const cityPh = container ? container.getAttribute('data-city-placeholder') : 'City';
		title.textContent = cityPh;
	}

	function wrcInitPreorderToggle() {
		const toggle = document.getElementById('wrc_preorder_enabled_delivery');
		const wrapper = document.getElementById('wrc_preorder_time_wrapper_delivery');

		if (!toggle || !wrapper) {
			return;
		}

		const sync = function() {
			wrapper.style.display = toggle.checked ? '' : 'none';
			if (!toggle.checked) {
				const input = wrapper.querySelector('input[type="time"]');
				if (input) {
					input.value = '';
				}
			}
		};

		toggle.addEventListener('change', sync);
		sync();
	}

	function wrcInitScheduledDateToggle() {
		const toggle = document.getElementById('wrc_scheduled_date_enabled_delivery');
		const wrapper = document.getElementById('wrc_scheduled_date_max_days_wrapper_delivery');

		if (!toggle || !wrapper) {
			return;
		}

		const sync = function() {
			wrapper.classList.toggle('wrc-field--preorder-hidden', !toggle.checked);
		};

		toggle.addEventListener('change', sync);
		sync();
	}

	// Make functions globally available
	window.wrcCloseCustomHoursModal = wrcCloseCustomHoursModal;
	window.wrcToggleCustomTimeInputs = wrcToggleCustomTimeInputs;
	window.wrcSaveCustomHours = wrcSaveCustomHours;
	window.wrcAddCustomHourToList = wrcAddCustomHourToList;
	window.wrcRemoveCustomHour = wrcRemoveCustomHour;
	window.wrcLoadCustomHours = wrcLoadCustomHours;
	window.wrcUpdateCustomHoursInput = wrcUpdateCustomHoursInput;
	window.wrcInitPreorderToggle = wrcInitPreorderToggle;
	window.wrcInitScheduledDateToggle = wrcInitScheduledDateToggle;

})(jQuery);
