jQuery(window).on('elementor:init', function () {
	elementor.hooks.addAction('panel/open_editor/widget', function (panel) {
		tp_waitForFormControls(panel);
	});
});

function tp_waitForFormControls(panel) {
	const $formSelect = panel.$el.find('select[data-setting="select_form"]');
	const $columnSelect = panel.$el.find('select[data-setting="form_columns"]');

	if (!$formSelect.length || !$columnSelect.length) {
		return setTimeout(() => tp_waitForFormControls(panel), 100);
	}
	tp_initTPFormDropdownWatcher(panel, $formSelect, $columnSelect);
}

function tp_initTPFormDropdownWatcher(panel, $formSelect, $columnSelect) {
	const $ = jQuery;

	function tp_initSelect2() {
		if (!$columnSelect.hasClass("select2-hidden-accessible")) {
			$columnSelect.select2({
				placeholder: 'Select form fields',
				allowClear: true,
				width: '100%'
			});
		}
	}

	function tp_destroySelect2() {
		if ($columnSelect.hasClass("select2-hidden-accessible")) {
			$columnSelect.select2('destroy');
		}
	}

	function tp_loadFormFields(formId, selected = []) {
		if (!formId) return;

		$columnSelect.prop('disabled', true);

		jQuery.ajax({
			type: "POST",
			url: PlusEditor_localize.ajax,
			dataType: "json",
			data: {
				action: "tp_get_form_fields",
				nonce: PlusEditor_localize.form_table,
				form_id: formId,
			},
			success: function (res) {
				if (res.success && res.message) {
					tp_destroySelect2();
					$columnSelect.empty();

					$columnSelect.append($('<option>', {
						value: '__index__',
						text: 'Index'
					}));

					$.each(res.message, function (key, label) {
						$columnSelect.append($('<option>', {
							value: key,
							text: label
						}));
					});

					tp_initSelect2();

					if (typeof selected === 'string') {
						selected = [selected];
					}

					if (selected.length) {
						$columnSelect.val(selected).trigger('change.select2');
					}
				}
			},
			error: function (err) {
				console.error("AJAX error:", err);
			},
			complete: function () {
				$columnSelect.prop('disabled', false);
			}
		});
	}

	$formSelect.off('change.tpform').on('change.tpform', function () {
		const formId = jQuery(this).val();
		tp_loadFormFields(formId);
	});

	$columnSelect.off('select2:open.tpform').on('select2:open.tpform', function () {
		if (!$columnSelect.children().length) {
			const formId = $formSelect.val();
			tp_loadFormFields(formId);
		}
	});

	const savedFormId = $formSelect.val();
	let savedColumns = [];

	const settings = panel?.model?.get('settings');
	if (settings) {
		let raw = settings.get('form_columns');
		if (raw) {
			savedColumns = typeof raw === 'string' ? [raw] : raw;
		}
	}

	if (savedFormId && !$columnSelect.children().length) {
		tp_loadFormFields(savedFormId, savedColumns);
	} else {
		tp_initSelect2();
	}
}