/* eslint-disable no-undef */
/* global rewardswpTrackingVars */
import Cookies from 'js-cookie';

document.addEventListener( 'DOMContentLoaded', () => {
	if (
		Cookies.get( rewardswpTrackingVars.visitIdCookieName ) &&
		Cookies.get( rewardswpTrackingVars.advocateIdCookieName )
	) {
		return; // Bail since cookies were already created.
	}

	const urlParams = new URLSearchParams( window.location.search );
	const referralCode = urlParams.get( rewardswpTrackingVars.referralSlug );

	if ( ! referralCode ) {
		return; // No referral code provided.
	}

	trackVisit( referralCode );
} );

const createCookie = ( name, value ) => {
	Cookies.set(
		name,
		value,
		{
			expires: rewardswpTrackingVars.cookieExpiration,
			path: rewardswpTrackingVars.cookiePath,
			domain: rewardswpTrackingVars.cookieDomain,
		}
	);
};

const trackVisit = async ( referralCode ) => {
	try {

		const body = new FormData();

		body.append( 'action', 'rewardswp_track_visit' );
		body.append( 'referral_code', referralCode );
		body.append( 'referrer_url', document.referrer ?? '' );
		body.append( 'landing_url', document.URL ?? '' );
		body.append( '_ajax_nonce', rewardswpTrackingVars.nonce );

		const response = await fetch( rewardswpTrackingVars.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			body,
		} );

		if ( ! response.ok ) {
			throw new Error( `Failed to create visit. HTTP error! Status: ${ response.status }` );
		}

		const data = await response.json();

		if ( data.event_id ) {
			createCookie( rewardswpTrackingVars.visitIdCookieName, data.event_id );
		}

		if ( data.advocate_id ) {
			createCookie( rewardswpTrackingVars.advocateIdCookieName, data.advocate_id );
		}
	} catch ( error ) {
		console.log( 'Request failed', error );
	}
};
