/* global customer_journey */

'use strict';

/**
 * Customer Journey function.
 *
 * @since 1.0.0
 */
var CustomerJourney = window.CustomerJourney || ( function( document, window ) {

	/**
	 * Public functions and properties.
	 *
	 * @since 1.0.0
	 *
	 * @type {object}
	 */
	var app = {

		/**
		 * Start the engine.
		 *
		 * @since 1.0.0
		 */
		init: function() {

			var timeStamp = Math.round( Date.now() / 1000 ),
				cookie    = app.getCookie( '_cjforwoo' ),
				data      = {},
				url       = window.location.href;

			if ( ! cookie && document.referrer !== '' && ! document.referrer.startsWith( window.location.origin ) ) {
				data[ timeStamp - 2 ] = document.referrer + '|#|{ReferrerPageTitle}';
			}

			url += '|#|' + document.title;

			if ( typeof customer_journey !== 'undefined' && customer_journey.page_id ) {
				url += '|#|' + Number( customer_journey.page_id );
			}

			if ( cookie ) {
				data = JSON.parse( cookie );
			}

			data[timeStamp] = encodeURIComponent( url );

			app.createCookie( '_cjforwoo', JSON.stringify( data ), 7 );
		},

		/**
		 * Create cookie.
		 *
		 * @since 1.0.0
		 *
		 * @param {string} name  Cookie name.
		 * @param {string} value Cookie value.
		 * @param {string} days  Whether it should expire and when.
		 */
		createCookie: function( name, value, days ) {

			var expires = '';
			var secure = '';

			if ( customer_journey.is_ssl ) {
				secure = ';secure';
			}

			var date = new Date();
			date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
			expires = ';expires=' + date.toGMTString();

			// Write the cookie.
			document.cookie = name + '=' + value + expires + ';path=/;samesite=strict' + secure;
		},

		/**
		 * Retrieve cookie.
		 *
		 * @since 1.0.0
		 *
		 * @param {string} name Cookie name.
		 *
		 * @returns {string|null} Cookie value or null when it doesn't exist.
		 */
		getCookie: function( name ) {

			var nameEQ = name + '=',
				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 ( 0 === c.indexOf( nameEQ ) ) {
					return c.substring( nameEQ.length, c.length );
				}
			}

			return null;
		},
	};

	// Provide access to public functions/properties.
	return app;

}( document, window ) );

// Initialize.
CustomerJourney.init();
