(function ($) {
	const API_TYPE_ZASLAT = 'zaslat';
	const CARRIER_MODES = {
		BALIKOVNA: ['P2P'],
		ZASILKOVNA: ['P2P'],
		GLS: ['H2H', 'H2P', 'P2P', 'P2H'],
		DPD: ['H2H', 'H2P', 'P2P', 'P2H'],
		PPL: ['H2H', 'H2P', 'P2P', 'P2H'],
		ONE: ['H2H', 'H2P'],
		TOPTRANS: ['H2H'],
		UPS: ['H2H'],
		FEDEX: ['H2H']
	};
	const CARRIER_TO_SUPPLIER = {
		BALIKOVNA: 'BALIKOVNA',
		ZASILKOVNA: 'PACKETA',
		DPD: 'ZASLAT_DPD',
		GLS: 'ZASLAT_GLS',
		PPL: 'PPL',
		ONE: 'ONE'
	};
	const PICKUP_SETTING_SUFFIX = '_alsendo_connect_pickup_branch';
	const LINKED_METHOD_SUFFIX = '_alsendo_connect_linked_api_shipping_method';
	const DISPLAY_MAP_SUFFIX = '_display_apaczka_map';
	const SUPPLIER_MAP_SUFFIX = '_supplier_apaczka_map';
	const ONLY_COD_MAP_SUFFIX = '_only_cod_apaczka_map';

	function isZaslatApi() {
		return alsendo_shipping_settings && API_TYPE_ZASLAT === alsendo_shipping_settings.api_type;
	}

	function getInputBySuffix(suffix) {
		return document.querySelector('[id$="' + suffix + '"]');
	}

	function getSettingRowBySuffix(suffix) {
		const input = getInputBySuffix(suffix);
		if (!input) {
			return null;
		}

		// Shipping settings can be rendered in table rows or Woo modal form blocks.
		const explicitContainer = input.closest('tr, .form-field, p');
		if (explicitContainer) {
			return explicitContainer;
		}

		return input.parentElement ? input.parentElement : null;
	}

	function toggleRow(row, shouldShow) {
		if (!row) {
			return;
		}
		row.style.display = shouldShow ? '' : 'none';
	}

	function restoreSupplierOptions(supplierSelect) {
		if (!supplierSelect || !supplierSelect.dataset.originalOptions) {
			return;
		}
		supplierSelect.innerHTML = supplierSelect.dataset.originalOptions;
	}

	function forceSupplierToCarrier(supplierSelect, carrierCode) {
		if (!supplierSelect || !carrierCode) {
			return;
		}
		const supplierValue = CARRIER_TO_SUPPLIER[carrierCode];
		if (!supplierValue) {
			return;
		}
		if (!supplierSelect.dataset.originalOptions) {
			supplierSelect.dataset.originalOptions = supplierSelect.innerHTML;
		}
		let foundLabel = supplierValue;
		const options = supplierSelect.querySelectorAll('option');
		options.forEach(
			function (option) {
				if (option.value === supplierValue) {
					foundLabel = option.textContent;
				}
			}
		);
		supplierSelect.innerHTML = '<option value="' + supplierValue + '">' + foundLabel + '</option>';
		supplierSelect.value = supplierValue;
	}

	function applyZaslatBranchRules(selectedCarrier) {
		const pickupInput = getInputBySuffix(PICKUP_SETTING_SUFFIX);
		const deliveryInput = getInputBySuffix(DISPLAY_MAP_SUFFIX);
		const pickupRow = getSettingRowBySuffix(PICKUP_SETTING_SUFFIX);
		const displayMapRow = getSettingRowBySuffix(DISPLAY_MAP_SUFFIX);
		const supplierMapRow = getSettingRowBySuffix(SUPPLIER_MAP_SUFFIX);
		const onlyCodMapRow = getSettingRowBySuffix(ONLY_COD_MAP_SUFFIX);
		const supplierMapInput = getInputBySuffix(SUPPLIER_MAP_SUFFIX);

		// If no linked carrier is selected ("None"), keep all settings visible.
		if (!selectedCarrier) {
			toggleRow(pickupRow, true);
			toggleRow(displayMapRow, true);
			toggleRow(supplierMapRow, true);
			toggleRow(onlyCodMapRow, true);
			if (pickupInput) {
				pickupInput.disabled = false;
			}
			if (deliveryInput) {
				deliveryInput.disabled = false;
			}
			restoreSupplierOptions(supplierMapInput);
			return;
		}

		const modes = CARRIER_MODES[selectedCarrier] || [];
		const hasPickupBranch = modes.includes('P2P') || modes.includes('P2H');
		const hasDeliveryBranch = modes.includes('P2P') || modes.includes('H2P');
		const isOnlyP2P = 1 === modes.length && modes.includes('P2P');

		if (pickupInput) {
			toggleRow(pickupRow, hasPickupBranch);
			if (!hasPickupBranch) {
				pickupInput.checked = false;
			}
			pickupInput.disabled = false;
		}
		if (deliveryInput) {
			toggleRow(displayMapRow, hasDeliveryBranch);
			if (!hasDeliveryBranch) {
				deliveryInput.checked = false;
			}
			deliveryInput.disabled = false;
		}

		if (isOnlyP2P) {
			if (pickupInput) {
				pickupInput.checked = true;
				pickupInput.disabled = true;
			}
			if (deliveryInput) {
				deliveryInput.checked = true;
				deliveryInput.disabled = true;
			}
		}

		const shouldShowMapSettings = hasDeliveryBranch && (deliveryInput ? deliveryInput.checked : false);
		toggleRow(supplierMapRow, shouldShowMapSettings);
		toggleRow(onlyCodMapRow, shouldShowMapSettings);

		if (shouldShowMapSettings && selectedCarrier) {
			forceSupplierToCarrier(supplierMapInput, selectedCarrier);
		} else {
			restoreSupplierOptions(supplierMapInput);
		}
	}

	function initZaslatMode() {
		if (!isZaslatApi()) {
			return;
		}

		const linkedMethodInput = getInputBySuffix(LINKED_METHOD_SUFFIX);
		const selectedCarrier = linkedMethodInput ? linkedMethodInput.value : '';
		if (linkedMethodInput) {
			applyZaslatBranchRules(selectedCarrier);
		}
	}

	document.addEventListener(
		'change',
		function (e) {
			e = e || window.event;
			const target = e.target;
			if (!target || !target.hasAttribute('id')) {
				return;
			}

			if (target.id.endsWith(LINKED_METHOD_SUFFIX)) {
				if (isZaslatApi()) {
					applyZaslatBranchRules(target.value);
					return;
				}

				// Get selected option value.
				let select_val = parseInt(target.value, 10);
				// Remove existing notices.
				let existingNotices = document.querySelectorAll('#alsendo-warehouse-add-notice');
				existingNotices.forEach(
					function (elem) {
						elem.remove();
					}
				);

				if (select_val === 90 || select_val === 310 || select_val === 311 || select_val === 316 || select_val === 317) {
					let warehouseMessages = {
						310: {
							content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
								'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Crossborder Logistic</div>' +
								'<div style="color:#4b5563;">Generała Józefa Sowińskiego 42A</div>' +
								'<div style="color:#4b5563;">PL 65-419 Zielona Góra</div>' +
								'</div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;">' +
								'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
								'<div style="color:#4b5563;">📧 Email: <a href="mailto:ops@cblog.pl" style="color:#ef4444;text-decoration:none;">ops@cblog.pl</a></div>' +
								'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48223803070" style="color:#ef4444;text-decoration:none;">22 380 30 70</a></div>' +
								'</div>'
						},
						311: {
							content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
								'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Crossborder Logistic</div>' +
								'<div style="color:#4b5563;">Generała Józefa Sowińskiego 42A</div>' +
								'<div style="color:#4b5563;">PL 65-419 Zielona Góra</div>' +
								'</div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;">' +
								'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
								'<div style="color:#4b5563;">📧 Email: <a href="mailto:ops@cblog.pl" style="color:#ef4444;text-decoration:none;">ops@cblog.pl</a></div>' +
								'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48223803070" style="color:#ef4444;text-decoration:none;">22 380 30 70</a></div>' +
								'</div>'
						},
						316: {
							content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
								'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Packeta</div>' +
								'<div style="color:#4b5563;">Księdza Józefa Londzina 106</div>' +
								'<div style="color:#4b5563;">43-382 Bielsko-Biała</div>' +
								'</div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;">' +
								'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
								'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48334457020" style="color:#ef4444;text-decoration:none;">+48 334 457 020</a></div>' +
								'<div style="color:#4b5563;">📧 Email: <a href="mailto:sales@packeta.pl" style="color:#ef4444;text-decoration:none;">sales@packeta.pl</a></div>' +
								'</div>'
						},
						317: {
							content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
								'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Packeta</div>' +
								'<div style="color:#4b5563;">Księdza Józefa Londzina 106</div>' +
								'<div style="color:#4b5563;">43-382 Bielsko-Biała</div>' +
								'</div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;">' +
								'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
								'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48334457020" style="color:#ef4444;text-decoration:none;">+48 334 457 020</a></div>' +
								'<div style="color:#4b5563;">📧 Email: <a href="mailto:sales@packeta.pl" style="color:#ef4444;text-decoration:none;">sales@packeta.pl</a></div>' +
								'</div>'
						},
						90: {
							content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
								'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Log4World</div>' +
								'<div style="color:#4b5563;">ul. Kępska 124</div>' +
								'<div style="color:#4b5563;">45-129 Opole</div>' +
								'</div>' +
								'<div style="background:#fff;padding:15px;border-radius:4px;">' +
								'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
								'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48790715402" style="color:#ef4444;text-decoration:none;">+48 790 715 402</a></div>' +
								'<div style="color:#4b5563;">📧 Email: <a href="mailto:alsendo@log4world.com" style="color:#ef4444;text-decoration:none;">alsendo@log4world.com</a></div>' +
								'</div>'
						}
					};

					let warehouse_notice = $('<div></div>')
						.attr('id', 'alsendo-warehouse-add-notice')
						.css({
							'padding': '20px 25px',
							'margin-bottom': '20px',
							'background-color': '#fef2f2',
							'border': '1px solid #fecaca',
							'border-left': '4px solid #ef4444',
							'border-radius': '6px',
							'color': '#991b1b',
							'font-size': '14px',
							'position': 'relative',
							'line-height': '1.6'
						})
						.html('⚠️ ' + warehouseMessages[select_val].content +
							'<span style="position:absolute;right:15px;top:15px;cursor:pointer;font-size:20px;font-weight:bold;color:#991b1b;" class="alsendo-warehouse-close-notice" title="Zamknij">&times;</span>');

					$(warehouse_notice).insertAfter(target);
				}
			}

			if (isZaslatApi() && target.id.endsWith(DISPLAY_MAP_SUFFIX)) {
				const linkedMethodInput = getInputBySuffix(LINKED_METHOD_SUFFIX);
				const selectedCarrier = linkedMethodInput ? linkedMethodInput.value : '';
				const supplierMapRow = getSettingRowBySuffix(SUPPLIER_MAP_SUFFIX);
				const onlyCodMapRow = getSettingRowBySuffix(ONLY_COD_MAP_SUFFIX);
				const supplierMapInput = getInputBySuffix(SUPPLIER_MAP_SUFFIX);
				const modes = CARRIER_MODES[selectedCarrier] || [];
				const hasDeliveryBranch = modes.includes('P2P') || modes.includes('H2P');
				const shouldShowMapSettings = hasDeliveryBranch && target.checked;

				toggleRow(supplierMapRow, shouldShowMapSettings);
				toggleRow(onlyCodMapRow, shouldShowMapSettings);

				if (shouldShowMapSettings && selectedCarrier) {
					forceSupplierToCarrier(supplierMapInput, selectedCarrier);
				} else {
					restoreSupplierOptions(supplierMapInput);
					if (supplierMapInput) {
						supplierMapInput.value = '';
					}
				}
			}
		}
	);

	document.addEventListener(
		'DOMContentLoaded',
		function () {
			initZaslatMode();
			// Woo shipping method modal is often rendered after page load.
			setTimeout(initZaslatMode, 200);
			setTimeout(initZaslatMode, 800);
		}
	);

	$(document.body).on(
		'wc_backbone_modal_loaded',
		function () {
			initZaslatMode();
			setTimeout(initZaslatMode, 150);
		}
	);

	// Add click event for close button
	document.addEventListener(
		'click',
		function (e) {
			if (e.target && e.target.classList.contains( 'alsendo-warehouse-close-notice' )) {
				var notice = document.getElementById( 'alsendo-warehouse-add-notice' );
				if (notice) {
					notice.remove();
				}
			}
		}
	);

})( jQuery );