/**
 * =====================================================================
 *  WordForm Admin Settings JavaScript
 *  ------------------------------------------------------------
 *  Handles:
 *   • General Settings Tab (save, reset, dynamic load)
 *   • Upload Settings Tab (save, reset)
 *   • Date & Range Builder Field Interactions
 *   • DataTables (Submissions, All Forms)
 *   • Block Editor auto-attach
 *   • WP Color Picker + jQuery UI integration
 *  ------------------------------------------------------------
 *  Author: SoftCoy | WordForm Pro
 *  Version: 2.0
 * =====================================================================
 */

/* -------------------------------------------------------
 * Date Comparison Utilities
 * ------------------------------------------------------- */

/**
 * Compare two ISO (YYYY-MM-DD) strings
 * @returns -1 (earlier), 0 (same), 1 (later)
 */
function compareDates(dateStr1, dateStr2) {
	const d1 = new Date(dateStr1);
	const d2 = new Date(dateStr2);
	if (d1.getTime() === d2.getTime()) return 0;
	else if (d1.getTime() < d2.getTime()) return -1;
	else return 1;
}

/**
 * Checks if date1 > date2 safely.
 */
function isDateGreater(date1, date2) {
	const d1 = new Date(date1);
	const d2 = new Date(date2);
	if (isNaN(d1) || isNaN(d2)) return false;
	return d1 > d2;
}

/* =====================================================================
 * MAIN ADMIN INITIALIZATION
 * ===================================================================== */
jQuery(document).ready(function ($) {

	function wordformNormalizeDialogCloseButton($root) {
		$root.find('.ui-dialog-titlebar-close').removeAttr('title').attr('aria-label', 'Close');
	}

	$(document).on('dialogopen', '.ui-dialog-content', function () {
		wordformNormalizeDialogCloseButton($(this).closest('.ui-dialog'));
	});

	$(document).on('mouseenter focusin', '.wordform-admin-dialog .ui-dialog-titlebar-close, .ui-dialog .ui-dialog-titlebar-close', function () {
		wordformNormalizeDialogCloseButton($(this).closest('.ui-dialog'));
	});

	// -----------------------------------------------------------------
	// 1️⃣ Block Editor: Attach WordForm block automatically
	// -----------------------------------------------------------------
	let wordformPostIDReadyHandler = 0;

	function wordformBlockEditorWaitTohavePostIdReady() {
		let postID = wp.data.select("core/editor").getCurrentPostId();
		if (postID) {
			clearInterval(wordformPostIDReadyHandler);
			let block = wp.blocks.createBlock('wordform-block/wordform', {
				wordformid: wordform_admin_view_page_script_obj.attachto_wordformid
			});
			wp.data.dispatch('core/block-editor').insertBlock(block);
		}
	}

	if (
		wordform_admin_view_page_script_obj.attachto_wordformid &&
		wordform_admin_view_page_script_obj.attachto_wordformid.length > 0
	) {
		wordformPostIDReadyHandler = setInterval(() => wordformBlockEditorWaitTohavePostIdReady(), 1000);
	}

	// -----------------------------------------------------------------
	// 2️⃣ All Forms Page: DataTable + Copy Shortcode
	// -----------------------------------------------------------------
	if ($('div#wordformAllFormsWrapperTable').length > 0) {
		$('#wordformAllFormsTable').DataTable({ order: [[2, 'desc']] });
		$('#wordformAllFormsWrapperTable').fadeIn(300);
		$('body').removeClass('wp-core-ui');
		new ClipboardJS('.sc-wordform-shortcode-copy-text');

		$('body').on('mouseenter', '#wordformAllFormsTable tr', function () {
			$(this).addClass('wordform-row-hover');
		});
		$('body').on('mouseleave', '#wordformAllFormsTable tr', function () {
			$(this).removeClass('wordform-row-hover');
		});
		$('body').on('click', '.sc-wordform-shortcode-copy-text', function () {
			let copyBtnTextEle = $(this);
			copyBtnTextEle.html(wordform_admin_view_page_script_obj.wordform_copied_text);
			setTimeout(() => {
				copyBtnTextEle.html(wordform_admin_view_page_script_obj.wordform_copy_shortcode_text);
			}, 3000);
		});
	}

	// -----------------------------------------------------------------
	// 3️⃣ Create Form Page: Warn before leaving unsaved form
	// -----------------------------------------------------------------
	if ($('div.wordform-draggable-elements-div-wrapper').length > 0) {
		$(window).on('beforeunload', function () {
			let scWordFormElementDropped = $('.wordform-dropzone-div-wrapper').children().length;
			let scWordFormID = $('.wordform-created-form-id').val();
			if ($.trim(scWordFormID).length === 0 && scWordFormElementDropped > 0) {
				return 'Please click Save Form button to save your form.';
			}
			return '';
		});
	}

	// -----------------------------------------------------------------
	// 4️⃣ WP Color Picker Initialization
	// -----------------------------------------------------------------
	const colorPickerSelectors =
		'.sc-wordform-form-submit-button-background-color, ' +
		'.sc-wordform-form-submit-button-background-hover-color, ' +
		'.sc-wordform-form-submit-button-font-color, ' +
		'.sc-wordform-upload-progress-bar-color';

	$(colorPickerSelectors).wpColorPicker({
		change: function () { },
		clear: function () { },
		hide: true,
		palettes: true
	});

	// -----------------------------------------------------------------
	// 5️⃣ jQuery UI Tabs
	// -----------------------------------------------------------------
	if ($('div#tabs').length > 0) {
		$('#tabs').tabs().promise().done(() => {
			$('.sc-wordform-tabs-wrapper-div').fadeIn(300);
		});
	}

	// -----------------------------------------------------------------
	// 6️⃣ Submissions Report: Summary DataTable
	// -----------------------------------------------------------------
	if ($('div#wordformUsersSubmissionReportWrapperTable').length > 0) {
		const updateSubmissionReportSummary = function(summary) {
			if (!summary || typeof summary !== 'object') {
				return;
			}

			$('#wordformSubmissionReportSummaryForms').text(summary.forms || 0);
			$('#wordformSubmissionReportSummaryTotal').text(summary.total || 0);
			$('#wordformSubmissionReportSummaryAverage').text(summary.average || 0);
			$('#wordformSubmissionReportSummaryLatest').text(summary.latest || 'No submissions yet');
		};

		$('#wordformUsersSubmissionReportDataTable').DataTable({
			processing: true,
			serverSide: true,
			paging: true,
			searching: true,
			lengthChange: true,
			pageLength: 10,
			lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
			ajax: {
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				dataSrc: function(json) {
					updateSubmissionReportSummary(json.summary || {});
					return json.data || [];
				},
				data: function (d) {
					d.action = 'sc_wordform_users_submission_report_load';
					d.security = wordform_admin_view_page_script_obj.nonce;
				}
			},
			columns: [
				{ data: 'formName' },
				{ data: 'totalSubmission' },
				{ data: 'lastSubmissionDate' }
			],
			order: [[2, 'desc']]
		});
		$('#wordformUsersSubmissionReportWrapperTable').fadeIn(300);
	}

	// -----------------------------------------------------------------
	// 7️⃣ Submission Data Page: Form-specific DataTable
	// -----------------------------------------------------------------
	if ($('#wordformUsersFormSubmissionDataWrapperTable').length > 0) {
		const formId = $('#wordformUsersFormSubmissionDataWrapperTable').data('form-id');
		const $submissionTable = $('#wordformUsersFormSubmissionDataTable');
		const updateSubmissionDetailSummary = function(summary) {
			if (!summary || typeof summary !== 'object') {
				return;
			}

			$('#wordformSubmissionSummaryTotal').text(summary.total || 0);
			$('#wordformSubmissionSummaryToday').text(summary.today || 0);
			$('#wordformSubmissionSummaryWeek').text(summary.week || 0);
			$('#wordformSubmissionSummaryLatest').text(summary.latest || 'No submissions yet');
		};

		if ($.fn.DataTable.isDataTable($submissionTable)) {
			$submissionTable.DataTable().destroy();
			$submissionTable.find('tbody').empty();
		}

		$submissionTable.DataTable({
			processing: true,
			serverSide: true,
			paging: true,
			searching: true,
			lengthChange: true,
			pageLength: 10,
			lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
			ajax: {
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				dataSrc: function(json) {
					updateSubmissionDetailSummary(json.summary || {});
					return json.data || [];
				},
				data: function (d) {
					d.action = 'sc_wordform_users_submission_data_load';
					d.security = wordform_admin_view_page_script_obj.nonce;
					d.form_id = formId;
				}
			},
			columns: [
				{ data: 'submitter', defaultContent: '' },
				{ data: 'preview', defaultContent: '' },
				{ data: 'date', defaultContent: '' },
				{ data: 'details', orderable: false, searchable: false, defaultContent: '' }
			],
			order: [[2, 'desc']]
		});

		$('#wordformUsersFormSubmissionDataWrapperTable').fadeIn(300);
	}

	$('body').on('click', '.wordform-report-export-btn', function (event) {
		event.preventDefault();
		event.stopPropagation();

		const $button = $(this);
		const $popover = $button.siblings('.wordform-report-export-popover');
		const willOpen = $popover.prop('hidden');

		$('.wordform-report-export-popover').attr('hidden', true);
		$('.wordform-report-export-btn').attr('aria-expanded', 'false');

		if (willOpen) {
			$popover.prop('hidden', false);
			$button.attr('aria-expanded', 'true');
		}
	});

	$(document).on('click', function (event) {
		if (!$(event.target).closest('.wordform-report-export-popover-wrapper').length) {
			$('.wordform-report-export-popover').attr('hidden', true);
			$('.wordform-report-export-btn').attr('aria-expanded', 'false');
		}
	});

	$('body').on('submit', '.wordform-report-export-form', function (event) {
		const $form = $(this);
		const $checkedSheets = $form.find('input[name="export_sheets[]"]:checked:not(:disabled)');
		const $error = $form.find('.wordform-report-export-sheet-error');

		if (!$checkedSheets.length) {
			event.preventDefault();
			$error.prop('hidden', false);
			return;
		}

		$error.prop('hidden', true);
	});

	$('body').on('click', '.wordform-report-export-sheet-option-locked', function (event) {
		const upgradeUrl = $(this).data('upgrade-url');
		if (upgradeUrl) {
			event.preventDefault();
			window.location.href = upgradeUrl;
		}
	});

	$('body').on('keydown', '.wordform-report-export-sheet-option-locked', function (event) {
		if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault();
			$(this).trigger('click');
		}
	});

	if ($('.wordform-support-page-wrapper').length > 0) {
		const supportOfficeStatusUrl = wordform_admin_view_page_script_obj.support_office_status_url || 'https://softcoy.com/api/v1/support/tickets/status';
		const supportBrandIcons = {
			softcoy: wordform_admin_view_page_script_obj.support_softcoy_icon_url || 'https://www.softcoy.com/brand-assets/logos/softcoy-mark.png',
			wordform: wordform_admin_view_page_script_obj.support_wordform_icon_url || 'https://softcoy.com/brand-assets/logos/wordform-pro.svg'
		};

		const formatSupportLabel = function (value) {
			if (!value) {
				return '—';
			}
			return String(value)
				.replace(/_/g, ' ')
				.replace(/\b\w/g, (m) => m.toUpperCase())
				.replace(/\bCustomer\b/g, 'User')
				.replace(/\bSoftcoy Admin\b/gi, 'SOFTCOY Support')
				.replace(/\bSoftcoy Support\b/gi, 'SOFTCOY Support');
		};

		const formatSupportRoleLabel = function (role) {
			const roleKey = String(role || '').toLowerCase();
			if (roleKey.includes('customer') || roleKey.includes('user')) {
				return 'Plugin User';
			}
			if (roleKey.includes('support') || roleKey.includes('admin') || roleKey.includes('softcoy')) {
				return 'SOFTCOY Support';
			}
			return formatSupportLabel(role || 'support');
		};

		const escapeHtml = function (value) {
			return $('<div>').text(value || '').html();
		};

		const decodeSupportTicketPayload = function (rawPayload) {
			const parseSupportTicketJson = function (value) {
				if (!value) {
					return {};
				}

				try {
					const parsed = JSON.parse(value);
					return parsed && typeof parsed === 'object' ? parsed : {};
				} catch (error) {
					return null;
				}
			};

			const decodedUriPayload = function (value) {
				try {
					return decodeURIComponent(value);
				} catch (error) {
					return null;
				}
			};

			const decodedBase64Payload = function (value) {
				try {
					return decodeURIComponent(escape(window.atob(value)));
				} catch (error) {
					return null;
				}
			};

			const directPayload = parseSupportTicketJson(rawPayload || '{}');
			if (directPayload) {
				return directPayload;
			}

			const uriPayload = parseSupportTicketJson(decodedUriPayload(rawPayload || ''));
			if (uriPayload) {
				return uriPayload;
			}

			const base64Payload = parseSupportTicketJson(decodedBase64Payload(rawPayload || ''));
			if (base64Payload) {
				return base64Payload;
			}

			try {
				const parsed = JSON.parse(rawPayload || '{}');
				return parsed && typeof parsed === 'object' ? parsed : {};
			} catch (error) {
				return {};
			}
		};

		const encodeSupportTicketPayload = function (ticketData) {
			try {
				return window.btoa(unescape(encodeURIComponent(JSON.stringify(ticketData || {}))));
			} catch (error) {
				return '';
			}
		};

		const normalizeSupportTicket = function (ticketData) {
			const replies = Array.isArray(ticketData?.replies) ? ticketData.replies : [];
			return {
				ticket_uuid: ticketData?.ticket_uuid || '',
				sender_email: ticketData?.sender_email || '',
				initial_message: ticketData?.initial_message || ticketData?.message || '',
				initial_author_name: ticketData?.initial_author_name || 'Plugin User',
				initial_created_at: ticketData?.initial_created_at || ticketData?.created_at || '',
				issue_type: ticketData?.issue_type || 'General',
				channels: Array.isArray(ticketData?.channels) ? ticketData.channels : [],
				overall_status: formatSupportLabel(ticketData?.overall_status || ticketData?.overall_status_key || 'received'),
				email_status: ticketData?.email_status || '—',
				office_status: ticketData?.office_status || '—',
				office_status_key: ticketData?.office_status_key || '',
				office_status_label: formatSupportLabel(ticketData?.office_status_label || ticketData?.office_status || 'Open'),
				status_badge_class: ticketData?.status_badge_class || '',
				status_badge_label: ticketData?.status_badge_label || '',
				office_ticket_id: ticketData?.office_ticket_id || '',
				office_update: ticketData?.office_update || 'Awaiting office update.',
				created_at: ticketData?.created_at || '',
				updated_at: ticketData?.updated_at || '',
				office_last_synced_at: ticketData?.office_last_synced_at || '',
				resolved_at: ticketData?.resolved_at || '',
				timings: ticketData?.timings && typeof ticketData.timings === 'object' ? ticketData.timings : {},
				replies: replies
			};
		};

		const supportStatusKey = function (ticket) {
			return String(ticket.office_status_key || ticket.office_status || ticket.overall_status || 'open').toLowerCase().replace(/\s+/g, '_');
		};

		const hasSupportReply = function (ticket) {
			return Array.isArray(ticket.replies) && ticket.replies.length > 0;
		};

		const latestSupportReplyRole = function (ticket) {
			const replies = Array.isArray(ticket.replies) ? ticket.replies : [];
			const latestReply = replies.length ? replies[replies.length - 1] : {};
			return String(latestReply?.role || '').toLowerCase();
		};

		const supportStatusBadgeClass = function (ticket) {
			const key = supportStatusKey(ticket);
			if (ticket.status_badge_class) {
				return ticket.status_badge_class;
			}
			if (['resolved', 'closed', 'solved'].includes(key)) {
				return 'is-resolved';
			}
			if (['failed', 'error', 'rejected'].includes(key)) {
				return 'is-error';
			}
			if (key === 'customer_replied' || latestSupportReplyRole(ticket).includes('customer')) {
				return 'is-waiting';
			}
			if (hasSupportReply(ticket) || ['answered', 'replied', 'in_review', 'pending_customer', 'waiting_on_customer'].includes(key)) {
				return 'is-replied';
			}
			return 'is-open';
		};

		const supportStatusBadgeLabel = function (ticket) {
			const key = supportStatusKey(ticket);
			if (ticket.status_badge_label) {
				return ticket.status_badge_label;
			}
			if (['resolved', 'closed', 'solved'].includes(key)) {
				return 'Solved';
			}
			if (['failed', 'error', 'rejected'].includes(key)) {
				return 'Needs attention';
			}
			if (key === 'customer_replied' || latestSupportReplyRole(ticket).includes('customer')) {
				return 'Waiting for SOFTCOY';
			}
			if (hasSupportReply(ticket) || ['answered', 'replied', 'in_review', 'pending_customer', 'waiting_on_customer'].includes(key)) {
				return 'SOFTCOY replied';
			}
			return 'Open';
		};

		const mergeSupportTicketWithOffice = function (ticketData, officeTicket) {
			const ticket = normalizeSupportTicket(ticketData);
			if (!officeTicket || typeof officeTicket !== 'object') {
				return ticket;
			}

			return normalizeSupportTicket({
				...ticket,
				overall_status: formatSupportLabel(officeTicket.status_label || officeTicket.status || ticket.overall_status),
				office_status: formatSupportLabel(officeTicket.status || ticket.office_status),
				office_status_key: officeTicket.status || ticket.office_status_key,
				office_status_label: officeTicket.status_label || ticket.office_status_label,
				status_badge_class: '',
				status_badge_label: '',
				office_update: officeTicket?.latest_reply?.message || ticket.office_update,
				updated_at: officeTicket.updated_at || ticket.updated_at,
				office_last_synced_at: officeTicket.updated_at || ticket.office_last_synced_at,
				resolved_at: officeTicket.resolved_at || ticket.resolved_at,
				timings: officeTicket.timings || ticket.timings,
				replies: Array.isArray(officeTicket.replies) ? officeTicket.replies : ticket.replies
			});
		};

		const syncSupportTicketWithOffice = function (ticketData) {
			const ticket = normalizeSupportTicket(ticketData);

			if (!ticket.office_ticket_id || !ticket.sender_email) {
				return $.Deferred().resolve(ticket).promise();
			}

			return $.ajax({
				type: 'POST',
				url: supportOfficeStatusUrl,
				dataType: 'json',
				cache: false,
				contentType: 'application/json',
				data: JSON.stringify({
					email: ticket.sender_email,
					ticket_id: ticket.office_ticket_id
				})
			}).then(function (json) {
				const officeTicket = json && Array.isArray(json.tickets) ? json.tickets[0] : null;
				return mergeSupportTicketWithOffice(ticket, officeTicket);
			}).catch(function () {
				return ticket;
			});
		};

		const syncSupportTicketBatchWithOffice = function (ticketCollection) {
			const tickets = Array.isArray(ticketCollection) ? ticketCollection.map(normalizeSupportTicket) : [];
			const groupedTickets = {};
			const resolvedTickets = {};
			const deferred = $.Deferred();

			tickets.forEach(function (ticket) {
				if (!ticket.office_ticket_id || !ticket.sender_email) {
					resolvedTickets[ticket.ticket_uuid] = ticket;
					return;
				}

				if (!groupedTickets[ticket.sender_email]) {
					groupedTickets[ticket.sender_email] = [];
				}

				groupedTickets[ticket.sender_email].push(ticket);
			});

			const groupedEntries = Object.keys(groupedTickets);
			if (!groupedEntries.length) {
				deferred.resolve(resolvedTickets);
				return deferred.promise();
			}

			const requests = groupedEntries.map(function (email) {
				const groupTickets = groupedTickets[email];
				return $.ajax({
					type: 'POST',
					url: supportOfficeStatusUrl,
					dataType: 'json',
					cache: false,
					contentType: 'application/json',
					data: JSON.stringify({
						email: email,
						ticket_ids: groupTickets.map(function (ticket) {
							return ticket.office_ticket_id;
						})
					})
				}).done(function (response) {
					const officeTickets = Array.isArray(response?.tickets) ? response.tickets : [];

					groupTickets.forEach(function (ticket) {
						const officeTicket = officeTickets.find(function (candidate) {
							return candidate.ticket_id === ticket.office_ticket_id;
						});

						resolvedTickets[ticket.ticket_uuid] = mergeSupportTicketWithOffice(ticket, officeTicket);
					});
				}).fail(function () {
					groupTickets.forEach(function (ticket) {
						resolvedTickets[ticket.ticket_uuid] = ticket;
					});
				});
			});

			$.when.apply($, requests).always(function () {
				deferred.resolve(resolvedTickets);
			});

			return deferred.promise();
		};

		const buildSupportConversation = function (ticket) {
			const conversation = [];
			const initialMessage = $.trim(ticket.initial_message || '');
			if (initialMessage.length) {
				conversation.push({
					role: 'user',
					author_name: ticket.initial_author_name || 'Plugin User',
					message: initialMessage,
					created_at: ticket.initial_created_at || ticket.created_at || 'Submitted with ticket',
					is_initial: true
				});
			}

			(Array.isArray(ticket.replies) ? ticket.replies : []).forEach(function (reply) {
				if (!$.trim(reply?.message || '').length) {
					return;
				}
				conversation.push(reply);
			});

			return conversation;
		};

		const renderSupportReplies = function (ticket) {
			const conversation = buildSupportConversation(ticket);
			if (!conversation.length) {
				return '<div class="wordform-support-modal-empty">No conversation message has been recorded for this ticket yet.</div>';
			}

			return conversation.map(function (reply) {
				const roleLabel = formatSupportRoleLabel(reply?.role || (reply?.is_initial ? 'user' : 'support'));
				const isUser = roleLabel.toLowerCase().includes('user');
				const iconUrl = isUser ? supportBrandIcons.wordform : supportBrandIcons.softcoy;
				const authorName = isUser ? 'Plugin User' : 'SOFTCOY Support';
				return [
					'<article class="wordform-support-modal-reply ' + (isUser ? 'is-user' : 'is-support') + '">',
					'<div class="wordform-support-modal-reply-inner">',
					'<span class="wordform-support-modal-reply-avatar"><img src="' + escapeHtml(iconUrl) + '" alt="" loading="lazy"></span>',
					'<div class="wordform-support-modal-reply-content">',
					'<div class="wordform-support-modal-reply-meta">',
					'<strong>' + escapeHtml(authorName) + '</strong>',
					'<span>' + escapeHtml(reply?.created_at || 'Unknown time') + '</span>',
					'</div>',
					'<p class="wordform-support-modal-reply-message">' + escapeHtml(reply?.message || '') + '</p>',
					'</div>',
					'</div>',
					'</article>',
				].join('');
			}).join('');
		};

		const renderSupportTicketModal = function (ticketData) {
			const ticket = normalizeSupportTicket(ticketData);
			const channels = ticket.channels.length ? ticket.channels.join(', ') : 'Email';
			const timings = ticket.timings || {};
			const canReplyToOffice = !!ticket.office_ticket_id;
			const html = [
				'<div class="wordform-support-modal-grid">',
				'<div class="wordform-support-modal-stat"><span>Status</span><strong>' + escapeHtml(ticket.office_status_label || ticket.overall_status) + '</strong><small>' + escapeHtml(ticket.office_update) + '</small></div>',
				'<div class="wordform-support-modal-stat"><span>Submitted</span><strong>' + escapeHtml(ticket.created_at || timings.submitted_at || 'Unknown time') + '</strong><small>' + escapeHtml('First reply: ' + (timings.first_reply_at || 'Waiting')) + '</small></div>',
				'<div class="wordform-support-modal-stat"><span>Resolution</span><strong>' + escapeHtml(ticket.resolved_at || 'Open') + '</strong><small>' + escapeHtml('Resolved in: ' + (timings.resolved_in_seconds ? Math.round(timings.resolved_in_seconds / 60) + ' min' : 'Open')) + '</small></div>',
				'</div>',
				'<div class="wordform-support-modal-meta">',
				'<p><strong>Local Ticket:</strong> ' + escapeHtml(ticket.ticket_uuid) + '</p>',
				'<p><strong>SOFTCOY Ticket:</strong> ' + escapeHtml(ticket.office_ticket_id || 'Not assigned yet') + '</p>',
				'<p><strong>Issue:</strong> ' + escapeHtml(ticket.issue_type) + '</p>',
				'<p><strong>Channels:</strong> ' + escapeHtml(channels) + '</p>',
				'<p><strong>Email Status:</strong> ' + escapeHtml(ticket.email_status) + '</p>',
				'<p><strong>Office Status:</strong> ' + escapeHtml(ticket.office_status) + '</p>',
				'<p><strong>Last Synced:</strong> ' + escapeHtml(ticket.office_last_synced_at || ticket.updated_at || 'Not synced yet') + '</p>',
				'</div>',
				'<div class="wordform-support-modal-thread">',
				'<h4>Support Conversation</h4>',
				renderSupportReplies(ticket),
				canReplyToOffice ? [
					'<div class="wordform-support-modal-reply-form">',
					'<label for="wordformSupportModalReplyMessage"><strong>Reply to SOFTCOY Support</strong></label>',
					'<textarea id="wordformSupportModalReplyMessage" rows="5" placeholder="Reply on this ticket so the SOFTCOY support team can continue the same conversation."></textarea>',
					'<div class="wordform-support-modal-reply-actions">',
					'<span class="wordform-support-modal-reply-feedback" hidden></span>',
					'<button type="button" class="button button-primary wordform-support-modal-send-reply" data-ticket="' + escapeHtml(ticket.ticket_uuid) + '" data-email="' + escapeHtml(ticket.sender_email || '') + '">Send Reply</button>',
					'</div>',
					'</div>',
				].join('') : '<div class="wordform-support-modal-empty">This ticket does not have an office thread yet. Use the SOFTCOY Support Office delivery channel when creating the ticket.</div>',
				'</div>'
			].join('');

			$('#wordformSupportTicketModal .wordform-support-modal-body').html(html);
			$('#wordformSupportTicketModal')
				.attr('data-ticket-payload', encodeSupportTicketPayload(ticket))
				.prop('hidden', false);
			$('body').addClass('wordform-support-modal-open');
		};

		const closeSupportTicketModal = function () {
			$('#wordformSupportTicketModal').prop('hidden', true);
			$('body').removeClass('wordform-support-modal-open');
		};

		const buildSupportHistoryRowHtml = function (ticketData) {
			const ticket = normalizeSupportTicket(ticketData);
			const channelLabel = ticket.channels.length ? ticket.channels.join(', ') : 'Email';
			const channelStatus = '<span class="wordform-support-channel-stack"><span>Email: ' + escapeHtml(ticket.email_status) + '</span><span>Office: ' + escapeHtml(ticket.office_status) + '</span></span>';

			return [
				'<tr>',
				'<td><button type="button" class="button-link wordform-support-ticket-trigger" data-ticket="' + encodeSupportTicketPayload(ticket) + '"><strong>' + escapeHtml(ticket.ticket_uuid) + '</strong></button></td>',
				'<td>' + escapeHtml(ticket.issue_type) + '</td>',
				'<td>' + escapeHtml(channelLabel) + '</td>',
				'<td><span class="wordform-support-status-badge ' + escapeHtml(supportStatusBadgeClass(ticket)) + '">' + escapeHtml(supportStatusBadgeLabel(ticket)) + '</span></td>',
				'<td>' + channelStatus + '</td>',
				'<td>' + escapeHtml(ticket.office_update) + '</td>',
				'<td>' + escapeHtml(ticket.updated_at || new Date().toLocaleString()) + '</td>',
				'</tr>',
			].join('');
		};

		const prependSupportHistoryRow = function (ticketId, issueType, deliveryChannels, overallStatus, deliveryResults, initialMessage) {
			const $tbody = $('.wordform-support-history-table tbody');
			if (!$tbody.length) {
				window.location.reload();
				return;
			}

			const ticketData = {
				ticket_uuid: ticketId || '',
				sender_email: $('#wordformSupportSenderEmail').val() || '',
				initial_message: initialMessage || '',
				initial_author_name: 'Plugin User',
				initial_created_at: new Date().toLocaleString(),
				issue_type: formatSupportLabel(issueType || 'general'),
				channels: (deliveryChannels || []).map((channel) => formatSupportLabel(channel)).filter(Boolean),
				overall_status: formatSupportLabel(overallStatus || 'received'),
				email_status: formatSupportLabel(deliveryResults?.email?.status || ''),
				office_status: formatSupportLabel(deliveryResults?.office?.status || ''),
				office_status_key: deliveryResults?.office?.status || '',
				office_status_label: formatSupportLabel(deliveryResults?.office?.status_label || deliveryResults?.office?.status || ''),
				office_ticket_id: deliveryResults?.office?.ticket_id || '',
				office_update: deliveryResults?.office?.message || 'Awaiting office update.',
				created_at: new Date().toLocaleString(),
				updated_at: new Date().toLocaleString(),
				office_last_synced_at: '',
				resolved_at: deliveryResults?.office?.resolved_at || '',
				timings: deliveryResults?.office?.timings || {},
				replies: Array.isArray(deliveryResults?.office?.replies) ? deliveryResults.office.replies : []
			};

			$tbody.prepend(buildSupportHistoryRowHtml(ticketData));
		};

		const refreshSupportHistoryRows = function () {
			const buttonEntries = $('.wordform-support-ticket-trigger').map(function () {
				return {
					button: this,
					ticket: decodeSupportTicketPayload($(this).attr('data-ticket'))
				};
			}).get();

			syncSupportTicketBatchWithOffice(buttonEntries.map(function (entry) {
				return entry.ticket;
			})).then(function (resolvedTickets) {
				buttonEntries.forEach(function (entry) {
					const updatedTicket = resolvedTickets[entry.ticket.ticket_uuid] || normalizeSupportTicket(entry.ticket);
					$(entry.button).closest('tr').replaceWith(buildSupportHistoryRowHtml(updatedTicket));
				});
			});
		};

		$('body').on('click', '.wordform-support-ticket-trigger', function () {
			const $button = $(this);
			const currentTicket = decodeSupportTicketPayload($button.attr('data-ticket'));

			renderSupportTicketModal(currentTicket);

			syncSupportTicketWithOffice(currentTicket).then(function (updatedTicket) {
				$button.closest('tr').replaceWith(buildSupportHistoryRowHtml(updatedTicket));
				renderSupportTicketModal(updatedTicket);
			});
		});

		$('body').on('click', '.wordform-support-modal-close, .wordform-support-modal-backdrop', function () {
			closeSupportTicketModal();
		});

		$('body').on('click', '.wordform-support-modal-send-reply', function () {
			const $button = $(this);
			const $modal = $('#wordformSupportTicketModal');
			const $feedback = $modal.find('.wordform-support-modal-reply-feedback');
			const replyMessage = $.trim($('#wordformSupportModalReplyMessage').val() || '');
			const ticketUuid = $button.attr('data-ticket') || '';
			const senderEmail = $button.attr('data-email') || $('#wordformSupportTicketReplySenderEmail').val() || $('#wordformSupportSenderEmail').val() || '';
			const currentTicket = decodeSupportTicketPayload($modal.attr('data-ticket-payload'));

			if (!replyMessage.length) {
				$feedback.prop('hidden', false).removeClass('is-success').addClass('is-error').text('Write a reply before sending.');
				return;
			}

			$button.prop('disabled', true);
			$feedback.prop('hidden', false).removeClass('is-success is-error').addClass('is-pending').text('Sending reply to SOFTCOY Support Office...');

			$.ajax({
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				dataType: 'json',
				cache: false,
				data: {
					action: 'sc_wordform_reply_support_request',
					security: wordform_admin_view_page_script_obj.nonce,
					ticket_uuid: ticketUuid,
					sender_email: senderEmail,
					reply_message: replyMessage
				},
				success: function (json) {
					const isSuccess = json && json.status === 'success';
					$feedback.removeClass('is-pending is-success is-error').addClass(isSuccess ? 'is-success' : 'is-error').text((json && json.message) ? json.message : 'Reply could not be sent.');

					if (!isSuccess) {
						return;
					}

					const fallbackTicket = normalizeSupportTicket({
						...currentTicket,
						ticket_uuid: ticketUuid || currentTicket.ticket_uuid,
						sender_email: senderEmail || currentTicket.sender_email,
						overall_status: formatSupportLabel(json?.overall_status || currentTicket.overall_status),
						office_status: formatSupportLabel(json?.delivery_results?.office?.status || currentTicket.office_status),
						office_status_label: formatSupportLabel(json?.delivery_results?.office?.status_label || currentTicket.office_status_label),
						office_update: json?.delivery_results?.office?.message || currentTicket.office_update,
						updated_at: new Date().toLocaleString(),
						office_last_synced_at: new Date().toLocaleString(),
						timings: json?.delivery_results?.office?.timings || currentTicket.timings,
						replies: Array.isArray(json?.delivery_results?.office?.replies) ? json.delivery_results.office.replies : currentTicket.replies
					});
					const updateRowAndModal = function (updatedTicket) {
						const $rowButton = $('.wordform-support-ticket-trigger').filter(function () {
							return $.trim($(this).text()) === ticketUuid;
						}).first();

						if ($rowButton.length) {
							$rowButton.closest('tr').replaceWith(buildSupportHistoryRowHtml(updatedTicket));
						}

						renderSupportTicketModal(updatedTicket);
						$('#wordformSupportModalReplyMessage').val('');
						$('#wordformSupportTicketModal .wordform-support-modal-reply-feedback')
							.prop('hidden', false)
							.removeClass('is-pending is-error')
							.addClass('is-success')
							.text((json && json.message) ? json.message : 'Reply sent successfully.');
					};

					syncSupportTicketWithOffice(fallbackTicket)
						.then(function (updatedTicket) {
							updateRowAndModal(updatedTicket);
						})
						.fail(function () {
							updateRowAndModal(fallbackTicket);
						});
				},
				error: function () {
					$feedback.removeClass('is-pending is-success').addClass('is-error').text('Reply could not be sent right now.');
				},
				complete: function () {
					$button.prop('disabled', false);
				}
			});
		});

		$(document).on('keydown.wordformSupportModal', function (event) {
			if (event.key === 'Escape') {
				closeSupportTicketModal();
			}
		});

		refreshSupportHistoryRows();
		setInterval(refreshSupportHistoryRows, 30000);

		$('body').on('click', '#wordformSupportAttachButton', function () {
			$('#wordformSupportAttachments').trigger('click');
		});

		$('body').on('change', '#wordformSupportAttachments', function () {
			const files = Array.from(this.files || []);
			const $list = $('#wordformSupportAttachmentList');

			if (!files.length) {
				$list.empty();
				return;
			}

			$list.html(files.map(function (file) {
				const sizeKb = Math.max(1, Math.round(file.size / 1024));
				return '<span class="wordform-support-attachment-chip"><span class="dashicons dashicons-media-default" aria-hidden="true"></span>' + $('<div>').text(file.name + ' (' + sizeKb + ' KB)').html() + '</span>';
			}).join(''));
		});

		$('body').on('submit', '#wordformSupportRequestForm', function (event) {
			event.preventDefault();

			const $form = $(this);
			const $feedback = $('.wordform-support-submit-feedback');
			const $button = $form.find('.wordform-support-send-btn');
			const $pageTop = $('.wordform-support-page-wrapper');
			const includeDiagnostics = $('#wordformSupportIncludeDiagnostics').is(':checked') ? 'yes' : 'no';
			const deliveryChannels = $form.find('input[name="delivery_channels[]"]:checked').map(function () {
				return $(this).val();
			}).get();

			if (!deliveryChannels.length) {
				$feedback
					.prop('hidden', false)
					.removeClass('is-pending is-success')
					.addClass('is-error')
					.html(wordform_admin_view_page_script_obj.support_choose_channel);
				return;
			}

			$button.prop('disabled', true);
			$feedback
				.prop('hidden', false)
				.removeClass('is-success is-error')
				.addClass('is-pending')
				.html(wordform_admin_view_page_script_obj.support_sending_request);

			$('html, body').stop(true).animate({
				scrollTop: Math.max(0, $pageTop.offset().top - 32)
			}, 220);

			const formData = new FormData();
			formData.append('action', 'sc_wordform_submit_support_request');
			formData.append('security', wordform_admin_view_page_script_obj.nonce);
			formData.append('sender_email', $('#wordformSupportSenderEmail').val());
			formData.append('subject', $('#wordformSupportSubject').val());
			formData.append('issue_type', $('#wordformSupportIssueType').val());
			formData.append('message', $('#wordformSupportMessage').val());
			formData.append('include_diagnostics', includeDiagnostics);
			deliveryChannels.forEach(function (channel) {
				formData.append('delivery_channels[]', channel);
			});
			Array.from($('#wordformSupportAttachments')[0]?.files || []).forEach(function (file) {
				formData.append('support_attachments[]', file);
			});

			$.ajax({
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				dataType: 'json',
				cache: false,
				processData: false,
				contentType: false,
				data: formData,
				success: function (json) {
					const isSuccess = json && json.status === 'success';
					$feedback
						.removeClass('is-pending is-success is-error')
						.addClass(isSuccess ? 'is-success' : 'is-error')
						.html((json && json.message) ? json.message : wordform_admin_view_page_script_obj.support_request_failed);

					$('html, body').stop(true).animate({
						scrollTop: Math.max(0, $pageTop.offset().top - 32)
					}, 220);

					if (isSuccess) {
						prependSupportHistoryRow(
							json.ticket_uuid || '',
							$('#wordformSupportIssueType').val(),
							deliveryChannels,
							json.overall_status || 'received',
							json.delivery_results || {},
							$('#wordformSupportMessage').val()
						);
						$('#wordformSupportMessage').val('');
						$('#wordformSupportAttachments').val('');
						$('#wordformSupportAttachmentList').empty();
					}
				},
				error: function () {
					$feedback
						.removeClass('is-pending is-success')
						.addClass('is-error')
						.html(wordform_admin_view_page_script_obj.support_request_failed);

					$('html, body').stop(true).animate({
						scrollTop: Math.max(0, $pageTop.offset().top - 32)
					}, 220);
				},
				complete: function () {
					$button.prop('disabled', false);
				}
			});
		});
	}

	// -----------------------------------------------------------------
	// 8️⃣ Connection Send Log Page: Form-specific send status DataTable
	// -----------------------------------------------------------------
	if ($('#wordformConnectionStatusSendLogWrapperTable').length > 0) {
		const formId = $('#wordformConnectionStatusSendLogWrapperTable').data('form-id');
		$('#wordformConnectionStatusSendLogTable').DataTable({
			processing: true,
			serverSide: true,
			paging: true,
			searching: true,
			lengthChange: true,
			pageLength: 25,
			lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
			ajax: {
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				data: function (d) {
					d.action = 'sc_wordform_connection_status_send_log_load';
					d.security = wordform_admin_view_page_script_obj.nonce;
					d.form_id = formId;
				}
			},
			columns: [
				{ data: 'formName' },
				{ data: 'application' },
				{ data: 'sendStatus' },
				{ data: 'sendingDate' },
				{ data: 'details' }
			],
			order: [[3, 'desc']]
		});
	}

	// -----------------------------------------------------------------
	// 9️⃣ Settings -> Payment Reports: DataTable + live filters
	// -----------------------------------------------------------------
	function updateWordformPaymentReportsSummary() {
		const $summary = $('#wordformPaymentReportCurrentView');
		const $formSelect = $('#WordFormPaymentReportSelectForm');
		const $gatewaySelect = $('#WordFormPaymentReportSelectGateway');
		const $statusSelect = $('#WordFormPaymentReportSelectStatus');
		let formText = 'all forms';
		let gatewayText = 'all gateways';
		let statusText = 'all statuses';

		if (!$summary.length) {
			return;
		}

		if ($formSelect.length && $formSelect.val()) {
			formText = $formSelect.find('option:selected').text();
		}

		if ($gatewaySelect.length && $gatewaySelect.val()) {
			gatewayText = $gatewaySelect.find('option:selected').text();
		}

		if ($statusSelect.length && $statusSelect.val()) {
			statusText = $statusSelect.find('option:selected').text();
		}

		$summary.text('Showing ' + formText + ' payment records with ' + gatewayText + ' and ' + statusText + '.');
	}

	function initWordformPaymentReportsDataTable() {
		const $table = $('#wordformPaymentReportsDataTable');
		if (!$table.length || !$.fn.DataTable) {
			return null;
		}

		if ($.fn.DataTable.isDataTable($table)) {
			return $table.DataTable();
		}

		return $table.DataTable({
			processing: true,
			serverSide: true,
			paging: true,
			searching: true,
			lengthChange: true,
			pageLength: 25,
			lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
			ajax: {
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				data: function(d) {
					d.action = 'sc_wordform_payment_reports_load';
					d.security = wordform_admin_view_page_script_obj.nonce;
					d.payment_report_form_id = $('#WordFormPaymentReportSelectForm').val() || '';
					d.payment_report_gateway = $('#WordFormPaymentReportSelectGateway').val() || '';
					d.payment_report_status = $('#WordFormPaymentReportSelectStatus').val() || '';
				}
			},
			columns: [
				{ data: 'formName' },
				{ data: 'gateway' },
				{ data: 'paymentStatus' },
				{ data: 'amount' },
				{ data: 'coupon' },
				{ data: 'currency' },
				{ data: 'transactionRef' },
				{ data: 'submissionDate' },
				{ data: 'details', orderable: false, searchable: false }
			],
			order: [[7, 'desc']]
		});
	}

	if ($('#wordformPaymentReportsWrapperTable').length > 0) {
		$('#tabs').on('tabsactivate', function(event, ui) {
			if (ui.newPanel && ui.newPanel.attr('id') === 'scWordFormPaymentReports') {
				const table = initWordformPaymentReportsDataTable();
				updateWordformPaymentReportsSummary();
				if (table) {
					table.columns.adjust();
				}
			}
		});

		if ($('#scWordFormPaymentReports').is(':visible')) {
			initWordformPaymentReportsDataTable();
			updateWordformPaymentReportsSummary();
		}

		$('body').on('change', '#WordFormPaymentReportSelectForm, #WordFormPaymentReportSelectGateway, #WordFormPaymentReportSelectStatus', function() {
			const table = initWordformPaymentReportsDataTable();
			updateWordformPaymentReportsSummary();
			if (table) {
				table.ajax.reload();
			}
		});

		$('body').on('click', '#wordformPaymentReportResetFilters', function() {
			$('#WordFormPaymentReportSelectForm').val('');
			$('#WordFormPaymentReportSelectGateway').val('');
			$('#WordFormPaymentReportSelectStatus').val('');
			updateWordformPaymentReportsSummary();

			const table = initWordformPaymentReportsDataTable();
			if (table) {
				table.search('').ajax.reload();
			}
		});
	}

	$('body').on('click', '.wordform-open-connection-send-log-fail-detail-modal', function () {
		let detailRaw = $(this).attr('data-failure-detail') || '';
		let detail = {};
		let modal = $('#WordFormConnectionSendLogFailDetailModal');
		let docsHtml = '';
		let exceptionHtml = '';

		if (!detailRaw || !modal.length) {
			return;
		}

		try {
			detail = JSON.parse(detailRaw);
		} catch (error) {
			console.log(error);
			return;
		}

		if (detail.docsUrl && detail.docsLabel) {
			docsHtml = '<p><strong>Official help:</strong> <a href="' + detail.docsUrl + '" target="_blank" rel="noopener">' + detail.docsLabel + '</a></p>';
		}

		if (detail.exceptionType || detail.exceptionMsg) {
			exceptionHtml = '<div class="wordform-connection-fail-detail-block">';
			if (detail.exceptionType) {
				exceptionHtml += '<p><strong>Exception Type:</strong> ' + detail.exceptionType + '</p>';
			}
			if (detail.exceptionMsg) {
				exceptionHtml += '<p><strong>Exception Message:</strong> ' + detail.exceptionMsg + '</p>';
			}
			exceptionHtml += '</div>';
		}

		modal.html(
			'<div class="wordform-connection-fail-detail-wrapper">' +
				'<p><strong>Form:</strong> ' + (detail.formName || '') + '</p>' +
				'<p><strong>Application:</strong> ' + (detail.applicationName || '') + '</p>' +
				'<p><strong>Reason:</strong> ' + (detail.reason || 'Not available.') + '</p>' +
				'<p><strong>Details:</strong> ' + (detail.comment || 'Not available.') + '</p>' +
				'<p><strong>Suggestion:</strong> ' + (detail.suggestion || 'Please review the app configuration and try again.') + '</p>' +
				docsHtml +
				exceptionHtml +
			'</div>'
		);

		modal.dialog({
			autoOpen: true,
			minHeight: 240,
			minWidth: 520,
			modal: true,
			dialogClass: 'wordform-admin-dialog',
			buttons: {
				Close: function () {
					modal.dialog('close');
				}
			}
		}).dialog('open');
	});

	$('body').on('click', '.wordform-open-connection-send-log-success-detail-modal', function () {
		let detailRaw = $(this).attr('data-success-detail') || '';
		let detail = {};
		let modal = $('#WordFormConnectionSendLogSuccessDetailModal');
		let sendingDate = '';

		if (!detailRaw || !modal.length) {
			return;
		}

		try {
			detail = JSON.parse(detailRaw);
		} catch (error) {
			console.log(error);
			return;
		}

		if (detail.createdAt) {
			sendingDate = '<p><strong>Sending Datetime:</strong> ' + detail.createdAt + '</p>';
		}

		modal.html(
			'<div class="wordform-connection-send-log-success-detail-wrapper">' +
				'<p><strong>Form:</strong> ' + (detail.formName || '') + '</p>' +
				'<p><strong>Application:</strong> ' + (detail.applicationName || '') + '</p>' +
				sendingDate +
				'<div class="wordform-connection-send-log-success-data-block">' + (detail.submissionDataHtml || '<p>No submission data found.</p>') + '</div>' +
			'</div>'
		);

		modal.dialog({
			autoOpen: true,
			minHeight: 280,
			minWidth: 620,
			modal: true,
			dialogClass: 'wordform-admin-dialog wordform-connection-send-log-success-dialog',
			buttons: {
				Close: function () {
					modal.dialog('close');
				}
			}
		}).dialog('open');
	});

	$('body').on('click', '.wordform-open-payment-report-detail-modal', function () {
		let detailRaw = $(this).attr('data-payment-detail') || '';
		let detail = {};
		let modal = $('#WordFormPaymentReportDetailModal');
		let extraMeta = '';

		if (!detailRaw || !modal.length) {
			return;
		}

		try {
			detail = JSON.parse(detailRaw);
		} catch (error) {
			console.log(error);
			return;
		}

		if (detail.gatewaySlug === 'stripe' && detail.paymentMethodId) {
			extraMeta += '<p><strong>Payment Method ID:</strong> <code>' + detail.paymentMethodId + '</code></p>';
		}
		if (detail.gatewaySlug === 'paypal') {
			if (detail.orderId) {
				extraMeta += '<p><strong>Order ID:</strong> <code>' + detail.orderId + '</code></p>';
			}
			if (detail.captureId) {
				extraMeta += '<p><strong>Capture ID:</strong> <code>' + detail.captureId + '</code></p>';
			}
			if (detail.payerId) {
				extraMeta += '<p><strong>Payer ID:</strong> <code>' + detail.payerId + '</code></p>';
			}
		}
		if (detail.gatewaySlug === 'square') {
			if (detail.sourceId) {
				extraMeta += '<p><strong>Source ID:</strong> <code>' + detail.sourceId + '</code></p>';
			}
			if (detail.cardBrand) {
				extraMeta += '<p><strong>Card Brand:</strong> ' + detail.cardBrand + '</p>';
			}
			if (detail.last4) {
				extraMeta += '<p><strong>Last 4:</strong> ' + detail.last4 + '</p>';
			}
			if (detail.receiptUrl) {
				extraMeta += '<p><strong>Receipt URL:</strong> <a href="' + detail.receiptUrl + '" target="_blank" rel="noopener">Open Receipt</a></p>';
			}
		}
		if (detail.gatewaySlug === 'authorizenet') {
			if (detail.responseCode) {
				extraMeta += '<p><strong>Response Code:</strong> <code>' + detail.responseCode + '</code></p>';
			}
			if (detail.authCode) {
				extraMeta += '<p><strong>Auth Code:</strong> <code>' + detail.authCode + '</code></p>';
			}
			if (detail.accountNumber) {
				extraMeta += '<p><strong>Account Number:</strong> ' + detail.accountNumber + '</p>';
			}
			if (detail.accountType) {
				extraMeta += '<p><strong>Account Type:</strong> ' + detail.accountType + '</p>';
			}
		}
		if (detail.couponCode) {
			extraMeta += '<p><strong>Coupon Code:</strong> <code>' + detail.couponCode + '</code></p>';
		}
		if (detail.couponDiscount && detail.couponDiscount !== '0.00') {
			extraMeta += '<p><strong>Coupon Discount:</strong> ' + detail.couponDiscount + '</p>';
		}

		modal.html(
			'<div class="wordform-payment-report-detail-wrapper">' +
				'<p><strong>Form:</strong> ' + (detail.formName || '') + ' <code>' + (detail.formId || '') + '</code></p>' +
				'<p><strong>Gateway:</strong> ' + (detail.gatewayName || '') + '</p>' +
				'<p><strong>Status:</strong> ' + (detail.paymentStatusLabel || '') + (detail.paymentStatusRaw ? ' <code>(' + detail.paymentStatusRaw + ')</code>' : '') + '</p>' +
				'<p><strong>Amount:</strong> ' + (detail.amount || '0.00') + ' ' + (detail.currency || '') + '</p>' +
				'<p><strong>Transaction Ref:</strong> <code>' + (detail.transactionRef || '') + '</code></p>' +
				'<p><strong>Submission Date:</strong> ' + (detail.submissionDateDisplay || '') + '</p>' +
				extraMeta +
				'<div class="wordform-payment-report-submission-data-block">' + (detail.submissionDataHtml || '<p>No submission data found.</p>') + '</div>' +
			'</div>'
		);

		modal.dialog({
			autoOpen: true,
			minHeight: 300,
			minWidth: 640,
			modal: true,
			dialogClass: 'wordform-admin-dialog wordform-payment-report-detail-dialog',
			buttons: {
				Close: function () {
					modal.dialog('close');
				}
			}
		}).dialog('open');
	});

	$('body').on('click', '.wordform-open-submission-detail-modal', function () {
		let detailRaw = $(this).attr('data-submission-detail') || '';
		let detail = {};
		let modal = $('#WordFormSubmissionDetailModal');

		if (!detailRaw || !modal.length) {
			return;
		}

		try {
			detail = JSON.parse(detailRaw);
		} catch (error) {
			console.log(error);
			return;
		}

		modal.html(
			'<div class="wordform-submission-detail-modal-wrapper">' +
				'<p><strong>Form:</strong> ' + (detail.formName || '') + '</p>' +
				'<p><strong>Submitter:</strong> ' + (detail.submitter || '') + '</p>' +
				'<p><strong>Submission Date:</strong> ' + (detail.submissionDate || '') + '</p>' +
				'<div class="wordform-submission-detail-modal-data-block">' + (detail.submissionDataHtml || '<p>No submission data found.</p>') + '</div>' +
			'</div>'
		);

		modal.dialog({
			autoOpen: true,
			minHeight: 300,
			minWidth: 680,
			modal: true,
			dialogClass: 'wordform-admin-dialog wordform-submission-detail-dialog',
			buttons: {
				Close: function () {
					modal.dialog('close');
				}
			}
		}).dialog('open');
	});

	// =================================================================
	//  GENERAL TAB SETTINGS
	// =================================================================

	// ----------------------------------------------------
	// Load selected form’s settings dynamically (Fixed JSON issue)
	// ----------------------------------------------------
	$('body').on('change', '#scWordformSelectGeneralTabFor', function () {
		let formID = $(this).val();
		let updateInfoEle = $('.sc-wordform-general-tab-update-info').html('Loading...');

		$.ajax({
			type: "POST",
			url: wordform_admin_view_page_script_obj.adminajax_url,
			dataType: "json",     // ✅ auto-parse JSON
			cache: false,
			data: {
				action: 'sc_wordform_get_general_tab_data',
				security: wordform_admin_view_page_script_obj.nonce,
				form_id: formID
			},
			success: function (json) {
				if (!json || typeof json !== 'object') {
					updateInfoEle
						.html('Unexpected response from server.')
						.removeClass('text-success')
						.addClass('text-error');
					return;
				}

				if (json.status === 'success' && json.settings) {
					const s = json.settings;

					// Apply loaded settings
					$('.sc-wordform-form-width').val(s.wordform_form_width);
					$('.sc-wordform-form-width-slider')
						.slider('value', s.wordform_form_width)
						.siblings('.slider-value-display')
						.text(s.wordform_form_width + '%');

					[
						{ cls: '.sc-wordform-form-submit-button-background-color', val: s.submit_button_background_color },
						{ cls: '.sc-wordform-form-submit-button-background-hover-color', val: s.submit_button_background_hover_color },
						{ cls: '.sc-wordform-form-submit-button-font-color', val: s.submit_button_font_color }
					].forEach(f => {
						$(f.cls).val(f.val)
							.closest('div.wp-picker-container')
							.find('button[type="button"]').css('background-color', f.val);
					});

					$('.sc-wordform-form-submit-button-text-size').val(s.submit_button_font_size);
					$('.sc-wordform-form-submit-button-padding-top-bottom').val(s.submit_button_padding_top_bottom);
					$('.sc-wordform-form-submit-button-padding-left-right').val(s.submit_button_padding_left_right);
					$('.sc-wordform-form-submission-success-message').val(s.form_submission_success_message || '');
					$('.sc-wordform-submit-button-loading-text').val(s.submit_button_loading_text || '');
					$('.sc-wordform-show-submit-button-spinner').prop('checked', s.show_submit_button_spinner === 'yes');
					$('.sc-wordform-show-submit-progress-text').prop('checked', s.show_submit_progress_text === 'yes');
					$('.sc-wordform-show-success-message-as-card').prop('checked', s.show_success_message_as_card === 'yes');
					$('.sc-wordform-redirect-on-form-submission').prop('checked', s.redirect_on_form_submission === 'yes');
					$('.sc-wordform-redirect-url-on-form-submission').val(s.redirect_url_on_form_submission || '');
					$('.sc-wordform-form-field-gap').val(s.form_field_gap);
					$('.sc-wordform-form-container-padding').val(s.form_container_padding);
					$('.sc-wordform-form-container-border-radius').val(s.form_container_border_radius);

					$('input[name="sc-wordform-form-submit-button-font-weight"]').prop('checked', false)
						.filter('[value="' + s.submit_button_font_weight + '"]').prop('checked', true);

					$('.sc-wordform-form-submission-send-email').prop('checked', s.send_email_on_form_submission === 'yes');
					$('.sc-wordform-form-submission-hide-form').prop('checked', s.hide_form_on_form_submission === 'yes');

					updateInfoEle.html(json.message || 'Settings loaded successfully.').removeClass('text-error').addClass('text-success');
				} else {
					updateInfoEle.html(json.message || 'Failed to load settings.').removeClass('text-success').addClass('text-error');
				}
			},
			error: function (xhr) {
				const raw = (xhr && xhr.responseText) ? xhr.responseText.trim() : '';
				if (raw === '0') {
					updateInfoEle
						.html('Security check failed (nonce). Please refresh the page.')
						.removeClass('text-success')
						.addClass('text-error');
				} else {
					updateInfoEle
						.html('Error loading settings. Check console for details.')
						.removeClass('text-success')
						.addClass('text-error');
					console.debug('Raw response:', raw);
				}
			}
		});
	});

	// ----------------------------------------------------
	// Form Width Slider
	// ----------------------------------------------------
	const formWidth = parseInt($('.sc-wordform-form-width').val()) || 100;
	$('.sc-wordform-form-width-slider').slider({
		range: "min",
		value: formWidth,
		min: 30,
		max: 100,
		step: 1,
		slide: function (event, ui) {
			$('.sc-wordform-form-width').val(ui.value);
			$(this).next('.slider-value-display').text(ui.value + '%');
		}
	}).next('.slider-value-display').text(formWidth + '%');


		// ----------------------------------------------------
		// Reset Button (Dynamic - AJAX Fetch PHP Defaults)
		// ----------------------------------------------------
		$('body')
		.off('click', '.sc-wordform-settings-general-tab-reset')
		.on('click', '.sc-wordform-settings-general-tab-reset', function (event) {
			event.preventDefault();

			const $resetTrigger  = $(this);
			const updateInfoEle  = $('.sc-wordform-general-tab-update-info');
			const selectedFormId = $('#scWordformSelectGeneralTabFor').val();

			function applyGeneralSettingsDefaults() {
			updateInfoEle
				.html('Resetting to defaults...')
				.removeClass('text-success text-error')
				.addClass('text-info');

			$.ajax({
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				dataType: 'json',            // ✅ let jQuery parse JSON
				cache: false,
				data: {
				action:   'sc_wordform_get_general_tab_default_data',
				security: wordform_admin_view_page_script_obj.nonce,
				form_id:  selectedFormId
				},
				success: function (json) {
				// Handle nonce fail or unexpected payloads gracefully
				if (!json || typeof json !== 'object') {
					updateInfoEle
					.html('Unexpected response while fetching defaults.')
					.removeClass('text-info')
					.addClass('text-error');
					return;
				}
				if (json.status !== 'success' || !json.defaults) {
					updateInfoEle
					.html(json.message || 'Could not fetch default settings.')
					.removeClass('text-info')
					.addClass('text-error');
					return;
				}

				const d = json.defaults;

				// --- Apply defaults to fields ---
				$('.sc-wordform-form-width').val(d.wordform_form_width);
				$('.sc-wordform-form-width-slider')
					.slider('value', d.wordform_form_width)
					.siblings('.slider-value-display')
					.text(d.wordform_form_width + '%');

				[
					{ cls: '.sc-wordform-form-submit-button-background-color',       val: d.submit_button_background_color },
					{ cls: '.sc-wordform-form-submit-button-background-hover-color', val: d.submit_button_background_hover_color },
					{ cls: '.sc-wordform-form-submit-button-font-color',             val: d.submit_button_font_color }
				].forEach(f => {
					$(f.cls).val(f.val)
					.closest('div.wp-picker-container')
					.find('button[type="button"]')
					.css('background-color', f.val);
				});

				$('.sc-wordform-form-submit-button-text-size').val(d.submit_button_font_size);
				$('.sc-wordform-form-submit-button-padding-top-bottom').val(d.submit_button_padding_top_bottom);
				$('.sc-wordform-form-submit-button-padding-left-right').val(d.submit_button_padding_left_right);
				$('.sc-wordform-form-submission-success-message').val(d.form_submission_success_message || '');
				$('.sc-wordform-submit-button-loading-text').val(d.submit_button_loading_text || '');
				$('.sc-wordform-show-submit-button-spinner').prop('checked', d.show_submit_button_spinner === 'yes');
				$('.sc-wordform-show-submit-progress-text').prop('checked', d.show_submit_progress_text === 'yes');
				$('.sc-wordform-show-success-message-as-card').prop('checked', d.show_success_message_as_card === 'yes');
				$('.sc-wordform-redirect-on-form-submission').prop('checked', d.redirect_on_form_submission === 'yes');
				$('.sc-wordform-redirect-url-on-form-submission').val(d.redirect_url_on_form_submission || '');
				$('.sc-wordform-form-field-gap').val(d.form_field_gap);
				$('.sc-wordform-form-container-padding').val(d.form_container_padding);
				$('.sc-wordform-form-container-border-radius').val(d.form_container_border_radius);

				$('input[name="sc-wordform-form-submit-button-font-weight"]')
					.prop('checked', false)
					.filter('[value="' + d.submit_button_font_weight + '"]')
					.prop('checked', true);

				$('.sc-wordform-form-submission-send-email').prop('checked', d.send_email_on_form_submission === 'yes');
				$('.sc-wordform-form-submission-hide-form').prop('checked', d.hide_form_on_form_submission === 'yes');

				updateInfoEle
					.html('Defaults applied. Saving...')
					.removeClass('text-info')
					.addClass('text-success');

				// Save these defaults for the selected form
				$('#scWordformSettingsGeneralTabForm').trigger('submit');
				},
				error: function (xhr) {
				// Helpful debugging without breaking UI
				const raw = (xhr && xhr.responseText) ? xhr.responseText.trim() : '';
				if (raw === '0') {
					updateInfoEle
					.html('Security check failed (nonce). Please refresh the page.')
					.removeClass('text-info')
					.addClass('text-error');
				} else {
					updateInfoEle
					.html('Error fetching default settings.')
					.removeClass('text-info')
					.addClass('text-error');
					// console.debug('AJAX error payload:', raw); // uncomment if you need to debug
				}
				}
			});
		}



			const dialogId = 'wordform-settings-general-reset-dialog';
			$('#' + dialogId).remove();
			const $dialogContent = $('<div id="' + dialogId + '" title="Reset General Settings">' +
				'<p>Do you want to set default settings?</p></div>').appendTo('body');

			const triggerOffset = $resetTrigger.offset() || { top: 0, left: 0 };
			const triggerHeight = $resetTrigger.outerHeight() || 0;
			const windowHeight = $(window).height();
			const scrollTop = $(window).scrollTop();
			const estimatedDialogHeight = 160;
			const spaceBelowTrigger = scrollTop + windowHeight - (triggerOffset.top + triggerHeight + estimatedDialogHeight + 20);

			const positionOptions = spaceBelowTrigger >= 0
				? { my: 'center top', at: 'center bottom+20', of: $resetTrigger }
				: { my: 'center bottom', at: 'center top-20', of: $resetTrigger };

			$dialogContent.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				width: 420,
				position: positionOptions,
				appendTo: 'body',
				zIndex: 100000,
				dialogClass: 'wordform-admin-dialog',
				buttons: {
					Reset: function () { applyGeneralSettingsDefaults(); $(this).dialog('close'); },
					Cancel: function () { $(this).dialog('close'); }
				},
				close: function () { $(this).remove(); }
			});
		});

}); // ✅ END of main admin ready()

/* =====================================================================
 * UPLOAD TAB SETTINGS
 * ===================================================================== */
jQuery(document).ready(function ($) {

	// ----------------------------------------------------
	// Upload Tab: Save Form
	// ----------------------------------------------------
	$('#scWordformSettingsUploadTabForm').on('submit', function () {
		let updateInfoEle = $('.sc-wordform-upload-tab-update-info');
		let postData = $(this).serialize();
		let params = { formData: postData };

		updateInfoEle.html('').removeClass('text-success text-error');

		$.ajax({
			type: "POST",
			url: wordform_admin_view_page_script_obj.adminajax_url,
			data: {
				action: 'sc_wordform_settings_upload_tab_form',
				security: wordform_admin_view_page_script_obj.nonce,
				params: params
			},
			success: function (data) {
				let jsonData = JSON.parse(data);
				if (jsonData.status == 'success')
					updateInfoEle.html(jsonData.successMsg).addClass('text-success');
				else if (jsonData.status == 'warning')
					updateInfoEle.html(jsonData.warningMsg).addClass('text-info');
				else if (jsonData.status == 'fail')
					updateInfoEle.html(jsonData.failMsg).addClass('text-error');
			},
			error: function (xhr, status, error) {
				console.log(xhr, status, error);
			}
		});
		return false;
	});

	// ----------------------------------------------------
	// Upload Tab: Initialize Range Sliders
	// ----------------------------------------------------
	const uploadData = wordform_admin_view_page_script_obj.wordform_upload_config_data || {};

	// Max Files
	const maxFiles = parseInt($('.sc-wordform-upload-max-numof-files').val()) || 0;
	$('.sc-wordform-upload-max-numof-files-slider').slider({
		range: "min",
		value: maxFiles,
		min: 1,
		step: 1,
		max: parseInt(uploadData.server_max_num_files_allowed) || 1000,
		slide: function (e, ui) {
			$('.sc-wordform-upload-max-numof-files').val(ui.value);
			$(this).next('.slider-value-display').text(ui.value);
		}
	}).next('.slider-value-display').text(maxFiles);

	// Each File Size
	const eachFileSize = parseInt($('.sc-wordform-upload-each-file-max-size').val()) || 0;
	$('.sc-wordform-upload-each-file-max-size-slider').slider({
		range: "min",
		value: eachFileSize,
		min: 1,
		step: 1,
		max: parseInt(uploadData.server_each_file_max_size_allowed) || 2000,
		slide: function (e, ui) {
			$('.sc-wordform-upload-each-file-max-size').val(ui.value);
			$(this).next('.slider-value-display').text(ui.value + ' MB');
		}
	}).next('.slider-value-display').text(eachFileSize + ' MB');

	// All Files Size
	const allFilesSize = parseInt($('.sc-wordform-upload-all-files-max-size').val()) || 0;
	$('.sc-wordform-upload-all-files-max-size-slider').slider({
		range: "min",
		value: allFilesSize,
		min: 1,
		step: 1,
		max: parseInt(uploadData.server_all_files_max_size_allowed) || 5000,
		slide: function (e, ui) {
			$('.sc-wordform-upload-all-files-max-size').val(ui.value);
			$(this).next('.slider-value-display').text(ui.value + ' MB');
		}
	}).next('.slider-value-display').text(allFilesSize + ' MB');

	// ----------------------------------------------------
	// Upload Tab: Reset (Dialog confirmation)
	// ----------------------------------------------------
	$('body').off('click', '.sc-wordform-settings-upload-tab-reset')
		.on('click', '.sc-wordform-settings-upload-tab-reset', function () {
			const applyUploadSettingsDefaults = () => {
				let defMaxFiles = uploadData.server_max_num_files_allowed;
				let defEachFile = uploadData.server_each_file_max_size_allowed;
				let defAllFiles = uploadData.server_all_files_max_size_allowed;
				let defColor = '#2271b1';
				let defFormWidth = 100;

				$('.sc-wordform-upload-max-numof-files').val(defMaxFiles);
				$('.sc-wordform-upload-max-numof-files-slider').slider('value', defMaxFiles)
					.siblings('.slider-value-display').text(defMaxFiles);
				$('.sc-wordform-upload-each-file-max-size').val(defEachFile);
				$('.sc-wordform-upload-each-file-max-size-slider').slider('value', defEachFile)
					.siblings('.slider-value-display').text(defEachFile + ' MB');
				$('.sc-wordform-upload-all-files-max-size').val(defAllFiles);
				$('.sc-wordform-upload-all-files-max-size-slider').slider('value', defAllFiles)
					.siblings('.slider-value-display').text(defAllFiles + ' MB');
				$('.sc-wordform-form-width').val(defFormWidth);
				$('.sc-wordform-form-width-slider').slider('value', defFormWidth)
					.siblings('.slider-value-display').text(defFormWidth + '%');
				$('.sc-wordform-upload-progress-bar-show-hide').prop('checked', true);
				$('.sc-wordform-upload-progress-bar-color').val(defColor)
					.closest('div.wp-picker-container')
					.find('button[type="button"]').css('background-color', defColor);
				$('#scWordformSettingsUploadTabForm').trigger('submit');
			};

			const $resetTrigger = $(this);
			const dialogId = 'wordform-settings-upload-reset-dialog';
			$('#' + dialogId).remove();

			const $dialogContent = $('<div id="' + dialogId + '" title="Reset Upload Settings">' +
				'<p>Do you want to reset upload settings to default values?</p></div>').appendTo('body');

			const triggerOffset = $resetTrigger.offset();
			const triggerHeight = $resetTrigger.outerHeight();
			const windowHeight = $(window).height();
			const scrollTop = $(window).scrollTop();
			const estimatedDialogHeight = 160;
			const spaceBelowTrigger = scrollTop + windowHeight - (triggerOffset.top + triggerHeight + estimatedDialogHeight + 20);

			const positionOptions = spaceBelowTrigger >= 0
				? { my: 'center top', at: 'center bottom+20', of: $resetTrigger }
				: { my: 'center bottom', at: 'center top-20', of: $resetTrigger };

			$dialogContent.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				width: 420,
				position: positionOptions,
				appendTo: 'body',
				zIndex: 100000,
				dialogClass: 'wordform-admin-dialog',
				buttons: {
					Reset: function () { applyUploadSettingsDefaults(); $(this).dialog('close'); },
					Cancel: function () { $(this).dialog('close'); }
				},
				close: function () { $(this).remove(); }
			});
		});
});

/* =====================================================================
 * PAYMENT TAB SETTINGS
 * ===================================================================== */
jQuery(document).ready(function ($) {

	window.wordformGetStoredPaymentPane = window.wordformGetStoredPaymentPane || function() {
		const storageKey = 'wordform_payment_active_panel_' + window.location.origin + window.location.pathname;
		try {
			return window.sessionStorage.getItem(storageKey) || '';
		} catch (e) {
			return '';
		}
	};

	window.wordformSetStoredPaymentPane = window.wordformSetStoredPaymentPane || function(panelName) {
		const storageKey = 'wordform_payment_active_panel_' + window.location.origin + window.location.pathname;
		try {
			window.sessionStorage.setItem(storageKey, String(panelName || 'general'));
		} catch (e) {}
	};

	function wordformGetPaymentPanelMode(panelName) {
		switch (panelName) {
			case 'stripe':
				return ($('#wordformStripeMode').val() || '').toString();
			case 'paypal':
				return ($('#wordformPaypalMode').val() || '').toString();
			case 'square':
				return ($('#wordformSquareMode').val() || '').toString();
			case 'authorizenet':
				return ($('#wordformAuthorizeNetMode').val() || '').toString();
			default:
				return '';
		}
	}

	function wordformGetPaymentPanelState(panelName) {
		switch (panelName) {
			case 'stripe':
				return {
					panel: 'stripe',
					enabled: $('#wordformStripeEnabled').is(':checked'),
					mode: wordformGetPaymentPanelMode('stripe'),
					requiredTotal: 2,
					requiredComplete: ($.trim($('#wordformStripePublishableKey').val() || '') !== '' ? 1 : 0) + ($.trim($('#wordformStripeSecretKey').val() || '') !== '' ? 1 : 0),
					primaryReady: $.trim($('#wordformStripePublishableKey').val() || '') !== '',
					secondaryReady: $.trim($('#wordformStripeSecretKey').val() || '') !== '',
					optionalReady: $.trim($('#wordformStripeWebhookSecret').val() || '') !== '',
					primarySelector: '#wordformStripePublishableKey',
					secondarySelector: '#wordformStripeSecretKey',
					optionalSelector: '#wordformStripeWebhookSecret'
				};
			case 'paypal':
				return {
					panel: 'paypal',
					enabled: $('#wordformPaypalEnabled').is(':checked'),
					mode: wordformGetPaymentPanelMode('paypal'),
					requiredTotal: 2,
					requiredComplete: ($.trim($('#wordformPaypalClientId').val() || '') !== '' ? 1 : 0) + ($.trim($('#wordformPaypalClientSecret').val() || '') !== '' ? 1 : 0),
					primaryReady: $.trim($('#wordformPaypalClientId').val() || '') !== '',
					secondaryReady: $.trim($('#wordformPaypalClientSecret').val() || '') !== '',
					optionalReady: $.trim($('#wordformPaypalWebhookId').val() || '') !== '',
					primarySelector: '#wordformPaypalClientId',
					secondarySelector: '#wordformPaypalClientSecret',
					optionalSelector: '#wordformPaypalWebhookId'
				};
			case 'square':
				return {
					panel: 'square',
					enabled: $('#wordformSquareEnabled').is(':checked'),
					mode: wordformGetPaymentPanelMode('square'),
					requiredTotal: 3,
					requiredComplete: ($.trim($('#wordformSquareApplicationId').val() || '') !== '' ? 1 : 0) + ($.trim($('#wordformSquareLocationId').val() || '') !== '' ? 1 : 0) + ($.trim($('#wordformSquareAccessToken').val() || '') !== '' ? 1 : 0),
					primaryReady: $.trim($('#wordformSquareApplicationId').val() || '') !== '',
					secondaryReady: $.trim($('#wordformSquareLocationId').val() || '') !== '',
					tertiaryReady: $.trim($('#wordformSquareAccessToken').val() || '') !== '',
					optionalReady: false,
					primarySelector: '#wordformSquareApplicationId',
					secondarySelector: '#wordformSquareLocationId',
					tertiarySelector: '#wordformSquareAccessToken'
				};
			case 'authorizenet':
				return {
					panel: 'authorizenet',
					enabled: $('#wordformAuthorizeNetEnabled').is(':checked'),
					mode: wordformGetPaymentPanelMode('authorizenet'),
					requiredTotal: 3,
					requiredComplete: ($.trim($('#wordformAuthorizeNetApiLoginId').val() || '') !== '' ? 1 : 0) + ($.trim($('#wordformAuthorizeNetClientKey').val() || '') !== '' ? 1 : 0) + ($.trim($('#wordformAuthorizeNetTransactionKey').val() || '') !== '' ? 1 : 0),
					primaryReady: $.trim($('#wordformAuthorizeNetApiLoginId').val() || '') !== '',
					secondaryReady: $.trim($('#wordformAuthorizeNetClientKey').val() || '') !== '',
					tertiaryReady: $.trim($('#wordformAuthorizeNetTransactionKey').val() || '') !== '',
					optionalReady: false,
					primarySelector: '#wordformAuthorizeNetApiLoginId',
					secondarySelector: '#wordformAuthorizeNetClientKey',
					tertiarySelector: '#wordformAuthorizeNetTransactionKey'
				};
			default:
				return {
					panel: panelName,
					enabled: false,
					mode: '',
					requiredTotal: 0,
					requiredComplete: 0
				};
		}
	}

	function wordformIsPaymentPanelReady(panelName) {
		const state = wordformGetPaymentPanelState(panelName);
		return Number(state.requiredComplete || 0) >= Number(state.requiredTotal || 0) && Number(state.requiredTotal || 0) > 0;
	}

	function wordformGetPaymentFirstMissingSelector(panelName) {
		const state = wordformGetPaymentPanelState(panelName);
		if (state.primarySelector && !state.primaryReady) {
			return state.primarySelector;
		}
		if (state.secondarySelector && !state.secondaryReady) {
			return state.secondarySelector;
		}
		if (state.tertiarySelector && !state.tertiaryReady) {
			return state.tertiarySelector;
		}
		if (state.optionalSelector && !state.optionalReady) {
			return state.optionalSelector;
		}
		return '';
	}

	function wordformSetPaymentCheckState($overview, keyName, isComplete) {
		const $item = $overview.find('[data-payment-check="' + keyName + '"]').first();
		if (!$item.length) {
			return;
		}

		const $icon = $item.find('.wordform-payment-check-icon i').first();
		$item.toggleClass('is-done', !!isComplete).toggleClass('is-pending', !isComplete);
		if ($icon.length) {
			$icon.attr('class', isComplete ? 'fa-solid fa-circle-check' : 'fa-regular fa-circle');
		}
	}

	window.wordformUpdatePaymentPaneStatus = window.wordformUpdatePaymentPaneStatus || function(panelName) {
		const $pane = $('.wordform-payment-settings-pane[data-payment-panel-content="' + panelName + '"]').first();
		const $navButton = $('.wordform-payment-settings-nav-button[data-payment-panel="' + panelName + '"]').first();
		if (!$pane.length || !$navButton.length) {
			return;
		}

		const $statusPill = $pane.find('.wordform-payment-gateway-status-pill').first();
		const $navSmall = $navButton.find('.wordform-payment-settings-nav-copy small').first();
		const isLocked = $pane.hasClass('is-locked') || $navButton.hasClass('is-locked');
		if (isLocked) {
			$statusPill.removeClass('is-ready is-pending').addClass('is-pro').text('Pro only');
			$navSmall.text('Pro preview');
			return;
		}

		const state = wordformGetPaymentPanelState(panelName);
		const isReady = wordformIsPaymentPanelReady(panelName);
		const mode = state.mode;
		if ($statusPill.length) {
			$statusPill.removeClass('is-ready is-pending is-pro');
			if (isReady) {
				$statusPill.addClass('is-ready').text('Configured' + (mode ? ' · ' + String(mode).toUpperCase() : ''));
			} else {
				$statusPill.addClass('is-pending').text('Needs setup');
			}
		}
		if ($navSmall.length) {
			$navSmall.text(isReady ? 'Configured' : 'Needs setup');
		}

		const $overview = $pane.find('[data-payment-overview="' + panelName + '"]').first();
		if ($overview.length) {
			const $statusValue = $overview.find('[data-payment-summary-status]').first();
			const $modeValue = $overview.find('[data-payment-summary-mode]').first();
			const $progressValue = $overview.find('[data-payment-summary-progress]').first();
			const $optionalValue = $overview.find('[data-payment-summary-optional]').first();
			const $nextStep = $overview.find('[data-payment-next-step]').first();

			$statusValue.text(isReady ? 'Configured' : 'Needs setup').toggleClass('is-ready', isReady).toggleClass('is-pending', !isReady);
			$modeValue.text(mode ? String(mode).toUpperCase() : 'Not selected');
			$progressValue.text(String(state.requiredComplete || 0) + ' / ' + String(state.requiredTotal || 0));
			$optionalValue.text(state.optionalReady ? 'Added' : 'Optional').toggleClass('is-ready', !!state.optionalReady);

			wordformSetPaymentCheckState($overview, 'enabled', !!state.enabled);
			wordformSetPaymentCheckState($overview, 'primary', !!state.primaryReady);
			wordformSetPaymentCheckState($overview, 'secondary', !!state.secondaryReady);
			wordformSetPaymentCheckState($overview, 'tertiary', !!state.tertiaryReady);
			wordformSetPaymentCheckState($overview, 'optional', !!state.optionalReady);

			if ($nextStep.length) {
				if (!state.enabled) {
					$nextStep.text('Enable this gateway, add the required credentials, then save once.');
				} else if (!isReady) {
					$nextStep.text('Complete the missing required credentials, then save once and run a checkout test.');
				} else if (state.optionalSelector && !state.optionalReady) {
					$nextStep.text('Required setup is complete. You can add the optional webhook value now or after the first successful test.');
				} else if (panelName === 'authorizenet') {
					$nextStep.text('Gateway is configured. Finish the final sandbox checkout test from an HTTPS form URL before using live traffic.');
				} else {
					$nextStep.text('Gateway is configured. Run a complete test checkout before using live traffic.');
				}
			}
		}
	};

	window.wordformRefreshPaymentGatewayStates = window.wordformRefreshPaymentGatewayStates || function() {
		['stripe', 'paypal', 'square', 'authorizenet'].forEach(window.wordformUpdatePaymentPaneStatus);
	};

	$('#scWordformSettingsPaymentTabForm').on('submit', function () {
		let updateInfoEle = $('.sc-wordform-payment-tab-update-info');
		let activePanel = $('.wordform-payment-settings-pane.is-active').first().data('payment-panel-content') || window.wordformGetStoredPaymentPane() || 'general';
		let postData = $(this).serialize();
		let params = { formData: postData };

		updateInfoEle.html('').removeClass('text-success text-error text-info');

		$.ajax({
			type: 'POST',
			url: wordform_admin_view_page_script_obj.adminajax_url,
			dataType: 'json',
			data: {
				action: 'sc_wordform_settings_payment_tab_form',
				security: wordform_admin_view_page_script_obj.nonce,
				params: params
			},
			success: function (json) {
				if (!json || typeof json !== 'object') {
					updateInfoEle.html('Unexpected response from server.').addClass('text-error');
					return;
				}

				if (json.status === 'success') {
					updateInfoEle.html(json.successMsg).addClass('text-success');
					window.wordformRefreshPaymentGatewayStates();
					activateWordformPaymentPane(activePanel);
				} else if (json.status === 'fail') {
					updateInfoEle.html(json.failMsg).addClass('text-error');
					activateWordformPaymentPane(activePanel);
				}
			},
			error: function (xhr, status, error) {
				console.log(xhr, status, error);
				updateInfoEle.html('Payment settings request failed.').addClass('text-error');
				activateWordformPaymentPane(activePanel);
			}
		});

		return false;
	});
});

/* =====================================================================
 * COUPONS TAB SETTINGS
 * ===================================================================== */
jQuery(document).ready(function ($) {

	function initWordformCouponsDataTable() {
		const $table = $('#wordformCouponsTable');
		const $wrapper = $('#wordformCouponsWrapperTable');
		if (!$table.length || !$.fn.DataTable) {
			return null;
		}

		if ($.fn.DataTable.isDataTable($table)) {
			$wrapper.fadeIn(200);
			return $table.DataTable();
		}

		const dataTable = $table.DataTable({
			order: [[0, 'asc']],
			pageLength: 10,
			lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]]
		});

		$wrapper.fadeIn(200);
		return dataTable;
	}

	function resetWordformCouponForm() {
		const $form = $('#scWordformCouponForm');
		if (!$form.length) {
			return;
		}

		$form.get(0).reset();
		$form.find('.wordform-coupon-id').val('0');
		$form.find('.wordform-coupon-code').val('');
		$form.find('.wordform-coupon-discount-type').val('fixed');
		$form.find('.wordform-coupon-discount-value').val('0.00');
		$form.find('.wordform-coupon-status').val('active');
		$form.find('.wordform-coupon-start-date').val('');
		$form.find('.wordform-coupon-expiry-date').val('');
		$form.find('.wordform-coupon-usage-limit').val('0');
		$form.find('.wordform-coupon-minimum-amount').val('0.00');
		$form.find('.wordform-coupon-apply-to-custom-amount').prop('checked', false);
		$form.find('.wordform-coupon-note').val('');
		$form.find('.wordform-coupon-all-forms').prop('checked', true);
		$form.find('.wordform-coupon-apply-to-all-forms-input').val('yes');
		$form.find('.wordform-coupon-allowed-form').prop('checked', false).prop('disabled', true);
		$form.find('.wordform-coupon-form-update-info').html('').removeClass('text-success text-error text-info');
	}

	function syncWordformCouponFormsVisibility() {
		const $form = $('#scWordformCouponForm');
		const allFormsChecked = $form.find('.wordform-coupon-all-forms').is(':checked');
		$form.find('.wordform-coupon-apply-to-all-forms-input').val(allFormsChecked ? 'yes' : 'no');
		$form.find('.wordform-coupon-allowed-form').prop('disabled', allFormsChecked);
		$form.find('.wordform-coupon-forms-list').toggleClass('is-disabled', allFormsChecked);
	}

	function openWordformCouponDialog(mode, couponData) {
		const $dialog = $('#wordformCouponsDialog');
		const $form = $('#scWordformCouponForm');
		if (!$dialog.length || !$form.length) {
			return;
		}

		resetWordformCouponForm();

		if (mode === 'edit' && couponData && typeof couponData === 'object') {
			$dialog.dialog('option', 'title', 'Edit Coupon');
			$form.find('.wordform-coupon-id').val(couponData.id || 0);
			$form.find('.wordform-coupon-code').val(couponData.coupon_code || '');
			$form.find('.wordform-coupon-discount-type').val(couponData.discount_type || 'fixed');
			$form.find('.wordform-coupon-discount-value').val(couponData.discount_value || '0.00');
			$form.find('.wordform-coupon-status').val(couponData.coupon_status || 'active');
			$form.find('.wordform-coupon-start-date').val(couponData.start_date || '');
			$form.find('.wordform-coupon-expiry-date').val(couponData.expiry_date || '');
			$form.find('.wordform-coupon-usage-limit').val(couponData.usage_limit || 0);
			$form.find('.wordform-coupon-minimum-amount').val(couponData.minimum_amount || '0.00');
			$form.find('.wordform-coupon-apply-to-custom-amount').prop('checked', String(couponData.apply_to_custom_amount || 'no') === 'yes');
			$form.find('.wordform-coupon-note').val(couponData.coupon_note || '');

			const allowedForms = Array.isArray(couponData.allowed_forms) ? couponData.allowed_forms : [];
			if (allowedForms.length) {
				$form.find('.wordform-coupon-all-forms').prop('checked', false);
				$form.find('.wordform-coupon-allowed-form').each(function () {
					$(this).prop('checked', allowedForms.indexOf($(this).val()) !== -1);
				});
			}
		} else {
			$dialog.dialog('option', 'title', 'Create Coupon');
		}

		syncWordformCouponFormsVisibility();
		$dialog.dialog('open');
	}

	if ($('#wordformCouponsWrapperTable').length > 0) {
		$('#tabs').on('tabsactivate', function (event, ui) {
			if (ui.newPanel && ui.newPanel.attr('id') === 'scWordFormCoupons') {
				const table = initWordformCouponsDataTable();
				if (table) {
					table.columns.adjust();
				}
			}
		});

		if ($('#scWordFormCoupons').is(':visible')) {
			initWordformCouponsDataTable();
		}

		$('#wordformCouponsDialog').dialog({
			autoOpen: false,
			modal: true,
			resizable: false,
			draggable: false,
			width: 760,
			appendTo: 'body',
			dialogClass: 'wordform-admin-dialog wordform-coupon-admin-dialog',
			buttons: {
				Save: function () {
					$('#scWordformCouponForm').trigger('submit');
				},
				Cancel: function () {
					$(this).dialog('close');
				}
			},
			close: function () {
				resetWordformCouponForm();
			}
		});

		$('body').on('change', '.wordform-coupon-all-forms', function () {
			syncWordformCouponFormsVisibility();
		});

		$('body').on('click', '.sc-wordform-add-coupon', function () {
			openWordformCouponDialog('create', null);
		});

		$('body').on('click', '.sc-wordform-edit-coupon', function () {
			const rawCoupon = $(this).closest('tr').attr('data-coupon') || '{}';
			let couponData = {};
			try {
				couponData = JSON.parse(rawCoupon);
			} catch (error) {
				couponData = {};
			}
			openWordformCouponDialog('edit', couponData);
		});

		$('body').on('submit', '#scWordformCouponForm', function () {
			const $form = $(this);
			const $feedback = $form.find('.wordform-coupon-form-update-info');
			const postData = $form.serialize();

			$feedback.html('').removeClass('text-success text-error text-info');

			$.ajax({
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				dataType: 'json',
				data: {
					action: 'sc_wordform_coupon_save',
					security: wordform_admin_view_page_script_obj.nonce,
					params: { formData: postData }
				},
				success: function (json) {
					if (!json || typeof json !== 'object') {
						$feedback.html('Unexpected response from server.').addClass('text-error');
						return;
					}

					if (json.status === 'success') {
						const dataTable = $.fn.DataTable.isDataTable('#wordformCouponsTable') ? $('#wordformCouponsTable').DataTable() : null;
						if (dataTable) {
							dataTable.destroy();
						}
						$('#wordformCouponsTableBody').html(json.rowsHtml || '');
						initWordformCouponsDataTable();
						$('.sc-wordform-coupons-tab-update-info').html(json.successMsg || '').removeClass('text-error').addClass('text-success');
						$('#wordformCouponsDialog').dialog('close');
					} else {
						$feedback.html(json.failMsg || 'Coupon could not be saved.').addClass('text-error');
					}
				},
				error: function (xhr, status, error) {
					console.log(xhr, status, error);
					$feedback.html('Coupon request failed.').addClass('text-error');
				}
			});

			return false;
		});

		$('body').on('click', '.sc-wordform-delete-coupon', function () {
			const couponId = parseInt($(this).closest('tr').attr('data-coupon-id') || '0', 10);
			if (!couponId) {
				return;
			}

			const $dialogContent = $('<div title="Delete Coupon"><p>Do you want to delete this coupon?</p></div>').appendTo('body');
			$dialogContent.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				width: 420,
				appendTo: 'body',
				dialogClass: 'wordform-admin-dialog',
				buttons: {
					Delete: function () {
						const $modal = $(this);
						$.ajax({
							type: 'POST',
							url: wordform_admin_view_page_script_obj.adminajax_url,
							dataType: 'json',
							data: {
								action: 'sc_wordform_coupon_delete',
								security: wordform_admin_view_page_script_obj.nonce,
								coupon_id: couponId
							},
							success: function (json) {
								if (json && json.status === 'success') {
									const dataTable = $.fn.DataTable.isDataTable('#wordformCouponsTable') ? $('#wordformCouponsTable').DataTable() : null;
									if (dataTable) {
										dataTable.destroy();
									}
									$('#wordformCouponsTableBody').html(json.rowsHtml || '');
									initWordformCouponsDataTable();
									$('.sc-wordform-coupons-tab-update-info').html(json.successMsg || '').removeClass('text-error').addClass('text-success');
								} else {
									$('.sc-wordform-coupons-tab-update-info').html((json && json.failMsg) || 'Coupon could not be deleted.').removeClass('text-success').addClass('text-error');
								}
							},
							error: function (xhr, status, error) {
								console.log(xhr, status, error);
								$('.sc-wordform-coupons-tab-update-info').html('Coupon delete request failed.').removeClass('text-success').addClass('text-error');
							},
							complete: function () {
								$modal.dialog('close');
							}
						});
					},
					Cancel: function () {
						$(this).dialog('close');
					}
				},
				close: function () {
					$(this).remove();
				}
			});
		});
	}
});

/* =====================================================================
 * BUILDER ELEMENTS: RANGE + DATE
 * ===================================================================== */
jQuery(document).ready(function ($) {

	// ----------------------------------------------------
	// Range Input: Update dropped field values live
	// ----------------------------------------------------
	$('body').on('change', '.wordform-options-range-settings-values-ul-wrapper input', function () {
		let changedElementClass = $(this).prop('class').split('-')[2];
		let changedValue = $(this).val();
		let sanitizedValue = !isNaN(parseFloat(changedValue)) ? parseFloat(changedValue) : 0;
		let droppedRangeElement = $('.wordform-dropped-range-name');

		switch (changedElementClass) {
			case 'min': droppedRangeElement.prop('min', sanitizedValue); break;
			case 'max': droppedRangeElement.prop('max', sanitizedValue); break;
			case 'default': droppedRangeElement.attr('value', sanitizedValue); break;
			case 'step': droppedRangeElement.prop('step', sanitizedValue); break;
		}
	});

	// ----------------------------------------------------
	// Date Input: Initialize Datepicker & Update Format
	// ----------------------------------------------------
	$('body').on("focus", ".wordform-date-default-value", function () {
		if (!$(this).hasClass("hasDatepicker")) {
			$(this).datepicker({
				dateFormat: "yy-mm-dd",
				onSelect: () => {
					let elementIndex = $(this).closest('.wordform-date-field-options-wrapper').prop("id").split("-")[1];
					let droppedWrapperId = '#wordformElement-' + elementIndex;
					let optionsWrapperId = '#wordformElementOptions-' + elementIndex;
					let selectedDate = $(this).datepicker("getDate");
					if (selectedDate) {
						let rawDate = $.datepicker.formatDate("yy-mm-dd", selectedDate);
						$(optionsWrapperId).find(".wordform-date-default-value").attr("value", rawDate);
					}
					updateDroppedDate(droppedWrapperId, optionsWrapperId);
				}
			});
		}
		$(this).datepicker("refresh");
	});

	function updateDroppedDate(droppedWrapperId, optionsWrapperId) {
		let $optionsWrapper = $(optionsWrapperId);
		let $droppedInput = $(droppedWrapperId).find(".wordform-dropped-date-name");
		let rawDate = $optionsWrapper.find(".wordform-date-default-value").val();
		let displayFormat = $optionsWrapper.find(".wordform-default-date-display-format").val() || "yy-mm-dd";

		if (rawDate && /^\d{4}-\d{2}-\d{2}$/.test(rawDate)) {
			let parts = rawDate.split("-");
			let dateObj = new Date(parts[0], parts[1] - 1, parts[2]);
			let formatted = $.datepicker.formatDate(displayFormat, dateObj);
			$droppedInput.attr("value", formatted);
		} else {
			$droppedInput.attr("value", "");
			$optionsWrapper.find(".wordform-date-default-value").attr("value", "");
		}
	}

	// ----------------------------------------------------
	// Date Format Dropdown Change
	// ----------------------------------------------------
	$('body').on('change', 'select.wordform-default-date-display-format', function () {
		let $select = $(this);
		$select.find('option').attr('selected', false);
		$select.find('option:selected').attr('selected', true);
		let elementIndex = $select.closest('.wordform-date-field-options-wrapper').prop("id").split("-")[1];
		let droppedWrapperId = '#wordformElement-' + elementIndex;
		let optionsWrapperId = '#wordformElementOptions-' + elementIndex;
		updateDroppedDate(droppedWrapperId, optionsWrapperId);
	});

	// ----------------------------------------------------
	// Connect Page Accordion (Google / Zapier)
	// ----------------------------------------------------
	$("#google-oauth-help, #zapier-webhook-create-help, #custom-webhook-create-help, #slack-webhook-create-help, #mailchimp-api-create-help, #airtable-api-create-help, #brevo-api-create-help, #hubspot-api-create-help, #make-webhook-create-help, #activecampaign-api-create-help, #salesforce-api-create-help, #zohocrm-api-create-help").accordion({
		collapsible: true,
		active: false,
		heightStyle: "content"
	});


	// ✅ Add tabs persistence logic directly here - Settings Tabs - Keep open on reload of page the selected Tab
		const $tabsWrapper = $('#tabs');
		const hash = window.location.hash;
		let activeTab = 0;

		$(document).on('click', '.wordform-pro-locked-button', function(event) {
			const upgradeUrl = ($(this).data('upgrade-url') || $(this).attr('href') || '').toString();
			if (!upgradeUrl.length) {
				return;
			}

			event.preventDefault();
			window.open(upgradeUrl, '_blank', 'noopener');
		});

		if (hash && $tabsWrapper.find(`a[href="${hash}"]`).length) {
			activeTab = $tabsWrapper.find('a[href="' + hash + '"]').parent().index();
		}

	$tabsWrapper.show().tabs({
		active: activeTab,
		activate: function(event, ui) {
			const newHash = ui.newPanel.attr('id');
			if (newHash) {
				history.replaceState(null, null, '#' + newHash);
			}
		}
	});

	function activateWordformPaymentPane(panelName) {
		const normalizedPanel = String(panelName || '').trim();
		if (!normalizedPanel.length) {
			return;
		}

		const $navButtons = $('.wordform-payment-settings-nav-button');
		const $panes = $('.wordform-payment-settings-pane');
		const $targetButton = $navButtons.filter('[data-payment-panel="' + normalizedPanel + '"]').first();
		const $targetPane = $panes.filter('[data-payment-panel-content="' + normalizedPanel + '"]').first();

		if (!$targetButton.length || !$targetPane.length) {
			return;
		}

		$navButtons.removeClass('is-active');
		$panes.removeClass('is-active').attr('hidden', true);

		$targetButton.addClass('is-active');
		$targetPane.addClass('is-active').removeAttr('hidden');
		window.wordformSetStoredPaymentPane(normalizedPanel);
	}

	$(document).on('click', '.wordform-payment-settings-nav-button', function(event) {
		const panelName = ($(this).data('payment-panel') || '').toString();
		if (!panelName.length) {
			return;
		}

		event.preventDefault();
		activateWordformPaymentPane(panelName);
	});

	$(document).on('input change', '#scWordformSettingsPaymentTabForm input, #scWordformSettingsPaymentTabForm select', function() {
		window.wordformRefreshPaymentGatewayStates();
	});

	$(document).on('click', '.wordform-payment-connect-trigger', function(event) {
		const triggerButton = this;
		const panelName = ($(this).data('payment-panel') || '').toString();
		const focusTarget = wordformGetPaymentFirstMissingSelector(panelName) || ($(this).data('focus-target') || '').toString();

		if (panelName.length) {
			event.preventDefault();
			activateWordformPaymentPane(panelName);
		}

		if (focusTarget.length) {
			window.setTimeout(function() {
				if (triggerButton && typeof triggerButton.blur === 'function') {
					triggerButton.blur();
				}
				const $target = $(focusTarget).first();
				if ($target.length) {
					const targetNode = $target.get(0);
					if (targetNode && typeof targetNode.scrollIntoView === 'function') {
						targetNode.scrollIntoView({ behavior: 'smooth', block: 'center' });
					}
					if (targetNode && typeof targetNode.focus === 'function') {
						targetNode.focus({ preventScroll: true });
					}
					$target.trigger('focus');
				}
			}, 120);
		}
	});

	const initialStoredPaymentPane = window.wordformGetStoredPaymentPane();
	const $initialActivePaymentPane = initialStoredPaymentPane || $('.wordform-payment-settings-nav-button.is-active').first().data('payment-panel');
	if ($initialActivePaymentPane) {
		activateWordformPaymentPane($initialActivePaymentPane);
	}
	window.wordformRefreshPaymentGatewayStates();

}); // ✅ END OF FINAL DOCUMENT READY
