(function () {
  'use strict';

	var translatedMessages = window.MPAB_ADMIN_DATA && window.MPAB_ADMIN_DATA.messages ? window.MPAB_ADMIN_DATA.messages : {};
	function message(key, fallback, values) {
		var output = translatedMessages[key] || fallback;
		(values || []).forEach(function (value, index) {
			output = output.replace(new RegExp('%' + (index + 1) + '\\$[sd]|%[sd]'), String(value));
		});
		return output.replace(/%%/g, '%');
	}

  document.addEventListener('click', function (event) {
	var starterApply = event.target.closest('[data-mpab-starter-apply]');
	if (starterApply) {
		var confirmation = starterApply.getAttribute('data-confirm');
		if (confirmation && !window.confirm(confirmation)) {
			event.preventDefault();
			return;
		}
	}

    var button = event.target.closest('[data-mpab-copy]');
    if (!button) {
      return;
    }

    var input = document.getElementById(button.getAttribute('data-mpab-copy'));
    var status = document.querySelector('[data-mpab-copy-status]');
    if (!input) {
      return;
    }

    var copiedLabel = button.getAttribute('data-copied-label') || message('copied', 'Copied!');
    var copyLabel = button.getAttribute('data-copy-label') || message('copyShortcode', 'Copy shortcode');

    function confirmCopy() {
      button.textContent = copiedLabel;
      if (status) {
        status.textContent = copiedLabel;
      }
      window.setTimeout(function () {
        button.textContent = copyLabel;
      }, 1800);
    }

    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(input.value).then(confirmCopy);
      return;
    }

    input.focus();
    input.select();
    if (document.execCommand('copy')) {
      confirmCopy();
    }
  });


	function updateCurrency(currency) {
		var symbols = { GBP: '£', EUR: '€', USD: '$' };
		var symbol = symbols[currency] || '£';
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-wb-price]'), function (price) {
			var value = Number(price.getAttribute('data-' + currency.toLowerCase()) || 0);
			price.textContent = symbol + value.toFixed(2);
		});
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-currency-symbol]'), function (target) {
			target.textContent = symbol;
		});
	}

	document.addEventListener('change', function (event) {
		if (event.target.matches('[data-mpab-currency]')) {
			updateCurrency(event.target.value);
		}
		if (event.target.matches('input[type="checkbox"]')) {
			syncDashboard();
		}
	});

	function syncSenderPreview() {
		var name = document.querySelector('[data-mpab-sender-name]');
		var email = document.querySelector('[data-mpab-sender-email]');
		var preview = document.querySelector('[data-mpab-sender-preview]');
		if (!name || !email || !preview) {
			return;
		}
		preview.textContent = (name.value.trim() || message('yourStudio', 'Your studio')) + ' <' + (email.value.trim() || message('yourEmail', 'your@email.com')) + '>';
	}

	document.addEventListener('input', function (event) {
		if (event.target.matches('[data-mpab-sender-name], [data-mpab-sender-email]')) {
			syncSenderPreview();
		}
		if (event.target.matches('[data-mpab-accent-colour]')) {
			var value = document.querySelector('[data-mpab-accent-value]');
			if (value) {
				value.textContent = event.target.value.toUpperCase();
			}
		}
		if (event.target.matches('[data-mpab-promotion-percent], [data-mpab-promotion-end-date]')) {
			syncPromotion();
		}
		if (event.target.matches('[data-mpab-promotion-scope]')) {
			syncPromotionScope();
		}
	});

	function friendlyDate(value) {
		if (!value) {
			return '';
		}
		return new Date(value + 'T12:00:00').toLocaleDateString(undefined, {
			day: 'numeric',
			month: 'long',
			year: 'numeric'
		});
	}

	function syncPromotion() {
		document.querySelectorAll('[data-mpab-promotion]').forEach(syncPromotionCard);
	}

	function syncPromotionCard(card) {
		var toggle = card.querySelector('[data-mpab-promotion-toggle]');
		var body = card.querySelector('[data-mpab-promotion-body]');
		var controls = card.querySelector('[data-mpab-promotion-controls]');
		var percentField = card.querySelector('[data-mpab-promotion-percent]');
		var dateField = card.querySelector('[data-mpab-promotion-end-date]');
		var preview = card.querySelector('[data-mpab-promotion-preview]');
		var status = card.querySelector('[data-mpab-promotion-status]');
		var summary = card.querySelector('[data-mpab-promotion-summary]');
		var note = card.querySelector('[data-mpab-promotion-note]');
		var enabled = !!(toggle && toggle.checked);
		var percent = Math.max(1, Math.min(90, Number(percentField ? percentField.value : 20) || 20));
		var endDate = dateField ? dateField.value : '';
		var expired = enabled && endDate && endDate < card.getAttribute('data-mpab-today');
		if (controls) {
			controls.hidden = !enabled;
		}
		if (body) {
			body.hidden = !enabled;
		}
		if (preview) {
			preview.hidden = !enabled;
		}
		if (!preview || !status || !summary || !note) {
			return;
		}
		preview.classList.toggle('is-live', enabled && !expired);
		preview.classList.toggle('is-expired', !!expired);
		if (!enabled) {
			status.textContent = message('promotionOffStatus', 'Not currently showing');
			summary.textContent = message('promotionOffSummary', 'Clients are seeing your usual prices.');
			note.textContent = message('promotionOffNote', 'Switch the promotion on when you’re ready to share a special offer.');
			return;
		}
		if (expired) {
			status.textContent = message('promotionEndedStatus', 'This promotion has ended');
			summary.textContent = message('promotionEndedSummary', 'The %d%% offer is no longer visible to clients.', [percent]);
			note.textContent = message('promotionEndedNote', 'Choose a new end date or remove the deadline to run it again.');
			return;
		}
		status.textContent = message('promotionLiveStatus', 'Live on your client form');
		summary.textContent = endDate ? message('promotionLiveUntil', '%1$d%% off until %2$s', [percent, friendlyDate(endDate)]) : message('promotionLiveOpen', '%d%% off until you switch it off', [percent]);
		note.textContent = message('promotionLiveNote', 'The saving is applied automatically on the final step and recorded with every order.');
	}

	function syncPromotionScope() {
		var selected = document.querySelector('[data-mpab-promotion-scope]:checked');
		var separate = selected && selected.value === 'separate';
		document.querySelectorAll('[data-mpab-promotion]').forEach(function (card) {
			card.hidden = card.getAttribute('data-promotion-category') === 'wall-art' && !separate;
			var title = card.querySelector('.mpab-promotion-card__header h3');
			if (title && card.getAttribute('data-promotion-category') === 'albums') {
				title.textContent = separate ? message('albumPromotion', 'Album promotion') : message('studioPromotion', 'Studio promotion');
			}
		});
		syncPromotion();
	}

	function selectionInputs(group) {
		return Array.prototype.slice.call(group.querySelectorAll('[data-mpab-selection-input]')).filter(function (input) {
			return !input.closest('[hidden]');
		});
	}

	function updateSelectionGroup(group) {
		var inputs = selectionInputs(group);
		var selectedCount = inputs.filter(function (input) { return input.checked; }).length;
		var label = message('selectedCount', '%1$d of %2$d selected', [selectedCount, inputs.length]);
		Array.prototype.forEach.call(group.querySelectorAll('[data-mpab-selection-count]'), function (count) {
			count.textContent = label;
		});
		var details = group.closest('details');
		var summaryCount = details ? details.querySelector(':scope > summary [data-mpab-summary-count], :scope > summary .mpab-selection-count') : null;
		if (summaryCount) {
			summaryCount.textContent = label;
		}
	}

	function syncSelectionCards() {
		Array.prototype.forEach.call(document.querySelectorAll('.mpab-select-card [data-mpab-selection-input]'), function (input) {
			var card = input.closest('.mpab-select-card');
			if (card) {
				card.classList.toggle('is-selected', input.checked);
			}
		});
	}

	function syncPricing() {
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-album-offer]'), function (offer) {
			var toggle = offer.querySelector('[data-mpab-album-toggle]');
			var body = offer.querySelector('[data-mpab-album-body]');
			var active = !toggle || toggle.checked;
			offer.classList.toggle('is-disabled', !active);
			if (body) {
				body.hidden = !active;
			}
		});
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-pricing-row]'), function (row) {
			var toggle = row.querySelector('[data-mpab-size-toggle]');
			row.classList.toggle('is-disabled', toggle && !toggle.checked);
		});
	}

	function syncPresentationBoxes() {
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-box-offer]'), function (offer) {
			var toggle = offer.querySelector('[data-mpab-box-toggle]');
			var body = offer.querySelector('[data-mpab-box-body]');
			var active = !toggle || toggle.checked;
			offer.classList.toggle('is-disabled', !active);
			if (body) {
				body.hidden = !active;
			}
		});
	}

	function syncCoverFamilies() {
		Array.prototype.forEach.call(document.querySelectorAll('.mpab-family'), function (family) {
			var toggle = family.querySelector('.mpab-family-switch input[type="checkbox"]');
			family.classList.toggle('is-disabled', toggle && !toggle.checked);
		});
	}

	function selectedMethods() {
		return Array.prototype.slice.call(document.querySelectorAll('input[name*="[enabled_personalisation_methods]"]:checked')).map(function (input) {
			return input.value;
		}).filter(Boolean);
	}

	function syncPersonalisation() {
		var methods = selectedMethods();
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-requires-method]'), function (section) {
			section.hidden = methods.indexOf(section.getAttribute('data-mpab-requires-method')) === -1;
		});
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-methods]'), function (card) {
			var allowed = (card.getAttribute('data-mpab-methods') || '').split(/\s+/).filter(Boolean);
			card.hidden = !allowed.some(function (method) { return methods.indexOf(method) !== -1; });
		});
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-conditional-library]'), function (library) {
			var cards = Array.prototype.slice.call(library.querySelectorAll('[data-mpab-methods]'));
			library.hidden = cards.length > 0 && cards.every(function (card) { return card.hidden; });
		});
	}

	function syncDashboard() {
		syncSenderPreview();
		syncPromotionScope();
		syncSelectionCards();
		syncPricing();
		syncPresentationBoxes();
		syncCoverFamilies();
		syncPersonalisation();
		Array.prototype.forEach.call(document.querySelectorAll('[data-mpab-selection-group]'), updateSelectionGroup);
	}

	function initGuidedSetup() {
		var guide = document.querySelector('[data-mpab-guided-setup]');
		var form = document.querySelector('[data-mpab-guided-form]');
		var sharedPricing = document.querySelector('[data-mpab-shared-pricing]');
		if (!guide || !form || !sharedPricing) {
			return;
		}

		var panels = Array.prototype.slice.call(document.querySelectorAll('[data-mpab-setup-panel]'));
		var buttons = Array.prototype.slice.call(guide.querySelectorAll('[data-mpab-setup-step]'));
		var offerMount = form.querySelector('[data-mpab-pricing-mount="offer"]');
		var pricingMount = form.querySelector('[data-mpab-pricing-mount="pricing"]');
		var check = form.querySelector('[data-mpab-offer-check]');

		function checkedCount(selector) {
			return document.querySelectorAll(selector + ':checked').length;
		}

		function addCheckCard(title, value, note, step) {
			var card = document.createElement('section');
			var heading = document.createElement('strong');
			var result = document.createElement('span');
			var copy = document.createElement('p');
			var edit = document.createElement('button');
			card.className = 'mpab-offer-check__card';
			heading.textContent = title;
			result.textContent = value;
			copy.textContent = note;
			edit.type = 'button';
			edit.className = 'button-link';
			edit.setAttribute('data-mpab-setup-next', String(step));
			edit.textContent = message('edit', 'Edit');
			card.appendChild(heading);
			card.appendChild(result);
			card.appendChild(copy);
			card.appendChild(edit);
			check.appendChild(card);
		}

		function buildOfferCheck() {
			var selectedSizes = checkedCount('[data-mpab-size-toggle]');
			var selectedAlbums = checkedCount('[data-mpab-album-toggle]');
			var selectedCovers = checkedCount('input[name*="[enabled_cover_colours]"]');
			var selectedMethods = checkedCount('input[name*="[enabled_personalisation_methods]"]');
			var selectedBoxes = checkedCount('[data-mpab-box-toggle]');
			var currency = document.querySelector('[data-mpab-currency]');
			var promotion = document.querySelector('[data-mpab-album-promotion-enabled]');
			var promotionEnabled = promotion && promotion.value === '1';
			check.innerHTML = '';
			addCheckCard(message('albumsAndSizes', 'Albums and sizes'), message('albumSizeCount', '%1$d album %2$s · %3$d sizes', [selectedAlbums, selectedAlbums === 1 ? message('typeSingular', 'type') : message('typePlural', 'types'), selectedSizes]), message('albumCheckNote', 'These are the choices your clients can start with.'), 2);
			addCheckCard(message('coversAndPersonalisation', 'Covers and personalisation'), message('coverMethodCount', '%1$d cover colours · %2$d personalisation options', [selectedCovers, selectedMethods]), message('coverCheckNote', 'Only the relevant choices will appear as the client builds their album.'), 2);
			addCheckCard(message('presentation', 'Presentation'), selectedBoxes ? message('boxCount', '%1$d box %2$s', [selectedBoxes, selectedBoxes === 1 ? message('optionSingular', 'option') : message('optionPlural', 'options')]) : message('noBoxes', 'No presentation boxes'), selectedBoxes ? message('boxesShown', 'Clients can add one of these at the end.') : message('boxesHidden', 'The presentation step will stay hidden.'), 2);
			addCheckCard(message('pricing', 'Pricing'), message('pricingCount', '%1$d selected sizes · %2$s', [selectedSizes, currency ? currency.value : 'GBP']), message('pricingNote', 'Your client will only see the calculated total on the final step.'), 3);
			addCheckCard(message('promotion', 'Promotion'), promotionEnabled ? message('promotionOn', 'Promotion switched on') : message('noPromotion', 'No promotion'), promotionEnabled ? message('promotionCheckOn', 'The saving will appear with the final price.') : message('promotionCheckOff', 'Clients will see your usual prices.'), 3);
		}

		function showStep(step, scroll) {
			if (step === 2 && offerMount) {
				offerMount.appendChild(sharedPricing);
				sharedPricing.classList.add('mpab-pricing-mode--offer');
				sharedPricing.classList.remove('mpab-pricing-mode--pricing');
			}
			if (step === 3 && pricingMount) {
				pricingMount.appendChild(sharedPricing);
				sharedPricing.classList.remove('mpab-pricing-mode--offer');
				sharedPricing.classList.add('mpab-pricing-mode--pricing');
			}
			panels.forEach(function (panel) {
				panel.hidden = panel.getAttribute('data-mpab-setup-panel') !== String(step);
			});
			buttons.forEach(function (button) {
				var active = button.getAttribute('data-mpab-setup-step') === String(step);
				if (active) {
					button.setAttribute('aria-current', 'step');
				} else {
					button.removeAttribute('aria-current');
				}
			});
			if (step === 4) {
				buildOfferCheck();
			}
			syncDashboard();
			if (scroll) {
				guide.scrollIntoView({ behavior: 'smooth', block: 'start' });
			}
		}

		document.addEventListener('click', function (event) {
			var button = event.target.closest('[data-mpab-setup-step], [data-mpab-setup-next]');
			if (!button) {
				return;
			}
			showStep(Number(button.getAttribute('data-mpab-setup-step') || button.getAttribute('data-mpab-setup-next')), true);
		});

		showStep(window.location.hash === '#mpab-promotions' ? 3 : 2, false);
	}

	document.addEventListener('click', function (event) {
		var button = event.target.closest('[data-mpab-select-album-sizes]');
		if (!button) {
			return;
		}
		var album = button.closest('[data-mpab-album-size-group]');
		if (!album) {
			return;
		}
		Array.prototype.forEach.call(album.querySelectorAll('[data-mpab-size-toggle]'), function (input) {
			input.checked = true;
		});
		syncDashboard();
	});

	document.addEventListener('click', function (event) {
		var button = event.target.closest('[data-mpab-select]');
		if (!button) {
			return;
		}
		var group = button.closest('[data-mpab-selection-group]');
		if (!group) {
			return;
		}
		var checked = button.getAttribute('data-mpab-select') === 'all';
		selectionInputs(group).forEach(function (input) {
			input.checked = checked;
		});
		syncDashboard();
	});

	document.addEventListener('mpab:catalogue-ready', syncDashboard);
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', function () {
			syncDashboard();
			initGuidedSetup();
		});
	} else {
		syncDashboard();
		initGuidedSetup();
	}
}());
