/**
 * Northfield Theatre — Basket Page JavaScript
 *
 * Renders basket items, handles quantity changes, donation selection,
 * live total updates. Reads basket from REST API, updates via API calls.
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

(function () {
	'use strict';

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

	var donation = 0;

	/* ======================================================================
	   1. LOAD BASKET
	   ====================================================================== */

	function loadBasket() {
		fetch(restUrl + 'basket', {
			headers: { 'X-WP-Nonce': nonce },
		})
			.then(function (r) { return r.json(); })
			.then(function (basket) {
				renderBasket(basket);
			})
			.catch(function () {
				showEmpty();
			});
	}

	/* ======================================================================
	   2. RENDER BASKET
	   ====================================================================== */

	function renderBasket(basket) {
		var loading = document.getElementById('basket-loading');
		var empty = document.getElementById('basket-empty');
		var content = document.getElementById('basket-content');

		if (loading) loading.hidden = true;

		if (!basket || !basket.items || basket.items.length === 0) {
			showEmpty();
			return;
		}

		if (empty) empty.hidden = true;
		if (content) content.hidden = false;

		renderItems(basket.items);
		donation = basket.donation || 0;
		updateTotals(basket);
		updateHeaderBasket(basket);
	}

	function showEmpty() {
		var loading = document.getElementById('basket-loading');
		var empty = document.getElementById('basket-empty');
		var content = document.getElementById('basket-content');

		if (loading) loading.hidden = true;
		if (empty) empty.hidden = false;
		if (content) content.hidden = true;

		updateHeaderBasket({ items: [], total: 0 });
	}

	function renderItems(items) {
		var container = document.getElementById('basket-items');
		if (!container) return;

		container.innerHTML = '';

		items.forEach(function (item) {
			var dt = new Date(item.datetime);
			var dateStr = dt.toLocaleDateString('en-GB', {
				weekday: 'short', day: 'numeric', month: 'short', year: 'numeric',
				hour: 'numeric', minute: '2-digit',
			});

			var category_gradients = {
				'Drama': 'linear-gradient(135deg, #4A1942, #1B4D3E)',
				'Comedy': 'linear-gradient(135deg, #92400E, #E8A33D)',
				'Music': 'linear-gradient(135deg, #312E81, #6D28D9)',
				'Dance': 'linear-gradient(135deg, #164E63, #0891B2)',
				'Family': 'linear-gradient(135deg, #14532D, #22C55E)',
			};
			var imgStyle = 'background: ' + (category_gradients['Drama'] || 'var(--color-primary)');

			var html = '<div class="basket-item" data-item-id="' + item.id + '">'
				+ '<div class="basket-item__image" style="' + imgStyle + '"></div>'
				+ '<div class="basket-item__info">'
				+ '<h3 class="basket-item__name"><a href="' + siteUrl + 'events/' + (item.eventSlug || '') + '/">' + escapeHtml(item.eventName) + '</a></h3>'
				+ '<p class="basket-item__details">' + dateStr + '<br>' + escapeHtml(item.venue) + '</p>'
				+ '<span class="basket-item__ticket-type">' + escapeHtml(item.ticketTypeName) + '</span>'
				+ '<span class="basket-item__price">£' + item.price.toFixed(2) + ' each</span>'
				+ '</div>'
				+ '<div class="basket-item__qty">'
				+ '<button class="basket-item__qty-btn" data-action="decrease" data-item-id="' + item.id + '" aria-label="Decrease quantity"' + (item.quantity <= 1 ? ' disabled' : '') + '>−</button>'
				+ '<span class="basket-item__qty-count" aria-live="polite">' + item.quantity + '</span>'
				+ '<button class="basket-item__qty-btn" data-action="increase" data-item-id="' + item.id + '" aria-label="Increase quantity"' + (item.quantity >= 10 ? ' disabled' : '') + '>+</button>'
				+ '</div>'
				+ '<div class="basket-item__total">'
				+ '<span class="basket-item__line-total">£' + item.lineTotal.toFixed(2) + '</span>'
				+ '<button class="basket-item__remove" data-item-id="' + item.id + '">Remove</button>'
				+ '</div>'
				+ '</div>';

			container.insertAdjacentHTML('beforeend', html);
		});

		// Bind events.
		container.querySelectorAll('.basket-item__qty-btn').forEach(function (btn) {
			btn.addEventListener('click', function () {
				var itemId = this.getAttribute('data-item-id');
				var action = this.getAttribute('data-action');
				var countEl = this.parentNode.querySelector('.basket-item__qty-count');
				var current = parseInt(countEl.textContent, 10);
				var newQty = action === 'increase' ? current + 1 : current - 1;

				if (newQty < 1) newQty = 0; // Will remove the item.

				updateItemQuantity(itemId, newQty);
			});
		});

		container.querySelectorAll('.basket-item__remove').forEach(function (btn) {
			btn.addEventListener('click', function () {
				var itemId = this.getAttribute('data-item-id');
				removeItem(itemId);
			});
		});
	}

	/* ======================================================================
	   3. BASKET OPERATIONS
	   ====================================================================== */

	function updateItemQuantity(itemId, quantity) {
		fetch(restUrl + 'basket/items/' + itemId, {
			method: 'PATCH',
			headers: {
				'Content-Type': 'application/json',
				'X-WP-Nonce': nonce,
			},
			body: JSON.stringify({ quantity: quantity }),
		})
			.then(function (r) { return r.json(); })
			.then(function (basket) {
				renderBasket(basket);
			});
	}

	function removeItem(itemId) {
		fetch(restUrl + 'basket/items/' + itemId, {
			method: 'DELETE',
			headers: { 'X-WP-Nonce': nonce },
		})
			.then(function (r) { return r.json(); })
			.then(function (basket) {
				renderBasket(basket);
			});
	}

	/* ======================================================================
	   4. DONATION
	   ====================================================================== */

	function initDonation() {
		var buttons = document.querySelectorAll('.basket-donation__btn');
		buttons.forEach(function (btn) {
			btn.addEventListener('click', function () {
				buttons.forEach(function (b) { b.classList.remove('basket-donation__btn--active'); });
				this.classList.add('basket-donation__btn--active');
				donation = parseFloat(this.getAttribute('data-amount')) || 0;

				// Update displayed total.
				var subtotalEl = document.getElementById('basket-subtotal');
				if (subtotalEl) {
					var subtotal = parseFloat(subtotalEl.textContent.replace('£', '')) || 0;
					var totalEl = document.getElementById('basket-total');
					if (totalEl) {
						totalEl.textContent = '£' + (subtotal + donation).toFixed(2);
					}
				}
			});
		});
	}

	/* ======================================================================
	   5. UPDATE TOTALS
	   ====================================================================== */

	function updateTotals(basket) {
		var subtotalEl = document.getElementById('basket-subtotal');
		var totalEl = document.getElementById('basket-total');

		if (subtotalEl) subtotalEl.textContent = '£' + basket.subtotal.toFixed(2);
		if (totalEl) totalEl.textContent = '£' + (basket.subtotal + donation).toFixed(2);
	}

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

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

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

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

	/* ======================================================================
	   6. HELPERS
	   ====================================================================== */

	function escapeHtml(str) {
		var div = document.createElement('div');
		div.textContent = str;
		return div.innerHTML;
	}

	/* ======================================================================
	   7. INIT
	   ====================================================================== */

	function init() {
		loadBasket();
		initDonation();
	}

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