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

(function($) {
	'use strict';

	$(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() {
			$('#wrc-pickup-custom-hours-modal').addClass('is-open');
			$('body').css('overflow', 'hidden');
		});

		$('#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', '');
		// Reset form
		document.getElementById('wrc-pickup-custom-hours-form').reset();
		// Reset to default state: toggle OFF = Closed = time inputs hidden
		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 = '';
		});
		// Reset label to Closed
		document.querySelector('#wrc-pickup-custom-hours-modal .wrc-toggle-label').textContent = 'Closed';
	}

	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 wrcSaveCustomPickupHours() {
		const form = document.getElementById('wrc-pickup-custom-hours-form');
		const formData = new FormData(form);

		const date = formData.get('pickup-custom-date');
		const description = formData.get('pickup-custom-description');
		const closed = formData.get('pickup-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('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')
		};

		// Add to list
		wrcAddCustomPickupHourToList(customHour);

		// Close modal
		wrcCloseCustomPickupHoursModal();
	}

	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';
		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() {
			wrcRemoveCustomPickupHour(this);
		});

		list.appendChild(entry);
	}

	function wrcRemoveCustomPickupHour(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-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) {
					wrcAddCustomPickupHourToList({
						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 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 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 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);
