/* =============================================================================
 * Storzen — Sale Notification (frontend)
 * Vanilla JS, no jQuery. Reads JSON payload + config from the container,
 * then rotates notifications at configured intervals.
 * ========================================================================== */
(function () {
	'use strict';

	var SN = {

		container:    null,
		notifications: [],
		index:         0,
		currentEl:     null,
		dismissed:     false,
		shownThisVisit: 0,
		maxCount:      10,

		config: {
			firstDelay: 5000,
			duration:   6000,
			between:    8000,
			message:    '{name} from {city} purchased {product}',
			showAvatar: true,
			showTime:   true,
			showClose:  true
		},

		init: function () {
			this.container = document.querySelector('.sz-sn-container');
			if (!this.container) { return; }

			// Read config from data attributes.
			this.config.firstDelay = (parseInt(this.container.dataset.firstDelay, 10) || 5) * 1000;
			this.config.duration   = (parseInt(this.container.dataset.duration,   10) || 6) * 1000;
			this.config.between    = (parseInt(this.container.dataset.between,    10) || 8) * 1000;
			this.config.message    = this.container.dataset.message    || this.config.message;
			this.config.showAvatar = this.container.dataset.showAvatar === '1';
			this.config.showTime   = this.container.dataset.showTime   === '1';
			this.config.showClose  = this.container.dataset.showClose  === '1';
			this.maxCount          = parseInt(this.container.dataset.maxCount, 10) || 10;

			// Load notification data from the inline <script type="application/json">.
			var dataEl = this.container.querySelector('.sz-sn-data');
			if (!dataEl) { return; }

			try {
				this.notifications = JSON.parse((dataEl.textContent || '').trim());
			} catch (e) {
				return;
			}

			if (!Array.isArray(this.notifications) || !this.notifications.length) { return; }

			// Honor permanent dismissal for the current session.
			try {
				if (sessionStorage.getItem('storzen_sn_dismissed') === '1') {
					this.dismissed = true;
					return;
				}
			} catch (e) { /* sessionStorage may be unavailable in some contexts */ }

			var self = this;
			setTimeout(function () { self.showNext(); }, this.config.firstDelay);
		},

		showNext: function () {
			if (this.dismissed) { return; }
			if (this.shownThisVisit >= this.maxCount) { return; }

			var data = this.notifications[this.index % this.notifications.length];
			this.index++;
			this.shownThisVisit++;

			this.renderNotification(data);
		},

		renderNotification: function (data) {
			var self = this;

			// Build the message with placeholders. Product becomes a link if a URL is present.
			var productHTML = data.url
				? '<a class="sz-sn-item__product-link" href="' + this.escape(data.url) + '" rel="nofollow">' + this.escape(data.product) + '</a>'
				: '<strong>' + this.escape(data.product) + '</strong>';

			var message = this.config.message
				.replace(/{name}/g,    this.escape(data.name    || ''))
				.replace(/{city}/g,    this.escape(data.city    || ''))
				.replace(/{country}/g, this.escape(data.country || ''))
				.replace(/{product}/g, productHTML)
				.replace(/{time}/g,    this.escape(data.time    || ''));

			var item = document.createElement('div');
			item.className = 'sz-sn-item';
			item.setAttribute('role', 'status');

			var html = '';

			if (this.config.showAvatar) {
				if (data.image) {
					html += '<div class="sz-sn-item__avatar">' +
						'<img src="' + this.escape(data.image) + '" alt="" loading="lazy">' +
						'</div>';
				} else {
					var initial = (data.name || '?').substring(0, 1).toUpperCase();
					html += '<div class="sz-sn-item__avatar sz-sn-item__avatar--placeholder">' + this.escape(initial) + '</div>';
				}
			}

			html += '<div class="sz-sn-item__body">';
			html += '<div class="sz-sn-item__message">' + message + '</div>';
			if (this.config.showTime && data.time) {
				html += '<div class="sz-sn-item__time">' + this.escape(data.time) + '</div>';
			}
			html += '</div>';

			if (this.config.showClose) {
				html += '<button type="button" class="sz-sn-item__close" aria-label="Close notification">&times;</button>';
			}

			item.innerHTML = html;

			// Swap out any currently-visible notification.
			if (this.currentEl) {
				this.removeNotification(this.currentEl, true);
			}

			this.container.appendChild(item);
			this.currentEl = item;

			// Close button handler.
			var closeBtn = item.querySelector('.sz-sn-item__close');
			if (closeBtn) {
				closeBtn.addEventListener('click', function () {
					self.dismissed = true;
					try { sessionStorage.setItem('storzen_sn_dismissed', '1'); } catch (e) {}
					self.removeNotification(item);
				});
			}

			// Animate in.
			requestAnimationFrame(function () {
				item.classList.add('is-visible');
			});

			// Schedule hide + queue the next one.
			setTimeout(function () {
				self.removeNotification(item);
				setTimeout(function () { self.showNext(); }, self.config.between);
			}, this.config.duration);
		},

		removeNotification: function (item, immediate) {
			if (!item) { return; }

			if (immediate) {
				if (item.parentNode) { item.parentNode.removeChild(item); }
				if (this.currentEl === item) { this.currentEl = null; }
				return;
			}

			item.classList.remove('is-visible');
			item.classList.add('is-hiding');

			var self = this;
			setTimeout(function () {
				if (item.parentNode) { item.parentNode.removeChild(item); }
				if (self.currentEl === item) { self.currentEl = null; }
			}, 350);
		},

		/* Lightweight HTML escape — uses the browser to do it correctly. */
		escape: function (str) {
			var div = document.createElement('div');
			div.textContent = String(str);
			return div.innerHTML;
		}
	};

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

	// Public namespace (debugging).
	window.StorzenSaleNotification = SN;
})();
