class Tracker {
	constructor() {}

	async trackEvent(eventName) {
		const scriptEl = document.querySelector(
			'[data-script="analyticexpert"]'
		);
		let siteName = '';
		if (scriptEl) {
			siteName = scriptEl.dataset.siteName;
		}

		const queryParamsStorage = window.localStorage.getItem('queryParams');
		const uniqueToken = await this.getTrackerToken('aeToken');
		if (!uniqueToken) {
			return;
		}
		const documentReferrer =
			window.localStorage.getItem('documentReferrer');

		let username = window.localStorage.getItem('usernamePixel');
		const usernameLoggedIn =
			document.querySelector('.username-container > span')?.textContent ||
			document.querySelector('.username')?.textContent;

		if (
			(!username && usernameLoggedIn) ||
			(username && usernameLoggedIn && username != usernameLoggedIn)
		) {
			window.localStorage.setItem('usernamePixel', usernameLoggedIn);
			username = usernameLoggedIn;
		}

		await fetch('https://api.analyticexpert.org/analytic-event/track', {
			method: 'POST',
			headers: {
				accept: 'application/json',
				'content-type': 'application/json'
			},
			body: JSON.stringify({
				url: window.location.href,
				eventName,
				uniqueToken,
				username,
				referrer: documentReferrer,
				date: new Date(),
				queryParams: queryParamsStorage,
				siteName
			})
		});
	}

	async getTrackerToken(name) {
		const analyticExpertToken = localStorage.getItem(name);
		if (analyticExpertToken) {
			return analyticExpertToken;
		}
		const iframe = document.createElement('iframe');
		iframe.style.display = 'none';
		iframe.src = 'https://frame.analyticexpert.org';
		iframe.sandbox = 'allow-scripts allow-same-origin';
		document.body.appendChild(iframe);

		return new Promise((resolve) => {
			window.addEventListener('message', (event) => {
				const eventData = event.data;

				switch (eventData?.type) {
					case 'analyticExpertToken':
						localStorage.setItem(name, eventData?.uniqueToken);

						resolve(eventData?.uniqueToken);
						break;

					default:
						resolve(null);
						break;
				}
			});
		});
	}

	setCookie(name, value, domain, days) {
		let expires = '';
		if (days) {
			const date = new Date();
			date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
			expires = '; expires=' + date.toUTCString();
		}
		const cookieString =
			name +
			'=' +
			(value || '') +
			expires +
			'; path=/ ;domain=.' +
			domain;
		document.cookie = cookieString;
	}

	getCookie(name) {
		let nameEQ = name + '=';
		let ca = document.cookie.split(';');
		for (let i = 0; i < ca.length; i++) {
			let c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length, c.length);
		}
		return null;
	}
}

document.addEventListener('DOMContentLoaded', async function (event) {
	const tracker = new Tracker();
	tracker.trackEvent('pageview');
	const isDepositPage = window.location.href.indexOf('deposit') != -1;

	if (isDepositPage) {
		depositForm.addEventListener('submit', submitEvent);
		let hasBeenClicked = false;
		function submitEvent() {
			if (hasBeenClicked) {
				return;
			}
			hasBeenClicked = true;
			tracker.trackEvent('deposit');
		}
	}

	if (window.location.href.indexOf('register-done') != -1) {
		tracker.trackEvent('registration');
	}

	if (waitForElementRetry) {
		waitForElementRetry('#form-state', {
			timeout: 99999,
			maxRetries: 3,
			root: document.getElementById('_rht_toaster')
		})
			.then((el) => {
				if (el.dataset.value === 'register-done') {
					tracker.trackEvent('registration');
				}
			})
			.catch((err) => {
				console.log(err);
			});
	}
});
