(function () {
	'use strict';

	var STORAGE_KEY = 'wpdude_dc_picking_picked';

	function readPicked() {
		try {
			var raw = window.localStorage.getItem(STORAGE_KEY);
			var list = raw ? JSON.parse(raw) : [];
			return Array.isArray(list) ? list : [];
		} catch (e) {
			return [];
		}
	}

	function writePicked(list) {
		try {
			window.localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
		} catch (e) {
			// Ignore quota / private mode.
		}
	}

	function markPicked(uuid) {
		if (!uuid) {
			return;
		}
		var list = readPicked();
		if (list.indexOf(uuid) === -1) {
			list.push(uuid);
			writePicked(list);
		}
	}

	function clearPicked(uuid) {
		if (!uuid) {
			return;
		}
		writePicked(
			readPicked().filter(function (id) {
				return id !== uuid;
			})
		);
	}

	function applyPicked(card) {
		var uuid = card.getAttribute('data-order-uuid') || '';
		var pick = card.querySelector('[data-wpdude-dc-pick]');
		var ship = card.querySelector('[data-wpdude-dc-ship]');
		card.classList.add('is-picked');
		if (pick) {
			pick.disabled = true;
			pick.setAttribute('aria-pressed', 'true');
		}
		if (ship) {
			ship.disabled = false;
		}
		markPicked(uuid);
	}

	function restorePicked() {
		var picked = readPicked();
		if (!picked.length) {
			return;
		}
		var cards = document.querySelectorAll('.wpdude-dc-picking-card[data-order-uuid]');
		var visible = {};
		for (var i = 0; i < cards.length; i++) {
			var card = cards[i];
			var uuid = card.getAttribute('data-order-uuid') || '';
			visible[uuid] = true;
			if (picked.indexOf(uuid) !== -1) {
				applyPicked(card);
			}
		}
		// Drop UUIDs for orders no longer on the list (already shipped).
		writePicked(
			picked.filter(function (id) {
				return !!visible[id];
			})
		);
	}

	document.addEventListener('click', function (e) {
		var pick = e.target.closest ? e.target.closest('[data-wpdude-dc-pick]') : null;
		if (!pick) {
			return;
		}
		e.preventDefault();
		var card = pick.closest('.wpdude-dc-picking-card');
		if (!card) {
			return;
		}
		applyPicked(card);
		var ship = card.querySelector('[data-wpdude-dc-ship]');
		if (ship) {
			ship.focus();
		}
	});

	document.addEventListener('submit', function (e) {
		var form = e.target;
		if (!form || !form.classList || !form.classList.contains('wpdude-dc-picking-card__actions')) {
			return;
		}
		var card = form.closest('.wpdude-dc-picking-card');
		var uuid = card ? card.getAttribute('data-order-uuid') : '';
		clearPicked(uuid);
	});

	document.addEventListener('DOMContentLoaded', restorePicked);
})();
