(function () {
  'use strict';
  if (window.WBStudioBasket) return;
  var items = [];
  var listeners = [];
	var nextId = 1;
	var translatedMessages = window.WB_STUDIO_BASKET_I18N || {};
	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, '%');
	}

  function quantity(item) { return Math.max(1, Number(item && item.quantity) || 1); }
  function count(list) { return list.reduce(function (total, item) { return total + quantity(item); }, 0); }
  function money(item) { return (item.currency || '') + Number(item.total || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
  function notify() { listeners.slice().forEach(function (listener) { listener(items.slice()); }); }
	function basketId() { var id = 'wb-item-' + nextId; nextId += 1; return id; }
	function prepare(item, id) {
		var prepared = item || {};
		prepared.basketId = id || prepared.basketId || basketId();
		return prepared;
	}
	function indexOf(id) { return items.findIndex(function (item) { return item.basketId === id; }); }

  window.WBStudioBasket = {
    add: function (item) { var prepared = prepare(item); items.push(prepared); notify(); return prepared.basketId; },
		replace: function (id, item) {
			var index = indexOf(id);
			if (index < 0) return this.add(item);
			items[index] = prepare(item, id); notify(); return id;
		},
		remove: function (id) {
			var index = indexOf(id);
			if (index < 0) return null;
			var removed = items.splice(index, 1)[0]; notify(); return removed;
		},
		get: function (id) { var index = indexOf(id); return index < 0 ? null : items[index]; },
    all: function () { return items.slice(); },
    clear: function () { items = []; notify(); },
    count: function () { return count(items); },
    subscribe: function (listener) {
      if (typeof listener !== 'function') return function () {};
      listeners.push(listener); listener(items.slice());
      return function () { listeners = listeners.filter(function (item) { return item !== listener; }); };
    },
    render: function (container, current, options) {
      if (!container) return;
      var list = items.slice();
      if (current) list.push(current);
      container.innerHTML = '';
      container.hidden = options && options.force ? false : count(list) <= 1;
      if (container.hidden) return;
      var heading = document.createElement('h3'); heading.textContent = message('orderSoFar', 'Your order so far'); container.appendChild(heading);
      var note = document.createElement('p'); note.textContent = message('reviewItems', 'Review every item before confirming the complete order.'); container.appendChild(note);
			if (!list.length) {
				var empty = document.createElement('p'); empty.className = 'wb-studio-basket__empty'; empty.textContent = message('orderEmpty', 'Your order is empty.'); container.appendChild(empty); return;
			}
      list.forEach(function (item) {
        var row = document.createElement('div'); row.className = 'wb-studio-basket__row';
				var visual = document.createElement('span'); visual.className = 'wb-studio-basket__visual';
				if (item.image) {
					var image = document.createElement('img'); image.src = item.image; image.alt = ''; visual.appendChild(image); row.appendChild(visual);
				}
				if (!visual.parentNode) row.appendChild(visual);
        var copy = document.createElement('div'); var title = document.createElement('strong'); var detail = document.createElement('span');
        title.textContent = item.label; detail.textContent = item.detail || ''; copy.appendChild(title); copy.appendChild(detail);
        var qty = document.createElement('span'); qty.textContent = message('copies', 'Copies: %d', [quantity(item)]);
        var total = document.createElement('strong'); total.textContent = money(item);
				row.appendChild(copy); row.appendChild(qty); row.appendChild(total);
				if (options && options.actions && item.basketId) {
					var actions = document.createElement('span'); actions.className = 'wb-studio-basket__actions';
					if (typeof item.edit === 'function') {
						var edit = document.createElement('button'); edit.type = 'button'; edit.textContent = message('editItem', 'Edit');
						edit.addEventListener('click', function () { item.edit(item.basketId); }); actions.appendChild(edit);
					}
					var remove = document.createElement('button'); remove.type = 'button'; remove.textContent = message('removeItem', 'Remove');
					remove.addEventListener('click', function () { window.WBStudioBasket.remove(item.basketId); }); actions.appendChild(remove); row.appendChild(actions);
				}
				container.appendChild(row);
      });
      if (options && options.force) {
        var orderTotal = list.reduce(function (total, item) { return total + Number(item.total || 0); }, 0);
        var totalRow = document.createElement('div'); totalRow.className = 'wb-studio-basket__total';
        var totalLabel = document.createElement('strong'); totalLabel.textContent = message('orderTotal', 'Order total');
        var totalValue = document.createElement('strong'); totalValue.textContent = (list[0].currency || '') + orderTotal.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        totalRow.appendChild(totalLabel); totalRow.appendChild(totalValue); container.appendChild(totalRow);
      }
    },
    checkout: function (current, details) {
      var order = items.slice(); if (current) order.push(current);
      var references = [];
      return order.reduce(function (chain, item) {
        return chain.then(function () { return item.submit(details); }).then(function (result) { if (result && result.reference) references.push(result.reference); });
      }, Promise.resolve()).then(function () { items = []; notify(); return references; });
    }
  };
}());
