// Register eslint ignored glabals - to be revisited.
// https://github.com/woocommerce/automatewoo/issues/1212
/* global AW, localStorage */
/**
 * This module is a reduced clone of @woocommerce/tracks, for jQuery/legacy code-base.
 * It has no side-effect, only exports a suggar function on top of `window.wcTracks.recordEvent`.
 */
( function () {
	/**
	 * Console.log args in a way that mimics debug's behavior.
	 * Log is shown only if localStorage contains the 'debug' item with a pattern that matches 'wc-admin:tracks'.
	 * Paint that namespace in #FF33CC - the hardcoded color that should match the one generated by debug.
	 *
	 * @param {...any} args arguments to be logged.
	 */
	function tracksDebug( ...args ) {
		const debugNamespace = 'wc-admin:tracks';
		// Hard-coded color value of debug.selectColor( 'wc-admin:tracks' )
		// https://github.com/visionmedia/debug/blob/3f56313c1e4a0d59c1054fb9b10026b6903bfba7/src/common.js#L41
		const debugColor = '#FF33CC';

		// Mimic debug's enable/disable behavior.
		let isEnabled = localStorage.getItem( 'debug' );
		isEnabled =
			isEnabled &&
			new RegExp( '^' + isEnabled.replace( /\*/g, '.*?' ) + '$' ).test(
				debugNamespace
			);

		if ( isEnabled ) {
			// We do not provide the diff time as we cannot access the same counter as debug,
			// having a separate one would be even more confusing.
			// eslint-disable-next-line no-console -- Logging in debug mode is the actual feature of this module.
			console.log(
				`%c${ debugNamespace }`,
				`color: ${ debugColor };`,
				...args
			);
		}
	}
	/**
	 * Record an event to Tracks.
	 * This is a clone of @woocommerce/tracks.recordEvent for legacy jQuery files.
	 *
	 * @see @woocommerce/tracks.recordEvent
	 *
	 * @param {string} eventName       The name of the event to record, don't include the wcadmin_ prefix
	 * @param {Object} eventProperties event properties to include in the event
	 */
	function recordEvent( eventName, eventProperties ) {
		// copied from ../src/settings.js
		const TRACKS_PREFIX = 'aw_';
		eventName = TRACKS_PREFIX + eventName;

		tracksDebug( `recordevent wcadmin_${ eventName } `, eventProperties, {
			_tqk: window._tkq,
			shouldRecord:
				!! window._tkq &&
				!! window.wcTracks &&
				!! window.wcTracks.isEnabled,
		} );

		if (
			! window.wcTracks ||
			typeof window.wcTracks.recordEvent !== 'function'
		) {
			return false;
		}

		// 'wcadmin_' prefix is also added in the `recordEvent`.
		window.wcTracks.recordEvent( eventName, eventProperties );
	}

	// Export only recordEvent to the global namespace.
	AW.tracks = { recordEvent };
} )();
