/**
 * ElementSell — v panelu editoru doplní legacy email_from_name z faktury_jmeno.
 */
( function () {
	'use strict';

	function getConfig() {
		if (
			typeof elementor !== 'undefined'
			&& elementor.config
			&& elementor.config.elementsellEmailFromName
		) {
			return elementor.config.elementsellEmailFromName;
		}

		if ( typeof window.elementsellEmailFromName !== 'undefined' ) {
			return window.elementsellEmailFromName;
		}

		return null;
	}

	function isLegacyValue( value, legacyList ) {
		var trimmed = ( value || '' ).trim();

		if ( ! legacyList || ! legacyList.length ) {
			return trimmed === '' || trimmed === 'Platební formulář' || trimmed === 'Ruda z Ostravy';
		}

		return legacyList.indexOf( trimmed ) !== -1;
	}

	function patchEmailFromNameModel( model ) {
		if ( ! model || model.get( 'widgetType' ) !== 'elementsell_payment_form' ) {
			return;
		}

		var config = getConfig();

		if ( ! config || ! config.default ) {
			return;
		}

		var current = ( model.getSetting( 'email_from_name' ) || '' ).trim();

		if ( ! isLegacyValue( current, config.legacy ) ) {
			return;
		}

		if ( current === config.default ) {
			return;
		}

		model.setSetting( 'email_from_name', config.default );
	}

	function patchEmailFromNameControlInput() {
		var config = getConfig();

		if ( ! config || ! config.default ) {
			return;
		}

		var input = document.querySelector(
			'.elementor-control-email_from_name input[data-setting="email_from_name"]'
		);

		if ( ! input ) {
			return;
		}

		var current = ( input.value || '' ).trim();

		if ( ! isLegacyValue( current, config.legacy ) || current === config.default ) {
			return;
		}

		input.value = config.default;
	}

	function bindElementorPanelHooks() {
		if (
			typeof elementor === 'undefined'
			|| ! elementor.hooks
			|| typeof elementor.hooks.addAction !== 'function'
		) {
			return;
		}

		elementor.hooks.addAction(
			'panel/open_editor/widget/elementsell_payment_form',
			function ( panel, model ) {
				patchEmailFromNameModel( model );
				window.setTimeout( patchEmailFromNameControlInput, 0 );
				window.setTimeout( patchEmailFromNameControlInput, 150 );
			}
		);
	}

	function initEmailFromNameEditorPatch() {
		bindElementorPanelHooks();
	}

	function bindEditorReady() {
		if ( typeof jQuery !== 'undefined' ) {
			jQuery( initEmailFromNameEditorPatch );
		} else if ( document.readyState === 'loading' ) {
			document.addEventListener( 'DOMContentLoaded', initEmailFromNameEditorPatch );
		} else {
			initEmailFromNameEditorPatch();
		}

		if (
			typeof elementor !== 'undefined'
			&& elementor.channels
			&& elementor.channels.editor
		) {
			elementor.channels.editor.on( 'editor:init', initEmailFromNameEditorPatch );
		}
	}

	bindEditorReady();
} )();
