/**
 * ElementSell — opt-in odložený přechod ze stub režimu na plnou funkci v Elementor editoru.
 *
 * Výchozí: vypnuto (reloadEnabled=false). Stub režim načítá plné controls bez reloadu.
 * Zapnutí: define( 'ELEMENTSELL_ELEMENTOR_DEFERRED_RELOAD', true ); v wp-config.php
 */
( function () {
	'use strict';

	var config = window.elementsellDeferredBoot || {};

	if ( config.reloadEnabled === false ) {
		return;
	}

	var delayMs = parseInt( config.delayMs, 10 ) || 5000;
	var cookieName = config.cookieName || 'elementsell_editor_deferred';
	var cookiePaths = Array.isArray( config.cookiePaths ) && config.cookiePaths.length
		? config.cookiePaths
		: [ '/' ];
	var messages = config.messages || {};
	var started = false;
	var noticeEl = null;
	var manualBtn = null;
	var countdownIntervalId = null;
	var reloadFlagKey = 'elementsell_deferred_reload';
	var reloadDelayMs = 400;

	function log( message ) {
		// eslint-disable-next-line no-console
		console.log( '[ElementSell deferred]', message );
	}

	function getMessage( key, fallback ) {
		return messages[ key ] || fallback;
	}

	function hasDeferredCookie() {
		var prefix = cookieName + '=1';
		var parts = document.cookie ? document.cookie.split( ';' ) : [];

		for ( var i = 0; i < parts.length; i += 1 ) {
			if ( parts[ i ].trim().indexOf( prefix ) === 0 ) {
				return true;
			}
		}

		return false;
	}

	function setDeferredCookieClient() {
		var secure = window.location.protocol === 'https:' ? '; Secure' : '';
		var maxAge = parseInt( config.cookieMaxAge, 10 ) || 600;
		var pathsSet = [];

		for ( var p = 0; p < cookiePaths.length; p += 1 ) {
			var path = cookiePaths[ p ] || '/';
			var cookieValue =
				cookieName +
				'=1; path=' +
				path +
				'; max-age=' +
				maxAge +
				'; SameSite=Lax' +
				secure;

			document.cookie = cookieValue;
			pathsSet.push( path );
		}

		log(
			'document.cookie set: ' +
				cookieName +
				' paths=' +
				pathsSet.join( ',' ) +
				' max-age=' +
				maxAge
		);
	}

	function setDeferredCookieServer() {
		if ( ! config.ajaxUrl || ! config.nonce ) {
			log( 'ajax skipped: missing ajaxUrl or nonce in elementsellDeferredBoot' );
			return Promise.resolve( false );
		}

		var body = new URLSearchParams();
		body.append( 'action', 'elementsell_deferred_editor_boot' );
		body.append( 'nonce', config.nonce );

		if ( config.sessionKey ) {
			body.append( 'session_key', config.sessionKey );
		}

		log( 'ajax start: elementsell_deferred_editor_boot' );

		return fetch( config.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			},
			body: body.toString(),
		} )
			.then( function ( response ) {
				if ( ! response.ok ) {
					throw new Error( 'HTTP ' + response.status );
				}

				return response.json();
			} )
			.then( function ( payload ) {
				if ( ! payload || ! payload.success ) {
					throw new Error( 'ajax rejected' );
				}

				log( 'ajax ok: server cookie + transient set' );
				return true;
			} );
	}

	function ensureNotice() {
		if ( noticeEl ) {
			return;
		}

		noticeEl = document.createElement( 'div' );
		noticeEl.setAttribute( 'id', 'elementsell-deferred-notice' );
		noticeEl.style.cssText =
			'position:fixed;top:0;left:0;right:0;z-index:999999;' +
			'background:#2271b1;color:#fff;padding:12px 16px;' +
			'font:13px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;' +
			'box-shadow:0 2px 10px rgba(0,0,0,.2);' +
			'display:flex;align-items:center;justify-content:center;gap:12px;flex-wrap:wrap;' +
			'pointer-events:auto;';

		var textEl = document.createElement( 'span' );
		textEl.setAttribute( 'id', 'elementsell-deferred-notice-text' );
		noticeEl.appendChild( textEl );

		manualBtn = document.createElement( 'button' );
		manualBtn.type = 'button';
		manualBtn.setAttribute( 'id', 'elementsell-deferred-manual-btn' );
		manualBtn.textContent = getMessage( 'manual', 'Načíst plné nastavení formuláře' );
		manualBtn.style.cssText =
			'background:#fff;color:#2271b1;border:0;border-radius:4px;' +
			'padding:8px 14px;font:inherit;font-weight:600;cursor:pointer;' +
			'pointer-events:auto;';
		manualBtn.addEventListener( 'click', function ( event ) {
			event.preventDefault();
			event.stopPropagation();
			log( 'manual button clicked' );
			activateFullMode();
		} );
		noticeEl.appendChild( manualBtn );

		document.body.appendChild( noticeEl );
	}

	function updateNotice( text, isError, buttonLabel ) {
		ensureNotice();

		if ( isError ) {
			noticeEl.style.background = '#8a2424';
			if ( manualBtn ) {
				manualBtn.style.color = '#8a2424';
			}
		} else {
			noticeEl.style.background = '#2271b1';
			if ( manualBtn ) {
				manualBtn.style.color = '#2271b1';
			}
		}

		var textEl = document.getElementById( 'elementsell-deferred-notice-text' );

		if ( textEl ) {
			textEl.textContent = text;
		}

		if ( manualBtn && buttonLabel ) {
			manualBtn.textContent = buttonLabel;
		}
	}

	function removeNotice() {
		if ( countdownIntervalId ) {
			window.clearInterval( countdownIntervalId );
			countdownIntervalId = null;
		}

		if ( noticeEl && noticeEl.parentNode ) {
			noticeEl.parentNode.removeChild( noticeEl );
			noticeEl = null;
			manualBtn = null;
		}
	}

	function reloadEditor() {
		try {
			window.sessionStorage.setItem( reloadFlagKey, '1' );
		} catch ( storageError ) {
			log( 'sessionStorage unavailable, reload without flag' );
		}

		log( 'reloading editor in ' + reloadDelayMs + 'ms' );

		window.setTimeout( function () {
			window.location.reload();
		}, reloadDelayMs );
	}

	function activateFullMode() {
		if ( manualBtn ) {
			manualBtn.disabled = true;
		}

		log( 'activating full mode (ajax + cookie + reload)' );
		updateNotice(
			getMessage( 'active', 'Načítám plná nastavení formuláře…' ),
			false,
			getMessage( 'manual', 'Načíst plné nastavení formuláře' )
		);

		setDeferredCookieServer()
			.catch( function ( ajaxError ) {
				log( 'server cookie failed, using document.cookie: ' + ajaxError.message );
				setDeferredCookieClient();
				return false;
			} )
			.then( function () {
				if ( ! hasDeferredCookie() ) {
					setDeferredCookieClient();
				}

				if ( ! hasDeferredCookie() ) {
					log( 'warning: deferred cookie still not visible in document.cookie before reload' );
				} else {
					log( 'deferred cookie visible in browser before reload' );
				}

				reloadEditor();
			} );
	}

	function showReloadFailedNotice() {
		log(
			'reload completed but stub script still running — deferred boot not applied server-side'
		);
		updateNotice(
			getMessage(
				'failed',
				'Plná nastavení se po obnovení nenačetla. Klikněte na tlačítko níže nebo obnovte stránku (F5).'
			),
			true,
			getMessage( 'retry', 'Zkusit znovu' )
		);
	}

	function startCountdown() {
		if ( started ) {
			return;
		}

		started = true;
		log( 'script loaded, config delayMs=' + delayMs );

		if ( hasDeferredCookie() ) {
			log( 'deferred cookie already present in browser — reloading for server boot' );
			updateNotice(
				getMessage( 'active', 'Načítám plná nastavení formuláře…' ),
				false
			);
			reloadEditor();
			return;
		}

		var reloadAttempted = false;

		try {
			reloadAttempted = window.sessionStorage.getItem( reloadFlagKey ) === '1';
			window.sessionStorage.removeItem( reloadFlagKey );
		} catch ( storageError ) {
			reloadAttempted = false;
		}

		if ( reloadAttempted ) {
			showReloadFailedNotice();
			return;
		}

		var totalSeconds = Math.ceil( delayMs / 1000 );
		var remaining = totalSeconds;

		log( 'editor ready, countdown ' + totalSeconds + 's (or use manual button)' );

		updateNotice(
			getMessage(
				'waiting',
				'ElementSell: plná nastavení formuláře za %d s (stránka se pak sama obnoví)'
			).replace( '%d', String( remaining ) ),
			false
		);

		countdownIntervalId = window.setInterval( function () {
			remaining -= 1;

			if ( remaining <= 0 ) {
				window.clearInterval( countdownIntervalId );
				countdownIntervalId = null;
				return;
			}

			updateNotice(
				getMessage( 'countdown', 'ElementSell: plná nastavení za %d s' ).replace(
					'%d',
					String( remaining )
				),
				false
			);
		}, 1000 );

		window.setTimeout( function () {
			if ( countdownIntervalId ) {
				window.clearInterval( countdownIntervalId );
				countdownIntervalId = null;
			}

			activateFullMode();
		}, delayMs );
	}

	function bindEditorReady( callback ) {
		var fired = false;

		function runOnce( source ) {
			if ( fired ) {
				return;
			}

			fired = true;
			log( 'editor ready via ' + ( source || 'unknown' ) );
			callback();
		}

		if ( typeof jQuery !== 'undefined' ) {
			jQuery( window ).on( 'elementor:init', function () {
				runOnce( 'elementor:init' );
			} );
		}

		if ( typeof elementor !== 'undefined' && elementor.on ) {
			elementor.on( 'preview:loaded', function () {
				runOnce( 'preview:loaded' );
			} );

			if (
				elementor.preview &&
				( elementor.preview.loaded || elementor.preview.isLoaded )
			) {
				runOnce( 'preview already loaded' );
			}
		}

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

		window.setTimeout( function () {
			runOnce( 'timeout fallback 3s' );
		}, 3000 );
	}

	log( 'boot script initialized' );
	bindEditorReady( startCountdown );
} )();
