/**
 * Northfield Theatre — Single Event Page JavaScript
 *
 * Event page tabs, booking modal with ticket selection,
 * add-to-basket via REST API.
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

(function () {
	'use strict';

	/* ======================================================================
	   1. EVENT TABS
	   ====================================================================== */

	function initEventTabs() {
		var tablist = document.querySelector('.event-tabs__list');
		if (!tablist) return;

		var tabs = Array.from(tablist.querySelectorAll('[role="tab"]'));
		var panels = [];

		tabs.forEach(function (tab) {
			var panel = document.getElementById(tab.getAttribute('aria-controls'));
			if (panel) panels.push(panel);
		});

		function activateTab(newTab) {
			tabs.forEach(function (tab) {
				tab.setAttribute('aria-selected', 'false');
				tab.setAttribute('tabindex', '-1');
				tab.classList.remove('event-tabs__tab--active');
			});

			panels.forEach(function (panel) {
				panel.hidden = true;
			});

			newTab.setAttribute('aria-selected', 'true');
			newTab.setAttribute('tabindex', '0');
			newTab.classList.add('event-tabs__tab--active');

			var panel = document.getElementById(newTab.getAttribute('aria-controls'));
			if (panel) panel.hidden = false;

			newTab.focus();
		}

		tabs.forEach(function (tab) {
			tab.addEventListener('click', function () {
				activateTab(tab);
			});
		});

		tablist.addEventListener('keydown', function (e) {
			var idx = tabs.indexOf(document.activeElement);
			if (idx === -1) return;

			var newIdx;
			switch (e.key) {
				case 'ArrowRight':
				case 'ArrowDown':
					e.preventDefault();
					newIdx = (idx + 1) % tabs.length;
					activateTab(tabs[newIdx]);
					break;
				case 'ArrowLeft':
				case 'ArrowUp':
					e.preventDefault();
					newIdx = (idx - 1 + tabs.length) % tabs.length;
					activateTab(tabs[newIdx]);
					break;
				case 'Home':
					e.preventDefault();
					activateTab(tabs[0]);
					break;
				case 'End':
					e.preventDefault();
					activateTab(tabs[tabs.length - 1]);
					break;
			}
		});
	}

	/* ======================================================================
	   2. BOOKING MODAL
	   ====================================================================== */

	var modalState = {
		eventId: null,
		instanceId: null,
		quantities: {},
		total: 0,
	};

	function initBookingModal() {
		var modal = document.getElementById('booking-modal');
		var backdrop = document.getElementById('booking-modal-backdrop');
		var closeBtn = document.getElementById('booking-modal-close');
		var addBtn = document.getElementById('modal-add-to-basket');

		if (!modal) return;

		// Open modal when Book button clicked.
		document.querySelectorAll('.book-btn').forEach(function (btn) {
			btn.addEventListener('click', function () {
				modalState.eventId = this.getAttribute('data-event-id');
				modalState.instanceId = this.getAttribute('data-instance-id');

				var eventName = this.getAttribute('data-event-name');
				var datetime = this.getAttribute('data-datetime');
				var venue = this.getAttribute('data-venue');

				document.getElementById('modal-event-name').textContent = eventName;

				var dt = new Date(datetime);
				var options = { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: 'numeric', minute: '2-digit' };
				document.getElementById('modal-datetime').textContent = dt.toLocaleDateString('en-GB', options) + ' — ' + venue;

				// Reset quantities.
				modalState.quantities = {};
				document.querySelectorAll('.ticket-row').forEach(function (row) {
					var id = row.getAttribute('data-ticket-id');
					modalState.quantities[id] = 0;
					row.querySelector('.ticket-row__count').textContent = '0';
					row.querySelector('.ticket-row__btn--minus').disabled = true;
				});
				updateModalTotal();

				openModal(modal);
			});
		});

		// Quantity controls.
		document.querySelectorAll('.ticket-row').forEach(function (row) {
			var ticketId = row.getAttribute('data-ticket-id');
			var price = parseFloat(row.getAttribute('data-price'));
			var minusBtn = row.querySelector('.ticket-row__btn--minus');
			var plusBtn = row.querySelector('.ticket-row__btn--plus');
			var countEl = row.querySelector('.ticket-row__count');

			plusBtn.addEventListener('click', function () {
				var current = modalState.quantities[ticketId] || 0;
				if (current < 10) {
					modalState.quantities[ticketId] = current + 1;
					countEl.textContent = modalState.quantities[ticketId];
					minusBtn.disabled = false;
					updateModalTotal();
				}
			});

			minusBtn.addEventListener('click', function () {
				var current = modalState.quantities[ticketId] || 0;
				if (current > 0) {
					modalState.quantities[ticketId] = current - 1;
					countEl.textContent = modalState.quantities[ticketId];
					if (modalState.quantities[ticketId] === 0) {
						minusBtn.disabled = true;
					}
					updateModalTotal();
				}
			});
		});

		// Close handlers.
		if (closeBtn) {
			closeBtn.addEventListener('click', function () { closeModal(modal); });
		}
		if (backdrop) {
			backdrop.addEventListener('click', function () { closeModal(modal); });
		}

		document.addEventListener('keydown', function (e) {
			if (e.key === 'Escape' && !modal.hidden) {
				closeModal(modal);
			}
		});

		// Add to basket.
		if (addBtn) {
			addBtn.addEventListener('click', function () {
				addToBasket(modal);
			});
		}
	}

	function updateModalTotal() {
		var total = 0;
		var hasItems = false;

		document.querySelectorAll('.ticket-row').forEach(function (row) {
			var ticketId = row.getAttribute('data-ticket-id');
			var price = parseFloat(row.getAttribute('data-price'));
			var qty = modalState.quantities[ticketId] || 0;
			total += price * qty;
			if (qty > 0) hasItems = true;
		});

		modalState.total = total;
		var totalEl = document.getElementById('modal-total');
		if (totalEl) {
			totalEl.textContent = '£' + total.toFixed(2);
		}

		var addBtn = document.getElementById('modal-add-to-basket');
		if (addBtn) {
			addBtn.disabled = !hasItems;
		}
	}

	function openModal(modal) {
		modal.hidden = false;
		document.body.classList.add('mobile-nav-open');

		var firstFocusable = modal.querySelector('button, [href], input');
		if (firstFocusable) firstFocusable.focus();
	}

	function closeModal(modal) {
		modal.hidden = true;
		document.body.classList.remove('mobile-nav-open');

		// Return focus to the Book button that opened it.
		var trigger = document.querySelector('.book-btn[data-instance-id="' + modalState.instanceId + '"]');
		if (trigger) trigger.focus();
	}

	function addToBasket(modal) {
		var restUrl = (typeof northfieldData !== 'undefined') ? northfieldData.restUrl : '/wp-json/spektrix-mock/v1/';
		var nonce = (typeof northfieldData !== 'undefined') ? northfieldData.nonce : '';

		var promises = [];

		Object.keys(modalState.quantities).forEach(function (ticketId) {
			var qty = modalState.quantities[ticketId];
			if (qty > 0) {
				promises.push(
					fetch(restUrl + 'basket/items', {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json',
							'X-WP-Nonce': nonce,
						},
						body: JSON.stringify({
							eventId: modalState.eventId,
							instanceId: modalState.instanceId,
							ticketTypeId: ticketId,
							quantity: qty,
						}),
					}).then(function (r) { return r.json(); })
				);
			}
		});

		if (promises.length === 0) return;

		var addBtn = document.getElementById('modal-add-to-basket');
		if (addBtn) {
			addBtn.disabled = true;
			addBtn.textContent = 'Adding...';
		}

		Promise.all(promises).then(function (results) {
			var basket = results[results.length - 1];

			// Update header basket.
			updateHeaderBasket(basket);

			// Pulse the basket icon.
			var basketIcon = document.querySelector('.header-basket__icon');
			if (basketIcon) {
				basketIcon.classList.add('basket-pulse');
				setTimeout(function () {
					basketIcon.classList.remove('basket-pulse');
				}, 500);
			}

			closeModal(modal);

			if (addBtn) {
				addBtn.textContent = 'Add to Basket';
			}
		}).catch(function () {
			if (addBtn) {
				addBtn.disabled = false;
				addBtn.textContent = 'Add to Basket';
			}
		});
	}

	function updateHeaderBasket(basket) {
		var countEl = document.getElementById('header-basket-count');
		var totalEl = document.getElementById('header-basket-total');

		if (!basket || !basket.items) return;

		var itemCount = 0;
		basket.items.forEach(function (item) {
			itemCount += item.quantity;
		});

		if (countEl) {
			countEl.textContent = itemCount;
			countEl.setAttribute('data-count', itemCount);
		}

		if (totalEl) {
			totalEl.textContent = itemCount + ' item' + (itemCount !== 1 ? 's' : '') + ' · £' + basket.total.toFixed(2);
		}
	}

	/* ======================================================================
	   3. INIT
	   ====================================================================== */

	function init() {
		initEventTabs();
		initBookingModal();
	}

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