/* global seovaultseo_cache_notice */
(function () {
	'use strict';

	var cfg = typeof seovaultseo_cache_notice !== 'undefined' ? seovaultseo_cache_notice : {};
	var KEY = cfg.dismissKey || 'seovault_cache_notice_dismissed';

	function readDismissed() {
		try {
			return window.localStorage.getItem(KEY) === '1';
		} catch (e) {
			return false;
		}
	}

	function writeDismissed() {
		try {
			window.localStorage.setItem(KEY, '1');
		} catch (e) {
			// Ignore quota / private mode.
		}
	}

	function getNotices() {
		return document.querySelectorAll('[data-seovault-cache-notice="1"]');
	}

	function hideAll() {
		var nodes = getNotices();
		for (var i = 0; i < nodes.length; i++) {
			nodes[i].style.display = 'none';
			nodes[i].setAttribute('hidden', 'hidden');
		}
	}

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

	onReady(function () {
		if (readDismissed()) {
			hideAll();
			return;
		}

		document.addEventListener('click', function (event) {
			var target = event.target;
			if (!target) {
				return;
			}
			var btn = target.closest ? target.closest('.seovaultseo-cache-notice__dismiss') : null;
			if (!btn) {
				return;
			}
			event.preventDefault();
			writeDismissed();
			hideAll();
		});
	});
})();
