(function( $ ) {
	'use strict';
	// Add click event listener to all '.wdpop_core-cloneable-title' elements
	$(function() {
		$('.wdpop_core-cloneable-title').click(function() {
			// Get the clicked wrapper element
			var clickedWrapper = $(this).closest('.wdpop_core-cloneable-item');
		
			// Remove the 'wdpop_core-cloneable-item-active' class from all other wrapper elements
			clickedWrapper.siblings('.wdpop_core-cloneable-item').removeClass('wdpop_core-cloneable-item-active');
		
			// Toggle the class only on the clicked wrapper's item
			clickedWrapper.toggleClass('wdpop_core-cloneable-item-active');
		});
	});

})( jQuery );



document.addEventListener("DOMContentLoaded", function(){
	
	document.addEventListener('click', function (e) {
		const wrapper = e.target.closest('.wdpop_core-shortcode-wrapper');
		if (!wrapper) return; // Click not on wrapper

		const content = wrapper.querySelector('.wdpop_core-shortcode-contnet')?.textContent || '';
		const originalTooltip = wrapper.getAttribute('data-tooltip');

		if (content.trim() !== '') {
			navigator.clipboard.writeText(content).then(function () {
				// Change tooltip to "Copied!" + apply green background
				wrapper.setAttribute('data-tooltip', 'Copied!');
				wrapper.classList.add('copied');

				// Revert tooltip and style after 1s
				setTimeout(function () {
					wrapper.setAttribute('data-tooltip', originalTooltip);
					wrapper.classList.remove('copied');
				}, 1200);

			}).catch(function (err) {
				console.error('Clipboard copy failed', err);
			});
		}
	});
	// Clicl to copy end
	
	//Sync mailchimp list
	const syncBtn = document.querySelector('.wdpops-sync-mc--list');
	const syncedTextTime = 1000;
	const syncedList = document.querySelector('.wdpop_core--synced-list');
	syncBtn?.addEventListener('click', (e) => {
		e.preventDefault();
		const syncIcon = syncBtn.querySelector('.wdpop_core--icon');
		const syncContent = syncBtn.querySelector('.wdpop_core--sync-content');
		syncIcon.classList.add('fa-spin');
		
		let data = new FormData();
		data.append('action', 'wing_popup_mc_list_update');
		data.append('nonce', wdpop_admin.nonce);

		fetch(wdpop_admin.ajax_url, {
			method: 'POST',
			credentials: 'same-origin',
			body: data
		})
		.then(res => res.json())
		.then(json => {
		
			if (json.success) {
				
				syncContent.textContent = 'Synced. Reloading...';
				setTimeout(function () {
					location.reload();
				}, syncedTextTime);
			
				const listNow = json.data.list;
				const valuesArray = Object.values(listNow);
				const commaSeparatedValues = valuesArray.join(', ');
				syncedList.textContent = commaSeparatedValues;
				
			} else {
				console.log(json.data.message);
			}
			syncIcon.classList.remove('fa-spin');
		});
		
		
	});
	
});
	