jQuery(function ($) {
	if (typeof formulatePricingForms === 'undefined') {
		return;
	}

	$('#bf-check-all').on('change', function () {
		$('.bf-form-check').prop('checked', this.checked);
	});

	$(document).on('click', '.bf-sc-copy', function () {
		var $el  = $(this);
		var text = $el.data('sc');

		function onCopied() {
			$el.addClass('copied').text('Copied!');
			setTimeout(function () {
				$el.removeClass('copied').html('<i class="hgi-stroke hgi-copy-01" style="font-size:12px"></i> ' + text);
			}, 2000);
		}

		if (navigator.clipboard && window.isSecureContext) {
			navigator.clipboard.writeText(text).then(onCopied).catch(function () {
				fallbackCopy(text, onCopied);
			});
		} else {
			fallbackCopy(text, onCopied);
		}
	});

	function fallbackCopy(text, callback) {
		var $tmp = $('<textarea>').val(text).css({ position: 'fixed', opacity: 0 }).appendTo('body');
		$tmp[0].select();
		try {
			document.execCommand('copy');
			callback();
		} catch (e) {
			// Ignore copy failures in unsupported browsers.
		}
		$tmp.remove();
	}

	$(document).on('click', '.bf-duplicate-btn', function () {
		var $btn = $(this);
		$btn.prop('disabled', true).text(formulatePricingForms.strings.duplicating);
		$.post(
			ajaxurl,
			{
				action: 'formulate_pricing_duplicate_form',
				form_id: $btn.data('id'),
				nonce: $btn.data('nonce'),
			},
			function (res) {
				if (res.success) {
					location.href = formulatePricingForms.editBaseUrl + res.data.new_id;
				} else {
					alert(res.data.message || formulatePricingForms.strings.errorOccurred);
					$btn.prop('disabled', false).text(formulatePricingForms.strings.duplicate);
				}
			}
		);
	});

	$(document).on('click', '.bf-confirm-delete', function (e) {
		if (!confirm(formulatePricingForms.strings.confirmDelete)) {
			e.preventDefault();
		}
	});
});
