(function ($) {
	"use strict";

	let fired = new WeakSet();

	function canFire(el) {
		if (fired.has(el)) return false;
		fired.add(el);
		return true;
	}

	function getParams(data) {
		let obj = {};
		if (data.params) {
			data.params.forEach(p => {
				if (p.key) obj[p.key] = p.value;
			});
		}
		return obj;
	}

	function send(data, el) {

		if (!canFire(el)) return;

		let params = getParams(data);
		let name = data.name || 'click';

		// GA4 / Ads
		if (data.platforms.includes('ga4') || data.platforms.includes('ads')) {
			if (typeof gtag === 'function') {
				gtag('event', name, params);
			}
		}

		// FB
		if (data.platforms.includes('fb')) {
			if (typeof fbq === 'function') {
				fbq('track', name, params);
			}
		}

		if (data.debug) {
			console.log('[EC EVENT TRACK]', name, params, data);
		}
	}

	/* CLICK */
	$(document).on('click', '.ecafe-event-track', function () {
		let data = $(this).data('ec');
		if (data.trigger === 'click') send(data, this);
	});

    /* FORM SUBMIT */
	$(document).on('submit_success', function (event, response) {

		let $form = $(event.target);

		$('.ecafe-event-track').each(function () {

			let el = this;
			let data = $(this).data('ec');

			if (!data || data.trigger !== 'form') return;

			let $tracker = $(this);

			// inside form
			if ($form.find($tracker).length) {
				send(data, el);
			}
			// parent wrapper
			else if ($tracker.find($form).length) {
				send(data, el);
			}
		});
	});

	/* DELAY */
	function delay(el, data) {
		setTimeout(() => send(data, el), data.delay || 3000);
	}

	/* SCROLL */
	function scrollTrigger(el, data) {

        let threshold = data.scroll || 50;
        let triggered = false;
    
        function onScroll() {
            if (triggered) return;
    
            let scrollTop = window.scrollY;
            let docHeight = document.documentElement.scrollHeight - window.innerHeight;
            let percent = (scrollTop / docHeight) * 100;
    
            if (percent >= threshold) {
                send(data, el);
                triggered = true;
                window.removeEventListener('scroll', onScroll);
            }
        }
    
        window.addEventListener('scroll', onScroll);
    }

	/* EXIT */
	function exitIntent(el, data) {

		let triggered = false;

		$(document).on('mouseleave', function (e) {
			if (triggered) return;

			if (e.clientY < 10) {
				send(data, el);
				triggered = true;
			}
		});
	}

	function init() {

		$('.ecafe-event-track').each(function () {

			let el = this;
			let data = $(this).data('ec');

			if (!data) return;

			switch (data.trigger) {
				case 'delay':
					delay(el, data);
					break;
				case 'scroll':
					scrollTrigger(el, data);
					break;
				case 'exit':
					exitIntent(el, data);
					break;
			}
		});
	}

	$(document).ready(init);

})(jQuery);