(function () {
	'use strict';

	var EVENT_VIEW = 'view';
	var EVENT_START = 'start';
	var EVENT_INTERACTION = 'interaction';

	function randomId() {
		if (window.crypto && typeof window.crypto.randomUUID === 'function') {
			return window.crypto.randomUUID();
		}

		if (window.crypto && typeof window.crypto.getRandomValues === 'function') {
			var bytes = new Uint8Array(16);
			window.crypto.getRandomValues(bytes);
			return Array.prototype.map.call(bytes, function (byte) {
				return byte.toString(16).padStart(2, '0');
			}).join('');
		}

		return 'page-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 18);
	}

	function sendEvent(form, eventType) {
		var state = form.__subinAnalytics;
		if (!state || state.sent[eventType]) {
			return;
		}

		state.sent[eventType] = true;
		window.fetch(state.url, {
			method: 'POST',
			credentials: 'omit',
			cache: 'no-store',
			referrerPolicy: 'no-referrer',
			keepalive: true,
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				event_type: eventType,
				event_id: state.eventId,
				token: state.token
			})
		}).catch(function () {
			// Analytics is best-effort and must never affect the form experience.
		});
	}

	function observeView(form) {
		if (typeof window.IntersectionObserver !== 'function') {
			sendEvent(form, EVENT_VIEW);
			return;
		}

		var observer = new window.IntersectionObserver(function (entries) {
			entries.forEach(function (entry) {
				if (entry.isIntersecting) {
					sendEvent(form, EVENT_VIEW);
					observer.disconnect();
				}
			});
		}, { threshold: 0.01 });
		observer.observe(form);
	}

	function initForm(form) {
		if (!form || form.__subinAnalytics) {
			return;
		}

		var url = form.getAttribute('data-subin-analytics-url') || '';
		var token = form.getAttribute('data-subin-analytics-token') || '';
		if (!url || !token) {
			return;
		}

		form.__subinAnalytics = {
			url: url,
			token: token,
			eventId: randomId(),
			sent: {}
		};

		observeView(form);
		['focusin', 'pointerdown', 'keydown'].forEach(function (eventName) {
			form.addEventListener(eventName, function () {
				sendEvent(form, EVENT_START);
			}, { passive: true });
		});
		['input', 'change'].forEach(function (eventName) {
			form.addEventListener(eventName, function () {
				sendEvent(form, EVENT_START);
				sendEvent(form, EVENT_INTERACTION);
			}, { passive: true });
		});
		form.addEventListener('submit', function () {
			sendEvent(form, EVENT_START);
		});
	}

	function init() {
		document.querySelectorAll('form[data-subin-analytics-url][data-subin-analytics-token]').forEach(initForm);
	}

	window.SubinFrontendAnalytics = {
		initForm: initForm,
		sendEvent: sendEvent
	};

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