/**
 * Northfield Theatre — Basket Summary (Header Icon)
 *
 * Runs on every page. Fetches basket count and total from the REST API
 * and updates the header basket icon. Lightweight — single API call on load.
 *
 * @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 : '';

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

		if (!countEl && !totalEl) return;

		fetch(restUrl + 'basket', {
			headers: { 'X-WP-Nonce': nonce },
			credentials: 'same-origin',
		})
			.then(function (r) { return r.json(); })
			.then(function (basket) {
				if (!basket || !basket.items) return;

				var itemCount = 0;
				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.toFixed(2)
						: '';
				}
			})
			.catch(function () {
				// Silently fail — basket icon stays at 0.
			});
	}

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