/**
 * Form Connector UTM Tracker
 *
 * Captures UTM parameters from the URL and stores them in cookies.
 * These cookies are then read during form submission to attach
 * marketing attribution data to CareHQ enquiries.
 *
 * Attribution modes:
 *   - last_click:       Keep existing cookies when no UTM in URL (default — stickiest)
 *   - last_click_clear: Clear UTM cookies when no UTM in URL (most accurate per-visit)
 *   - session:          Store UTM as session cookies that expire when the browser closes
 */
(function () {
	"use strict";

	// UTM parameters to capture
	var utmParams = [
		"utm_source",
		"utm_medium",
		"utm_campaign",
		"utm_term",
		"utm_content",
		"utm_id",
	];

	// Extra cookies we manage alongside UTM params
	var extraCookies = ["fc_landing_page", "fc_referrer_other"];

	// Get config from WordPress (fallback defaults)
	var config = window.fcUtmConfig || {
		cookieDuration: 30,
		attributionMode: "last_click_clear",
		debug: false,
	};

	// Debug logger (only when WP_DEBUG is on or ?fc_utm_debug=1 in URL)
	var debugMode =
		config.debug ||
		new URLSearchParams(window.location.search).has("fc_utm_debug");
	function log() {
		if (debugMode) {
			console.log.apply(
				console,
				["[FC UTM]"].concat(Array.prototype.slice.call(arguments)),
			);
		}
	}

	/**
	 * Get a URL parameter value
	 */
	function getUrlParam(name) {
		var urlParams = new URLSearchParams(window.location.search);
		return urlParams.get(name);
	}

	/**
	 * Set a cookie with an explicit expiry in days.
	 * Pass 0 for a session cookie (expires when browser closes).
	 */
	function setCookie(name, value, days) {
		var expires = "";
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
			expires = "; expires=" + date.toUTCString();
		}
		// SameSite=Lax for security, path=/ for site-wide access
		document.cookie =
			name +
			"=" +
			encodeURIComponent(value) +
			expires +
			"; path=/; SameSite=Lax";
	}

	/**
	 * Delete a cookie by setting it in the past
	 */
	function deleteCookie(name) {
		document.cookie =
			name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax";
	}

	/**
	 * Get a cookie value
	 */
	function getCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(";");
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) === " ") {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) === 0) {
				return decodeURIComponent(c.substring(nameEQ.length, c.length));
			}
		}
		return null;
	}

	/**
	 * Check if any UTM parameters are in the URL
	 */
	function hasUtmParams() {
		for (var i = 0; i < utmParams.length; i++) {
			if (getUrlParam(utmParams[i])) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Clear all UTM-related cookies
	 */
	function clearUtmCookies() {
		var i;
		for (i = 0; i < utmParams.length; i++) {
			deleteCookie(utmParams[i]);
		}
		for (i = 0; i < extraCookies.length; i++) {
			deleteCookie(extraCookies[i]);
		}
	}

	/**
	 * Get the cookie lifetime in days based on the current attribution mode.
	 *   - session mode → 0 (session cookie, no explicit expiry)
	 *   - all others   → configured cookieDuration
	 */
	function getCookieDays() {
		return config.attributionMode === "session" ? 0 : config.cookieDuration;
	}

	/**
	 * Store each UTM parameter found in the URL as a cookie.
	 */
	function storeUtmCookies() {
		var days = getCookieDays();

		for (var i = 0; i < utmParams.length; i++) {
			var param = utmParams[i];
			var value = getUrlParam(param);

			if (value) {
				setCookie(param, value, days);
				log(
					"Set cookie:",
					param,
					"=",
					value,
					days ? "(expires in " + days + "d)" : "(session)",
				);
			}
		}

		// Landing page
		setCookie("fc_landing_page", window.location.pathname, days);
		log("Set landing page cookie:", window.location.pathname);

		// HTTP referrer — first-touch only
		if (document.referrer && !getCookie("fc_referrer_other")) {
			setCookie("fc_referrer_other", document.referrer, days);
			log("Set referrer_other cookie:", document.referrer);
		}
	}

	/**
	 * Handle the case where no UTM params are in the URL.
	 * Behaviour depends on the configured attribution mode.
	 */
	function handleNoUtmParams() {
		var mode = config.attributionMode;

		if (mode === "last_click_clear") {
			// Clear stale cookies so organic visits are not mis-attributed
			log("Mode last_click_clear — clearing stale UTM cookies");
			clearUtmCookies();
			return;
		}

		// "last_click" and "session" both preserve existing cookies
		// (session cookies will self-expire when the browser closes)
		log("Mode", mode, "— preserving existing cookies");
		var existing = {};
		for (var i = 0; i < utmParams.length; i++) {
			var val = getCookie(utmParams[i]);
			if (val) existing[utmParams[i]] = val;
		}
		log(
			"Existing UTM cookies:",
			Object.keys(existing).length > 0 ? JSON.stringify(existing) : "none",
		);
	}

	/**
	 * Main entry point — capture UTM parameters and store in cookies.
	 */
	function captureUtmParams() {
		log("Tracker loaded. Mode:", config.attributionMode);
		log("URL:", window.location.href);
		log("Config:", JSON.stringify(config));

		if (!hasUtmParams()) {
			handleNoUtmParams();
			return;
		}

		log("UTM params detected in URL — storing cookies...");
		storeUtmCookies();
		log("UTM capture complete.");
	}

	// Run on page load
	captureUtmParams();
})();
