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

(function($) {
	'use strict';

	let wrcEditingCustomPickupHourEntry = 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 pickup hours modal functionality
		$('#wrc-add-custom-pickup-hour-btn').on('click', function() {
			wrcOpenCustomPickupHoursModal(null);
		});

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

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

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

		// Load custom pickup hours on page load
		wrcLoadCustomPickupHours();

		// Initialize preorder toggle functionality
		wrcInitPickupPreorderToggle();

		// Initialize scheduled date toggle functionality
		wrcInitPickupScheduledDateToggle();

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

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

	function wrcCloseCustomPickupHoursModal() {
		$('#wrc-pickup-custom-hours-modal').removeClass('is-open');
		$('body').css('overflow', '');
		wrcEditingCustomPickupHourEntry = null;
		wrcResetCustomPickupHoursForm();
		wrcSetCustomPickupHoursModalLabels(false);
	}

	function wrcOpenCustomPickupHoursModal(entry) {
		if (entry) {
			wrcEditingCustomPickupHourEntry = entry;
			wrcPopulateCustomPickupHoursForm(wrcGetCustomPickupHourFromEntry(entry));
			wrcSetCustomPickupHoursModalLabels(true);
		} else {
			wrcEditingCustomPickupHourEntry = null;
			wrcResetCustomPickupHoursForm();
			wrcSetCustomPickupHoursModalLabels(false);
		}

		$('#wrc-pickup-custom-hours-modal').addClass('is-open');
		$('body').css('overflow', 'hidden');
	}

	function wrcSetCustomPickupHoursModalLabels(isEdit) {
		const modal = document.getElementById('wrc-pickup-custom-hours-modal');
		const title = modal ? modal.querySelector('.foodord-modal__title') : null;
		const saveButton = document.getElementById('wrc-pickup-modal-save-btn');

		if (title) {
			title.textContent = isEdit ? (title.dataset.editTitle || 'Edit Custom Pickup Hours') : (title.dataset.addTitle || 'Add Custom Pickup Hours');
		}

		if (saveButton) {
			saveButton.textContent = isEdit ? (saveButton.dataset.updateLabel || 'Save changes') : (saveButton.dataset.addLabel || 'Add Pickup Hours');
		}
	}

	function wrcResetCustomPickupHoursForm() {
		const form = document.getElementById('wrc-pickup-custom-hours-form');
		if (form) {
			form.reset();
		}

		const toggle = document.getElementById('pickup-custom-closed');
		if (toggle) {
			toggle.checked = false;
		}

		document.getElementById('pickup-custom-time-inputs').style.display = 'none';
		document.querySelectorAll('#pickup-custom-time-inputs .wrc-time-input').forEach(function(input) {
			input.disabled = true;
			input.value = '';
		});
		const label = document.querySelector('#wrc-pickup-custom-hours-modal .wrc-toggle-label');
		if (label) {
			label.textContent = 'Closed';
		}
	}

	function wrcPopulateCustomPickupHoursForm(customHour) {
		const dateRange = wrcGetCustomPickupHourDateRange(customHour);
		const closedToggle = document.getElementById('pickup-custom-closed');

		document.getElementById('pickup-custom-start-date').value = dateRange.startDate;
		document.getElementById('pickup-custom-end-date').value = dateRange.endDate;
		document.getElementById('pickup-custom-description').value = customHour.description || '';

		if (closedToggle) {
			closedToggle.checked = !customHour.closed;
			wrcToggleCustomPickupTimeInputs(closedToggle);
		}

		if (!customHour.closed) {
			document.getElementById('pickup-custom-morning-start').value = customHour.morningStart || '';
			document.getElementById('pickup-custom-morning-end').value = customHour.morningEnd || '';
			document.getElementById('pickup-custom-evening-start').value = customHour.eveningStart || '';
			document.getElementById('pickup-custom-evening-end').value = customHour.eveningEnd || '';
		}
	}

	function wrcToggleCustomPickupTimeInputs(checkbox) {
		const timeInputs = document.getElementById('pickup-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 wrcGetCustomPickupHourDateRange(customHour) {
		const startDate = customHour.startDate || customHour.start_date || customHour.date || '';
		const endDate = customHour.endDate || customHour.end_date || customHour.date || startDate;

		return {
			startDate: startDate,
			endDate: endDate || startDate
		};
	}

	function wrcFormatCustomPickupHourDateRange(startDate, endDate) {
		if (!endDate || startDate === endDate) {
			return startDate;
		}

		return startDate + ' - ' + endDate;
	}

	function wrcEscapeCustomPickupHourText(value) {
		return String(value || '').replace(/[&<>"']/g, function(character) {
			return {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				'\'': '&#039;'
			}[character];
		});
	}

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

		const startDate = formData.get('pickup-custom-start-date');
		const endDate = formData.get('pickup-custom-end-date') || startDate;
		const description = formData.get('pickup-custom-description');
		const closed = formData.get('pickup-custom-closed');

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

		if (endDate < startDate) {
			alert('End date cannot be earlier than start date.');
			return;
		}

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

		if (wrcEditingCustomPickupHourEntry) {
			wrcRenderCustomPickupHourEntry(wrcEditingCustomPickupHourEntry, customHour);
		} else {
			wrcAddCustomPickupHourToList(customHour);
		}

		wrcUpdateCustomPickupHoursInput();

		// Close modal
		wrcCloseCustomPickupHoursModal();
	}

	function wrcGetCustomPickupHourFromEntry(entry) {
		const startDate = entry.dataset.startDate || entry.dataset.date || '';
		const endDate = entry.dataset.endDate || startDate;

		return {
			date: startDate,
			startDate: startDate,
			endDate: endDate,
			description: entry.dataset.description || '',
			closed: entry.dataset.closed === 'true',
			morningStart: entry.dataset.morningStart || '',
			morningEnd: entry.dataset.morningEnd || '',
			eveningStart: entry.dataset.eveningStart || '',
			eveningEnd: entry.dataset.eveningEnd || ''
		};
	}

	function wrcAddCustomPickupHourToList(customHour) {
		const list = document.getElementById('wrc-pickup-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';
		wrcRenderCustomPickupHourEntry(entry, customHour);

		list.appendChild(entry);
	}

	function wrcRenderCustomPickupHourEntry(entry, customHour) {
		const dateRange = wrcGetCustomPickupHourDateRange(customHour);
		entry.dataset.date = dateRange.startDate;
		entry.dataset.startDate = dateRange.startDate;
		entry.dataset.endDate = dateRange.endDate;
		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;
		}

		const dateDisplay = wrcFormatCustomPickupHourDateRange(dateRange.startDate, dateRange.endDate);

		entry.innerHTML = '<div class="wrc-custom-hour-info">' +
			'<strong>' + wrcEscapeCustomPickupHourText(customHour.description) + '</strong>' +
			'<span class="wrc-custom-date">' + wrcEscapeCustomPickupHourText(dateDisplay) + '</span>' +
			'<span class="wrc-custom-time">' + timeDisplay + '</span>' +
			'</div>' +
			'<div class="wrc-custom-hour-actions">' +
			'<button type="button" class="wrc-edit-custom-hour" aria-label="Edit" title="Edit">' +
			'Edit' +
			'</button>' +
			'<button type="button" class="wrc-remove-custom-hour" aria-label="Delete" title="Delete">' +
			'Delete' +
			'</button>' +
			'</div>';

		entry.querySelector('.wrc-edit-custom-hour').addEventListener('click', function() {
			wrcEditCustomPickupHour(this);
		});
		entry.querySelector('.wrc-remove-custom-hour').addEventListener('click', function() {
			wrcRemoveCustomPickupHour(this);
		});
	}

	function wrcEditCustomPickupHour(button) {
		const entry = button.closest('.wrc-custom-hour-entry');
		if (!entry) {
			return;
		}

		wrcOpenCustomPickupHoursModal(entry);
	}

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

		// Check if list is empty (only actual entries, not placeholder)
		const list = document.getElementById('wrc-pickup-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 pickup hours added yet. Click the button above to add.</p>';
		}
	}

	function wrcLoadCustomPickupHours() {
		const hiddenInput = document.getElementById('wrc_pickup_custom_hours');
		const list = document.getElementById('wrc-pickup-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) {
					const dateRange = wrcGetCustomPickupHourDateRange(customHour);
					wrcAddCustomPickupHourToList({
						date: dateRange.startDate,
						startDate: dateRange.startDate,
						endDate: dateRange.endDate,
						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 pickup 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 pickup hours added yet. Click the button above to add.</p>';
		}
	}

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

		const entries = list.querySelectorAll('.wrc-custom-hour-entry');
		entries.forEach(function(entry) {
			const startDate = entry.dataset.startDate || entry.dataset.date;
			const endDate = entry.dataset.endDate || startDate;
			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: startDate,
				startDate: startDate,
				endDate: endDate,
				description: description,
				closed: closed,
				morningStart: morningStart,
				morningEnd: morningEnd,
				eveningStart: eveningStart,
				eveningEnd: eveningEnd
			});
		});

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

	function wrcInitPickupPreorderToggle() {
		const toggle = document.getElementById('wrc_preorder_enabled_pickup');
		const wrapper = document.getElementById('wrc_preorder_time_wrapper_pickup');

		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 wrcInitPickupScheduledDateToggle() {
		const toggle = document.getElementById('wrc_scheduled_date_enabled_pickup');
		const wrapper = document.getElementById('wrc_scheduled_date_max_days_wrapper_pickup');

		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.wrcCloseCustomPickupHoursModal = wrcCloseCustomPickupHoursModal;
	window.wrcToggleCustomPickupTimeInputs = wrcToggleCustomPickupTimeInputs;
	window.wrcSaveCustomPickupHours = wrcSaveCustomPickupHours;
	window.wrcAddCustomPickupHourToList = wrcAddCustomPickupHourToList;
	window.wrcRemoveCustomPickupHour = wrcRemoveCustomPickupHour;
	window.wrcLoadCustomPickupHours = wrcLoadCustomPickupHours;
	window.wrcUpdateCustomPickupHoursInput = wrcUpdateCustomPickupHoursInput;
	window.wrcInitPickupPreorderToggle = wrcInitPickupPreorderToggle;
	window.wrcInitPickupScheduledDateToggle = wrcInitPickupScheduledDateToggle;

})(jQuery);
