/**
 * Initialize Image Compare Viewer on supreme before/after modules (frontend).
 *
 * @package DiviSupreme
 */

/* global ImageCompare */
( function () {
	'use strict';

	/**
	 * Whether JSON `data-params` represents an “on” toggle value.
	 *
	 * @param {*} raw Raw value.
	 * @return {boolean}
	 */
	function dsmBaIsToggleOn( raw ) {
		return true === raw || 1 === raw || '1' === raw || 'on' === raw || 'true' === raw;
	}

	/**
	 * Mount ImageCompare on each uninitialized wrapper.
	 *
	 * @return {void}
	 */
	function dsmInitBeforeAfterImageCompare() {
		if ( 'undefined' === typeof ImageCompare ) {
			return;
		}

		var nodes = document.querySelectorAll(
			'.dsm_before_after_image_wrapper:not([data-dsm-icv-mounted])'
		);

		nodes.forEach( function ( el ) {
			var raw = el.getAttribute( 'data-params' );
			var data = {};

			try {
				data = raw ? JSON.parse( raw ) : {};
			} catch ( e ) {
				return;
			}

			el.setAttribute( 'data-dsm-icv-mounted', '1' );

			var start = parseFloat( data.startingPoint );
			if ( isNaN( start ) ) {
				start = 50;
			}
			start = Math.max( 0, Math.min( 100, start ) );

			var smoothAmt = parseInt( data.smoothingAmount, 10 );
			if ( isNaN( smoothAmt ) ) {
				smoothAmt = 100;
			}
			smoothAmt = Math.max( 0, Math.min( 2000, smoothAmt ) );

			var opts = {
				controlColor:
					'string' === typeof data.controlColor && data.controlColor
						? data.controlColor
						: '#FFFFFF',
				controlShadow: dsmBaIsToggleOn( data.controlShadow ),
				addCircle: dsmBaIsToggleOn( data.addCircle ),
				addCircleBlur: dsmBaIsToggleOn( data.addCircleBlur ),
				showLabels: dsmBaIsToggleOn( data.showLabels ),
				labelOptions: {
					before:
						'string' === typeof data.beforeLabel && data.beforeLabel
							? data.beforeLabel
							: 'Before',
					after:
						'string' === typeof data.afterLabel && data.afterLabel
							? data.afterLabel
							: 'After',
					onHover: dsmBaIsToggleOn( data.labelOnHover ),
				},
				smoothing: dsmBaIsToggleOn( data.smoothing ),
				smoothingAmount: smoothAmt,
				hoverStart: dsmBaIsToggleOn( data.hoverStart ),
				verticalMode: true === data.verticalMode,
				startingPoint: start,
				fluidMode: dsmBaIsToggleOn( data.fluidMode ),
			};

			try {
				new ImageCompare( el, opts ).mount();
			} catch ( err ) {
				el.removeAttribute( 'data-dsm-icv-mounted' );
			}
		} );
	}

	if ( 'loading' === document.readyState ) {
		document.addEventListener( 'DOMContentLoaded', dsmInitBeforeAfterImageCompare );
	} else {
		dsmInitBeforeAfterImageCompare();
	}

	window.addEventListener( 'load', dsmInitBeforeAfterImageCompare );

	if ( window.jQuery ) {
		window.jQuery( document ).ajaxComplete( function () {
			dsmInitBeforeAfterImageCompare();
		} );
	}
} )();
