window.handleConnectDomain = function () {
	const zipwpData = document.getElementById( 'zipwp-data' );
	const plan = zipwpData ? zipwpData.getAttribute( 'data-plan' ) : '';

	if (
		( plan === 'free' || plan === 'hobby' ) &&
		typeof window.zipwpOpenKeepSiteLive === 'function'
	) {
		window.zipwpOpenKeepSiteLive();
		return;
	}

	const appUrl = 'https://app.zipwp.com';
	const utmSource = 'zipwp-client-gate-screen';
	const utmMedium = 'connect-domain-cta';

	let url = appUrl + '/sites?utm_source=' + utmSource + '&utm_medium=' + utmMedium;

	// Add UUID to URL if available
	if ( zipwpData ) {
		const siteUuid = zipwpData.getAttribute( 'data-site-uuid' );
		if ( siteUuid && siteUuid.trim() !== '' ) {
			url = appUrl + '/sites?uuid=' + siteUuid + '&utm_source=' + utmSource + '&utm_medium=' + utmMedium;
		}
	}

	window.open( url, '_blank' );
};

window.handleContinueTemporary = function () {
	const continueBtn = document.querySelector( '.zipwp-continue-btn' );
	const zipwpData = document.getElementById( 'zipwp-data' );
	const nonceInput = document.querySelector( 'input[name="zipwp_site_protection_nonce"]' );

	// Validate required elements exist
	if ( ! continueBtn || ! zipwpData || ! nonceInput ) {
		console.error( 'Required elements not found.' );
		return;
	}

	const ajaxURL = zipwpData.getAttribute( 'data-url' );
	const nonce = nonceInput.value;

	if ( ! ajaxURL || ! nonce ) {
		console.error( 'AJAX URL or nonce not found.' );
		return;
	}

	continueBtn.disabled = true;
	continueBtn.textContent = 'Verifying...';

	const formData = new FormData();
	formData.append( 'action', 'zipwp_site_protection_call' );
	formData.append( 'nonce', nonce );

	fetch( ajaxURL, {
		method: 'POST',
		body: formData,
	} )
		.then( function ( response ) {
			return response.json();
		} )
		.then( function ( data ) {
			if ( data.success ) {
				continueBtn.textContent = 'Redirecting...';
				window.location.reload();
			} else {
				continueBtn.disabled = false;
				continueBtn.textContent = 'Continue with Temporary Site';
				console.error( 'Site verification failed.' );
			}
		} )
		.catch( function ( error ) {
			continueBtn.disabled = false;
			continueBtn.textContent = 'Continue with Temporary Site';
			console.error( 'Error:', error );
		} );
};
