/**
 * Discount Rules Box – Admin Live Preview & Builder Engine.
 */
(function ($) {
	'use strict';

	// Escapuje HTML-specijalne karaktere pre umetanja bilo kog
	// server-vraćenog ili korisnički unetog stringa u HTML string (npr.
	// naziv proizvoda u restriction picker-u) — bez ovoga, naziv proizvoda
	// koji sadrži "<script>"/"onerror=" bi se izvršio u browseru admina
	// koji pretražuje proizvode.
	function escapeHtml(str) {
		return String(str == null ? '' : str)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#39;');
	}

	$(document).ready(function () {
		/* ==========================================================================
		   1. TAB NAVIGACIJA (Uvek aktivna)
		   ========================================================================== */
		$(document).on('click', '.drbu-tab-btn', function (e) {
			e.preventDefault();
			var tabId = $(this).data('tab');

			$('.drbu-tab-btn').removeClass('active');
			$(this).addClass('active');

			$('.drbu-tab-panel').removeClass('active');
			$('#drbu-tab-' + tabId).addClass('active');
		});

		// Prečica "See the Upgrade tab →" linkovi (License/Account tab) — samo
		// simuliraju klik na stvarno Upgrade tab dugme u nav-u.
		$(document).on('click', '.drbu-goto-upgrade-tab', function (e) {
			e.preventDefault();
			$('.drbu-tab-btn[data-tab="upgrade"]').trigger('click');
			$('html, body').animate({ scrollTop: $('.drbu-tabs-nav').offset().top - 40 }, 300);
		});

		// Inicijalizacija tabele analitike (pretraga, paginacija 30 po strani, sortiranje)
		initAnalyticsOrdersTable();

		var $form = $('#drbu-settings-form');
		var $previewContainer = $('#drbu-live-preview-box');
		if (!$form.length) {
			return;
		}

		// State za trenutno selektovani paket u preview-u (1, 2 ili 3).
		var selectedTierIndex = 2; // Po default-u tier 2

		/* ==========================================================================
		   2. INTERAKTIVNOST RADIO GURMADI & TOGGLE SKRIVANJA
		   ========================================================================== */
		// Radio dugmad za broj nivoa (2 ili 3)
		$('input[name="drbu_options[drbu_tier_count]"]').on('change', function () {
			var val = parseInt($(this).val(), 10) || 3;
			$('#drbu-tier-count-selector label').removeClass('selected');
			$(this).closest('label').addClass('selected');

			if (val === 2) {
				$('.drbu-tier-row-3').hide();
			} else {
				$('.drbu-tier-row-3').show();
			}

			updatePreview();
		});

		// Color picker ažuriranje hex teksta
		$('.drbu-color-picker').on('input change', function () {
			var val = $(this).val().toUpperCase();
			$(this).siblings('.drbu-color-val').text(val);
			updatePreview();
		});

		// Subfield toggles
		$('input[name="drbu_options[drbu_enable_free_shipping]"]').on('change', function () {
			if ($(this).is(':checked')) {
				$('#drbu-subfield-free-ship-threshold').slideDown(150);
			} else {
				$('#drbu-subfield-free-ship-threshold').slideUp(150);
			}
			updatePreview();
		});

		$('input[name="drbu_options[drbu_enable_best_value]"]').on('change', function () {
			if ($(this).is(':checked')) {
				$('#drbu-subfield-best-value-index').slideDown(150);
			} else {
				$('#drbu-subfield-best-value-index').slideUp(150);
			}
			updatePreview();
		});

		// Automatsko ažuriranje "Package Name" polja kada se promeni Quantity (pcs)
		$form.on('input change keyup', '.drbu-tier-input-qty', function () {
			var $row = $(this).closest('.drbu-tier-row');
			var $labelInput = $row.find('.drbu-tier-input-label');
			var qty = parseInt($(this).val(), 10);
			if (isNaN(qty) || qty < 1) return;

			var currentLabel = $labelInput.val().trim();

			if (currentLabel === '' || /^\d+\s*(pieces?|piece|pakovanje|pakovanja|komad|komada|pcs|pack|packs)?$/i.test(currentLabel)) {
				var suffix = (qty === 1) ? 'piece' : 'pieces';
				if (/pakovanje|pakovanja/i.test(currentLabel)) {
					suffix = (qty === 1) ? 'pakovanje' : 'pakovanja';
				} else if (/komad|komada/i.test(currentLabel)) {
					suffix = (qty === 1) ? 'komad' : 'komada';
				}
				$labelInput.val(qty + ' ' + suffix);
			} else if (/^\d+/.test(currentLabel)) {
				var updatedLabel = currentLabel.replace(/^\d+/, qty);
				$labelInput.val(updatedLabel);
			}

			updatePreview();
		});

		// Slušanje izmena na svim ostalim poljima forme
		$form.on('input change keyup', 'input, select, textarea', function () {
			updatePreview();
		});

		$('#drbu-test-price').on('input change keyup', function () {
			updatePreview();
		});

		// Sync color picker swatch and HEX text input
		$(document).on('input change', '.drbu-color-picker-swatch', function () {
			var hexVal = $(this).val().toUpperCase();
			var targetSelector = $(this).data('target');
			if (targetSelector) {
				$(targetSelector).val(hexVal).trigger('change');
			}
		});

		$(document).on('input keyup change', '.drbu-hex-input', function () {
			var val = $.trim($(this).val());
			if (val.length > 0 && val.indexOf('#') !== 0) {
				val = '#' + val;
				$(this).val(val);
			}
			val = val.toUpperCase();
			if (/^#[0-9A-F]{6}$/.test(val)) {
				$(this).siblings('.drbu-color-picker-swatch').val(val);
			}
		});

		// Bidirectional sync between Tab 1 table and Tab 4 Texts card for Tier Title & Note
		$(document).on('input keyup change', '.drbu-tier-sync-input', function () {
			var tierIndex = $(this).data('tier');
			var fieldType = $(this).data('field');
			var val = $(this).val();

			var $targetInput = $('.drbu-tier-row-' + tierIndex).find('.drbu-tier-input-' + fieldType);
			if ($targetInput.length) {
				$targetInput.val(val);
				updatePreview();
			}
		});

		$(document).on('input keyup change', '.drbu-tier-input-label, .drbu-tier-input-note', function () {
			var $row = $(this).closest('.drbu-tier-row');
			var tierIndex = $row.data('tier-index');
			var isLabel = $(this).hasClass('drbu-tier-input-label');
			var fieldType = isLabel ? 'label' : 'note';
			var val = $(this).val();

			$('.drbu-tier-sync-input[data-tier="' + tierIndex + '"][data-field="' + fieldType + '"]').val(val);
		});

		/* ==========================================================================
		   3. STYLE PRESETS (QUICK THEMES)
		   ========================================================================== */
		$('.drbu-preset-card').on('click', function (e) {
			e.preventDefault();
			var primary = $(this).data('primary');
			var ctaText = $(this).data('cta');
			var bestVal = $(this).data('best');
			var cardBg = $(this).data('card');
			var btnRadius = $(this).data('btn-radius');
			var cardRadius = $(this).data('card-radius');

			$('input[name="drbu_options[drbu_primary_color]"]').val(primary).trigger('change');
			$('input[name="drbu_options[drbu_cta_text_color]"]').val(ctaText).trigger('change');
			$('input[name="drbu_options[drbu_best_value_color]"]').val(bestVal).trigger('change');
			$('input[name="drbu_options[drbu_card_bg_color]"]').val(cardBg).trigger('change');

			if (btnRadius) {
				$('#drbu_button_radius').val(btnRadius).trigger('change');
			}
			if (cardRadius) {
				$('#drbu_card_radius').val(cardRadius).trigger('change');
			}

			// Visual selection indicator
			$('.drbu-preset-card').removeClass('selected');
			$(this).addClass('selected');

			updatePreview();
		});

		/* ==========================================================================
		   4. DESKTOP / MOBILE VIEWPORT TOGGLE
		   ========================================================================== */
		$('.drbu-view-toggle button').on('click', function () {
			var view = $(this).data('view');
			$('.drbu-view-toggle button').removeClass('active');
			$(this).addClass('active');

			if (view === 'mobile') {
				$('#drbu-preview-viewport').addClass('mobile-view');
			} else {
				$('#drbu-preview-viewport').removeClass('mobile-view');
			}
		});

		/* ==========================================================================
		   5. MONEY FORMATTING & PRICE CALCULATION UTILS
		   ========================================================================== */
		function formatMoney(amount) {
			var num = parseFloat(amount) || 0;
			var formatted = num.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');

			if (formatted.indexOf('.00') !== -1) {
				formatted = formatted.replace('.00', '');
			}

			var symbol = (typeof drbuAdminData !== 'undefined' && drbuAdminData.currency_symbol) ? drbuAdminData.currency_symbol : '$';
			var pos = (typeof drbuAdminData !== 'undefined' && drbuAdminData.currency_position) ? drbuAdminData.currency_position : 'left';

			switch (pos) {
				case 'left':
					return symbol + formatted;
				case 'left_space':
					return symbol + ' ' + formatted;
				case 'right':
					return formatted + symbol;
				case 'right_space':
				default:
					return formatted + ' ' + symbol;
			}
		}

		function adjustHexBrightness(hex, factor) {
			hex = String(hex).replace('#', '');
			if (hex.length !== 6) hex = '9ec84d';
			var r = parseInt(hex.substring(0, 2), 16);
			var g = parseInt(hex.substring(2, 4), 16);
			var b = parseInt(hex.substring(4, 6), 16);

			var step = 255 * factor;
			r = Math.max(0, Math.min(255, Math.round(r + step)));
			g = Math.max(0, Math.min(255, Math.round(g + step)));
			b = Math.max(0, Math.min(255, Math.round(b + step)));

			return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
		}

		function mixHexWithWhite(hex, white) {
			hex = String(hex).replace('#', '');
			if (hex.length !== 6) hex = '9ec84d';
			var r = parseInt(hex.substring(0, 2), 16);
			var g = parseInt(hex.substring(2, 4), 16);
			var b = parseInt(hex.substring(4, 6), 16);

			r = Math.round(255 * white + r * (1 - white));
			g = Math.round(255 * white + g * (1 - white));
			b = Math.round(255 * white + b * (1 - white));

			return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
		}

		function hexToRgb(hex) {
			hex = String(hex).replace('#', '');
			if (hex.length !== 6) hex = '9ec84d';
			return parseInt(hex.substring(0, 2), 16) + ',' + parseInt(hex.substring(2, 4), 16) + ',' + parseInt(hex.substring(4, 6), 16);
		}

		/* ==========================================================================
		   6. MAIN LIVE PREVIEW ENGINE (UPDATE PREVIEW)
		   ========================================================================== */
		function updatePreview() {
			// Base price from test input
			var basePrice = parseFloat($('#drbu-test-price').val()) || 18;

			// Read form settings
			var tierCount = parseInt($('input[name="drbu_options[drbu_tier_count]"]:checked').val(), 10) || 3;
			var discountType = $('#drbu_discount_type').val() || 'percentage';

			var enableFreeShip = $('input[name="drbu_options[drbu_enable_free_shipping]"]').is(':checked');
			var freeShipThreshold = parseFloat($('#drbu_free_ship_threshold').val()) || 0;

			var enableFooterBadges = $('input[name="drbu_options[drbu_enable_footer_badges]"]').is(':checked');
			var enableSavings = $('input[name="drbu_options[drbu_enable_savings]"]').is(':checked');

			var enableBestValue = $('input[name="drbu_options[drbu_enable_best_value]"]').is(':checked');
			var bestValueIndex = parseInt($('#drbu_best_value_index').val(), 10) || 2;

			var enablePerUnit = $('input[name="drbu_options[drbu_enable_per_unit]"]').is(':checked');
			var enableWasPrice = $('input[name="drbu_options[drbu_enable_was_price]"]').is(':checked');

			// Colors & Radiuses
			var primaryColor = $('input[name="drbu_options[drbu_primary_color]"]').val() || '#2563eb';
			var ctaTextColor = $('input[name="drbu_options[drbu_cta_text_color]"]').val() || '#ffffff';
			var bestValueColor = $('input[name="drbu_options[drbu_best_value_color]"]').val() || '#1d4ed8';
			var cardBgColor = $('input[name="drbu_options[drbu_card_bg_color]"]').val() || '#f8fafc';
			var btnRadius = $('#drbu_button_radius').val() || '100px';
			var cardRadius = $('#drbu_card_radius').val() || '16px';

			// Texts & Labels
			var getString = function (key, def) {
				var val = $('input[name="drbu_options[drbu_strings][' + key + ']"]').val();
				return (val !== undefined && val !== '') ? val : def;
			};

			var bestLabel = getString('best_label', 'Most Popular');
			var inStockLabel = getString('in_stock_label', 'In stock');
			var perUnitLabel = getString('per_unit_label', 'per unit');
			var totalLabel = getString('total_label', 'total');
			var packTotalLabel = getString('pack_total_label', 'for {qty} pieces · total');
			var savingsLabel = getString('savings_label', 'savings');
			var shipFreeText = getString('ship_free_text', 'Free shipping included in this pack');
			var shipPaidPrefix = getString('ship_paid_prefix', 'Free shipping for orders over');
			var freeShipFlagText = getString('free_ship_flag', 'Free shipping');

			var footerBadgesText = $('#drbu_footer_badges').val() || "Shipping 1–3 days\nCash on delivery\nMoney-back guarantee";

			// Obezbeđujemo da selektovani nivo ne prelazi broj nivoa
			if (selectedTierIndex > tierCount) {
				selectedTierIndex = tierCount;
			}

			var pricingModel = $('input[name="drbu_options[drbu_pricing_model]"]:checked').val() || 'model_a';

			// Preračun po nivoima
			var tiersData = [];
			for (var i = 0; i < tierCount; i++) {
				var $row = $('.drbu-tier-row-' + (i + 1));
				var qty = parseInt($row.find('.drbu-tier-input-qty').val(), 10) || (i + 1);
				var label = $('input[name="drbu_options[drbu_tiers][' + i + '][label]"]').val() || (qty + (qty > 1 ? ' pieces' : ' piece'));
				var note = $('input[name="drbu_options[drbu_tiers][' + i + '][note]"]').val() || '';
				var disc = parseFloat($row.find('.drbu-tier-input-discount').val()) || 0;

				var baseTotal = basePrice * qty;
				var rawTotal = baseTotal;
				var discDisplay = (discountType === 'percentage') ? ('-' + disc + '%') : ('-' + formatMoney(disc));

				if (pricingModel === 'model_b') {
					// Model B: Full Volume Discount
					if (discountType === 'fixed') {
						var unitDisc = Math.max(0, basePrice - disc);
						rawTotal = unitDisc * qty;
					} else {
						var perc = Math.max(0, Math.min(100, disc));
						rawTotal = baseTotal * (1 - (perc / 100));
					}
				} else if (pricingModel === 'model_c') {
					// Model C: Fixed Package Price
					rawTotal = (disc > 0) ? disc : baseTotal;
					discDisplay = formatMoney(rawTotal);
				} else if (pricingModel === 'model_d') {
					// Model D: Fixed Price Per Unit
					var unitVal = (disc > 0) ? disc : basePrice;
					rawTotal = unitVal * qty;
					discDisplay = formatMoney(unitVal) + '/unit';
				} else {
					// Model A: Incremental Item Discount
					var discAmount = 0;
					if (qty >= 2) {
						var d2 = parseFloat($('.drbu-tier-row-2 .drbu-tier-input-discount').val()) || 0;
						discAmount += (discountType === 'percentage') ? (basePrice * (d2 / 100)) : d2;
					}
					if (qty >= 3) {
						var d3 = parseFloat($('.drbu-tier-row-3 .drbu-tier-input-discount').val()) || 0;
						discAmount += (discountType === 'percentage') ? (basePrice * (d3 / 100)) : d3;
					}
					if (qty > 3) {
						var d3Extra = parseFloat($('.drbu-tier-row-3 .drbu-tier-input-discount').val()) || 0;
						discAmount += (qty - 3) * ((discountType === 'percentage') ? (basePrice * (d3Extra / 100)) : d3Extra);
					}
					rawTotal = Math.max(0, baseTotal - discAmount);
				}

				var unitPrice = (qty > 0) ? Math.round(rawTotal / qty) : rawTotal;
				var totalPrice = (qty > 0) ? (unitPrice * qty) : rawTotal;
				var saveAmount = Math.max(0, baseTotal - totalPrice);
				var isShipFree = (freeShipThreshold === 0) || (freeShipThreshold > 0 && totalPrice >= freeShipThreshold);

				// CTA text
				var ctaKey = 'cta' + (i + 1);
				var rawCta = getString(ctaKey, 'Order ' + qty + ' pieces — {price}');
				var formattedSavings = (saveAmount > 0) ? (savingsLabel + ' ' + formatMoney(saveAmount)) : '';
				var ctaText = rawCta.replace('{price}', formatMoney(totalPrice))
					.replace('{save}', formattedSavings)
					.replace('{qty}', qty)
					.replace('{unit_price}', formatMoney(unitPrice));

				tiersData.push({
					index: i + 1,
					qty: qty,
					label: label,
					note: note,
					disc: disc,
					discDisplay: discDisplay,
					baseTotal: baseTotal,
					totalPrice: totalPrice,
					unitPrice: unitPrice,
					saveAmount: saveAmount,
					isShipFree: isShipFree,
					ctaText: ctaText
				});
			}

			// Apply CSS variables to live preview container
			var hoverColor = adjustHexBrightness(primaryColor, -0.08);
			var softColor = mixHexWithWhite(primaryColor, 0.82);
			var rgbCsv = hexToRgb(primaryColor);

			$previewContainer.css({
				'--drbu-primary': primaryColor,
				'--drbu-primary-hover': hoverColor,
				'--drbu-primary-soft': softColor,
				'--drbu-primary-rgb': rgbCsv,
				'--drbu-cta-text': ctaTextColor,
				'--drbu-best-value': bestValueColor,
				'--drbu-card-bg': cardBgColor,
				'--drbu-btn-radius': btnRadius,
				'--drbu-card-radius': cardRadius
			});

			// Build wrapper classes for live preview toggle reactivity
			var wrapClasses = 'pg-buy drbu-buy';
			if (!enableFreeShip) wrapClasses += ' drbu-no-free-shipping';
			if (!enableFooterBadges) wrapClasses += ' drbu-no-footer-badges';
			if (!enableSavings) wrapClasses += ' drbu-no-savings';
			if (!enableBestValue) wrapClasses += ' drbu-no-best-value';
			if (!enablePerUnit) wrapClasses += ' drbu-no-per-unit';
			if (!enableWasPrice) wrapClasses += ' drbu-no-was-price';

			// Generate HTML
			var activeData = tiersData[selectedTierIndex - 1] || tiersData[0];

			var html = '<div class="' + wrapClasses + '">';

			// Hidden radios for CSS selector compatibility
			for (var r = 0; r < tierCount; r++) {
				var checkedAttr = ((r + 1) === selectedTierIndex) ? ' checked="checked"' : '';
				html += '<input class="pg-radio drbu-radio" type="radio" name="drbu-preview-pack" id="drbu-prev-r' + (r + 1) + '" data-v="' + (r + 1) + '"' + checkedAttr + '>';
			}

			// HEAD (Header unit price)
			html += '<div class="pg-head drbu-head">';
			html += '  <div class="drbu-price-v" data-v="' + selectedTierIndex + '" style="display:flex !important; align-items:baseline; gap:6px;">';
			html += '    <span class="drbu-num">' + formatMoney(activeData.unitPrice) + '</span>';
			html += '    <span class="drbu-per">' + perUnitLabel + '</span>';
			if (selectedTierIndex > 1 && activeData.saveAmount > 0) {
				html += '    <s class="drbu-was">' + formatMoney(basePrice) + '</s>';
			}
			html += '  </div>';
			html += '  <span class="drbu-instock">' + inStockLabel + '</span>';
			html += '</div>';

			// SHIPPING STATUS LINE
			if (enableFreeShip) {
				html += '<div class="drbu-ship-v' + (activeData.isShipFree ? ' drbu-free' : '') + '" data-v="' + selectedTierIndex + '" style="display:block !important; margin-bottom:12px;">';
				if (activeData.isShipFree) {
					html += '✓ ' + shipFreeText;
				} else {
					html += shipPaidPrefix + ' ' + formatMoney(freeShipThreshold);
				}
				html += '</div>';
			}

			// PACKS (KARTICE PAKETA)
			html += '<div class="drbu-packs">';
			for (var k = 0; k < tiersData.length; k++) {
				var td = tiersData[k];
				var isSelected = (td.index === selectedTierIndex);
				var isBest = (enableBestValue && td.index === bestValueIndex);

				var packClass = 'pg-pack drbu-pack' + (isBest ? ' drbu-is-best' : '');

				// Replace placeholders in note & label
				var displayLabel = td.label.replace('{qty}', td.qty);
				var noteHasSave = (td.note.indexOf('{save}') !== -1);
				var noteText = td.note
					.replace('{d1}', td.discDisplay)
					.replace('{d2}', td.discDisplay)
					.replace('{d3}', td.discDisplay)
					.replace('{qty}', td.qty)
					.replace('{price}', formatMoney(td.totalPrice));

				if (enableSavings && td.saveAmount > 0) {
					var formattedSave = (savingsLabel ? (savingsLabel + ' ') : '') + formatMoney(td.saveAmount);
					noteText = noteText.replace('{save}', formattedSave);
					if (!noteHasSave) {
						noteText += ' <b>' + formattedSave + '</b>';
					}
				} else {
					noteText = noteText.replace('{save}', '');
				}

				html += '<div class="' + packClass + '" data-tier="' + td.index + '">';
				html += '  <span class="drbu-tile' + (isSelected ? ' active-tile' : '') + '" style="' + (isSelected ? 'border-color:' + hoverColor + '; background:' + softColor + ';' : '') + '">';
				html += '    <span class="drbu-badges-wrap">';
				if (enableFreeShip && td.isShipFree) {
					html += '      <span class="drbu-shipflag">✓ ' + freeShipFlagText + '</span>';
				}
				if (isBest) {
					html += '      <span class="drbu-flag">' + bestLabel + '</span>';
				}
				html += '    </span>';

				html += '    <span class="drbu-dot" style="' + (isSelected ? 'border-color:' + hoverColor + ';' : '') + '">';
				if (isSelected) {
					html += '      <span style="width:10px; height:10px; border-radius:50%; background:' + hoverColor + '; display:block;"></span>';
				}
				html += '    </span>';

				html += '    <span class="drbu-pbody">';
				html += '      <b>' + displayLabel + '</b>';
				if (noteText) {
					html += '      <span class="drbu-pnote">' + noteText + '</span>';
				}
				if (enablePerUnit) {
					html += '      <span class="drbu-punit">' + formatMoney(td.unitPrice) + ' ' + perUnitLabel + '</span>';
				}
				html += '    </span>';

				html += '    <span class="drbu-pprice">';
				html += '      <span>' + formatMoney(td.totalPrice) + '</span>';
				if (enableWasPrice && td.saveAmount > 0) {
					html += '      <s>' + formatMoney(td.baseTotal) + '</s>';
				}
				html += '    </span>';

				html += '  </span>';
				html += '</div>';
			}
			html += '</div>';

			// CTA BUTTON
			html += '<div class="drbu-cta-wrap">';
			html += '  <a href="#" class="drbu-cta-v" onclick="return false;" style="display:flex !important;">';
			html += '    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6"></path></svg>';
			html += '    <span>' + activeData.ctaText + '</span>';
			html += '  </a>';
			html += '</div>';

			// FOOTER BADGES (Značke ispod dugmeta)
			if (enableFooterBadges && footerBadgesText.trim().length > 0) {
				var badgeLines = footerBadgesText.split('\n');
				html += '<div class="drbu-pay">';
				for (var b = 0; b < badgeLines.length; b++) {
					var line = badgeLines[b].trim();
					if (line.length > 0) {
						html += '  <span><span class="drbu-pi"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg></span> ' + line + '</span>';
					}
				}
				html += '</div>';
			}

			html += '</div>'; // .drbu-buy

			$previewContainer.html(html);
		}

		/* ==========================================================================
		   7. KLIK NA KARTICU PAKETA U PREVIEW-U MENJA AKTIVNI PAKET
		   ========================================================================== */
		$previewContainer.on('click', '.drbu-pack', function () {
			var tier = parseInt($(this).data('tier'), 10);
			if (tier) {
				selectedTierIndex = tier;
				updatePreview();
			}
		});

		/* ==========================================================================
		   8. RESET ALL PARAMETERS TO DEFAULT
		   ========================================================================== */
		$('#drbu-reset-defaults-btn').on('click', function (e) {
			e.preventDefault();
			if (confirm('Are you sure you want to reset all parameters and styles to default settings?')) {
				// Tier count to 3
				$('input[name="drbu_options[drbu_tier_count]"][value="3"]').prop('checked', true);
				$('.drbu-radio-btn').removeClass('selected');
				$('input[name="drbu_options[drbu_tier_count]"][value="3"]').closest('.drbu-radio-btn').addClass('selected');
				$('.drbu-tier-row-3').show();

				// Discount model & Best value index
				$('#drbu_discount_type').val('percentage');
				$('#drbu_best_value_index').val(2);
				$('#drbu_free_ship_threshold').val(3900);

				// Colors & Radiuses
				$('input[name="drbu_options[drbu_primary_color]"]').val('#c49186').siblings('.drbu-color-val').text('#C49186');
				$('input[name="drbu_options[drbu_cta_text_color]"]').val('#ffffff').siblings('.drbu-color-val').text('#FFFFFF');
				$('input[name="drbu_options[drbu_best_value_color]"]').val('#7e4e45').siblings('.drbu-color-val').text('#7E4E45');
				$('input[name="drbu_options[drbu_card_bg_color]"]').val('#fdf8f6').siblings('.drbu-color-val').text('#FDF8F6');
				$('#drbu_button_radius').val('100px');
				$('#drbu_card_radius').val('16px');

				var toggles = [
					'drbu_enable_free_shipping',
					'drbu_enable_footer_badges',
					'drbu_enable_savings',
					'drbu_enable_best_value',
					'drbu_enable_per_unit',
					'drbu_enable_was_price',
					'drbu_auto_insert_product',
					'drbu_replace_add_to_cart'
				];
				toggles.forEach(function (key) {
					$('input[name="drbu_options[' + key + ']"]').prop('checked', true);
				});
				$('input[name="drbu_options[drbu_hide_default_price]"]').prop('checked', false);

				$('#drbu-subfield-free-ship-threshold').show();
				$('#drbu-subfield-best-value-index').show();

				// Default Tiers
				var defaultTiers = [
					{ qty: 1, label: '1 piece', note: 'Basic packaging', discount: 0 },
					{ qty: 2, label: '2 pieces', note: 'Second item − {d2} · {save}', discount: 40 },
					{ qty: 3, label: '3 pieces', note: 'Third item − {d3} · {save}', discount: 25 }
				];
				defaultTiers.forEach(function (t, idx) {
					var $row = $('.drbu-tier-row-' + (idx + 1));
					$row.find('.drbu-tier-input-qty').val(t.qty);
					$row.find('.drbu-tier-input-label').val(t.label);
					$row.find('.drbu-tier-input-note').val(t.note);
					$row.find('.drbu-tier-input-discount').val(t.discount);
				});

				// Default Strings
				var defaultStrings = {
					'best_label': 'Most Popular',
					'in_stock_label': 'In stock',
					'per_unit_label': 'per unit',
					'total_label': 'total',
					'pack_total_label': 'for {qty} pieces · total',
					'savings_label': 'savings',
					'ship_free_text': 'Free shipping included in this pack',
					'ship_paid_prefix': 'Free shipping for orders over',
					'free_ship_flag': 'Free shipping',
					'cta1': 'Order 1 piece — {price}',
					'cta2': 'Order 2 pieces — {price}',
					'cta3': 'Order 3 pieces — {price}',
					'cart_pack_label': 'Pack of {qty} pieces'
				};
				Object.keys(defaultStrings).forEach(function (key) {
					$('input[name="drbu_options[drbu_strings][' + key + ']"]').val(defaultStrings[key]);
				});

				$('#drbu_footer_badges').val("Shipping 1–3 days\nCash on delivery\nMoney-back guarantee");

				selectedTierIndex = 1;
				updatePreview();
			}
		});

		// Inicijalno pokretanje Live Preview-a
		var initialCount = parseInt($('input[name="drbu_options[drbu_tier_count]"]:checked').val(), 10) || 3;
		if (initialCount === 2) {
			$('.drbu-tier-row-3').hide();
		}
		updatePreview();
	});

	/* ==========================================================================
	   ANALYTICS ORDERS TABLE: SEARCH, SORT, PAGINATION (30 PER PAGE), CHECK ALL
	   ========================================================================== */
	function initAnalyticsOrdersTable() {
		var $table = $('#drbu-orders-list-table');
		if (!$table.length) {
			return;
		}

		var $rows = $('#drbu-orders-tbody .drbu-order-row');
		var $searchInput = $('#drbu-orders-search');
		var $selectAll = $('#cb-select-all-1');
		var $paginationInfo = $('#drbu-pagination-info');
		var $paginationControls = $('#drbu-pagination-controls');
		var $totalCountBadge = $('#drbu-orders-total-count');

		var itemsPerPage = 30;
		var currentPage = 1;
		var sortColumn = 'date';
		var sortDirection = 'desc';

		var allData = [];
		$rows.each(function () {
			var $tr = $(this);
			allData.push({
				$el: $tr,
				number: String($tr.data('number') || ''),
				customer: String($tr.data('customer') || ''),
				status: String($tr.data('status') || ''),
				origin: String($tr.data('origin') || ''),
				packet: String($tr.data('packet') || ''),
				date: parseInt($tr.data('date'), 10) || 0,
				total: parseFloat($tr.data('total')) || 0,
				index: parseInt($tr.data('index'), 10) || 0
			});
		});

		var filteredData = allData.slice();

		function sortData() {
			filteredData.sort(function (a, b) {
				var valA = a[sortColumn];
				var valB = b[sortColumn];

				if (typeof valA === 'string') {
					valA = valA.toLowerCase();
					valB = valB.toLowerCase();
				}

				if (valA < valB) return sortDirection === 'asc' ? -1 : 1;
				if (valA > valB) return sortDirection === 'asc' ? 1 : -1;
				return 0;
			});
		}

		function filterData() {
			var query = $.trim($searchInput.val()).toLowerCase();
			if (!query) {
				filteredData = allData.slice();
			} else {
				filteredData = allData.filter(function (item) {
					return item.number.indexOf(query) !== -1 ||
						item.customer.indexOf(query) !== -1 ||
						item.status.indexOf(query) !== -1 ||
						item.origin.indexOf(query) !== -1 ||
						item.packet.indexOf(query) !== -1 ||
						String(item.total).indexOf(query) !== -1;
				});
			}
			sortData();
			currentPage = 1;
			renderTable();
		}

		function renderTable() {
			var totalItems = filteredData.length;
			var totalPages = Math.ceil(totalItems / itemsPerPage) || 1;

			if (currentPage > totalPages) currentPage = totalPages;
			if (currentPage < 1) currentPage = 1;

			var startIndex = (currentPage - 1) * itemsPerPage;
			var endIndex = Math.min(startIndex + itemsPerPage, totalItems);

			var $tbody = $('#drbu-orders-tbody');
			$tbody.empty();

			for (var i = startIndex; i < endIndex; i++) {
				$tbody.append(filteredData[i].$el);
			}

			if (totalItems === 0) {
				$paginationInfo.text('Nema narudžbina koje odgovaraju pretrazi.');
			} else {
				$paginationInfo.text('Prikazano ' + (startIndex + 1) + '–' + endIndex + ' od ' + totalItems + ' narudžbina');
			}

			if ($totalCountBadge.length) {
				$totalCountBadge.text(totalItems + ' narudžbina');
			}

			renderPaginationControls(totalPages);
		}

		function renderPaginationControls(totalPages) {
			$paginationControls.empty();
			if (totalPages <= 1) {
				return;
			}

			var html = '';
			if (currentPage > 1) {
				html += '<a class="prev-page button" href="#" data-page="' + (currentPage - 1) + '">‹ Nazad</a> ';
			} else {
				html += '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹ Nazad</span> ';
			}

			html += '<span class="paging-input"><span class="current-page">' + currentPage + '</span> od <span class="total-pages">' + totalPages + '</span></span> ';

			if (currentPage < totalPages) {
				html += '<a class="next-page button" href="#" data-page="' + (currentPage + 1) + '">Napred ›</a>';
			} else {
				html += '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">Napred ›</span>';
			}

			$paginationControls.html(html);
		}

		$searchInput.on('input keyup search', function () {
			filterData();
		});

		$paginationControls.on('click', 'a[data-page]', function (e) {
			e.preventDefault();
			currentPage = parseInt($(this).data('page'), 10) || 1;
			renderTable();
			$('html, body').animate({ scrollTop: $table.offset().top - 80 }, 150);
		});

		$selectAll.on('change', function () {
			var isChecked = $(this).is(':checked');
			$('#drbu-orders-tbody .drbu-order-cb').prop('checked', isChecked);
		});

		$table.find('th.sortable').on('click', function (e) {
			e.preventDefault();
			var col = $(this).data('sort');
			if (sortColumn === col) {
				sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
			} else {
				sortColumn = col;
				sortDirection = 'desc';
			}

			$table.find('th.sortable').removeClass('asc desc');
			$(this).addClass(sortDirection);

			sortData();
			renderTable();
		});

		sortData();
		renderTable();
	}

	/* ==========================================================================
	   INTERACTIVE PRODUCT SEARCH & RESTRICTION PICKER
	   ========================================================================== */
	function initProductRestrictionsPicker() {
		var $searchInput = $('#drbu-product-search-input');
		var $searchResults = $('#drbu-product-search-results');
		var $pillsList = $('#drbu-selected-products-list');
		var $hiddenInput = $('#drbu_auto_insert_product_ids');
		if (!$searchInput.length || !$hiddenInput.length) {
			return;
		}

		var searchTimer = null;

		$searchInput.on('input keyup', function () {
			var term = $.trim($(this).val());
			clearTimeout(searchTimer);

			if (term.length < 2) {
				$searchResults.hide().empty();
				return;
			}

			searchTimer = setTimeout(function () {
				$.ajax({
					url: (typeof drbuAdminData !== 'undefined' && drbuAdminData.ajax_url) ? drbuAdminData.ajax_url : ajaxurl,
					type: 'GET',
					data: {
						action: 'drbu_search_products',
						security: (typeof drbuAdminData !== 'undefined') ? drbuAdminData.nonce : '',
						term: term
					},
					success: function (res) {
						if (res && res.success && res.data && res.data.length > 0) {
							var html = '';
							$.each(res.data, function (i, item) {
								var safeId = parseInt(item.id, 10) || 0;
								html += '<div class="drbu-search-item" data-id="' + safeId + '" data-name="' + escapeHtml(item.title) + '">';
								html += '  <span><strong>' + escapeHtml(item.name) + '</strong> <small style="color:#64748b;">(#' + safeId + ')</small></span>';
								if (item.price_html) {
									html += '  <span style="font-weight:600; color:#0284c7;">' + item.price_html + '</span>';
								}
								html += '</div>';
							});
							$searchResults.html(html).show();
						} else {
							$searchResults.html('<div style="padding:12px; color:#94a3b8; text-align:center;">No products found matching "' + escapeHtml(term) + '"</div>').show();
						}
					}
				});
			}, 250);
		});

		// Select product from search dropdown
		$(document).on('click', '.drbu-search-item', function () {
			var id = parseInt($(this).data('id'), 10);
			var name = $(this).data('name') || ('Product #' + id);

			if (!id) return;

			var currentIds = getProductIds();
			if (currentIds.indexOf(id) === -1) {
				currentIds.push(id);
				updateProductIds(currentIds);

				var pillHtml = '<span class="drbu-prod-pill" data-id="' + id + '">' + escapeHtml(name) + ' <button type="button" class="drbu-remove-pill" data-id="' + id + '">&times;</button></span>';
				$pillsList.append(pillHtml);
			}

			$searchInput.val('');
			$searchResults.hide().empty();
			updateModeBanner();
		});

		// Remove product pill
		$(document).on('click', '.drbu-remove-pill', function () {
			var id = parseInt($(this).data('id'), 10);
			$(this).closest('.drbu-prod-pill').remove();

			var currentIds = getProductIds();
			var index = currentIds.indexOf(id);
			if (index !== -1) {
				currentIds.splice(index, 1);
				updateProductIds(currentIds);
			}
			updateModeBanner();
		});

		// Close dropdown on outside click
		$(document).on('click', function (e) {
			if (!$(e.target).closest('.drbu-picker-container').length) {
				$searchResults.hide();
			}
		});

		function getProductIds() {
			var raw = $hiddenInput.val() || '';
			if (!raw) return [];
			return raw.split(',').map(function (v) { return parseInt(v, 10); }).filter(function (v) { return v > 0; });
		}

		function updateProductIds(idsArr) {
			$hiddenInput.val(idsArr.join(',')).trigger('change');
		}

		function updateModeBanner() {
			var prodIds = getProductIds();
			var catChecked = $('.drbu-cat-checklist input[type="checkbox"]:checked').length;
			var $banner = $('.drbu-mode-banner');

			if (prodIds.length === 0 && catChecked === 0) {
				$banner.removeClass('target').addClass('storewide')
					.html('<span>🌐 <strong>Storewide Mode:</strong> Discount Rules Box will appear on <strong>ALL</strong> simple products across your store.</span>');
			} else {
				$banner.removeClass('storewide').addClass('target')
					.html('<span>🎯 <strong>Target Mode:</strong> Discount Rules Box will appear <strong>ONLY</strong> on the selected products and categories below.</span>');
			}
		}

		$('.drbu-cat-checklist').on('change', 'input[type="checkbox"]', function () {
			updateModeBanner();
		});
	}

	function initQuickLanguagePresets() {
		var langPresets = (window.drbuAdminData && drbuAdminData.lang_presets) || {};

		$(document).on('change', '#drbu-quick-lang-select', function () {
			var langKey = $(this).val();
			if (!langKey || !langPresets[langKey]) return;

			var d = langPresets[langKey];

			// Update Tier labels & notes
			$('input[name*="[drbu_tiers][0][label]"]').val(d.t1_label).trigger('input');
			$('input[name*="[drbu_tiers][0][note]"]').val(d.t1_note).trigger('input');
			$('input[name*="[drbu_tiers][1][label]"]').val(d.t2_label).trigger('input');
			$('input[name*="[drbu_tiers][1][note]"]').val(d.t2_note).trigger('input');
			$('input[name*="[drbu_tiers][2][label]"]').val(d.t3_label).trigger('input');
			$('input[name*="[drbu_tiers][2][note]"]').val(d.t3_note).trigger('input');

			// Update string fields
			$('#drbu_footer_badges').val(d.footer_badges).trigger('input');
			$('input[name*="[drbu_strings][cta1]"]').val(d.cta1).trigger('input');
			$('input[name*="[drbu_strings][cta2]"]').val(d.cta2).trigger('input');
			$('input[name*="[drbu_strings][cta3]"]').val(d.cta3).trigger('input');
			$('input[name*="[drbu_strings][best_label]"]').val(d.best_label).trigger('input');
			$('input[name*="[drbu_strings][in_stock_label]"]').val(d.in_stock_label).trigger('input');
			$('input[name*="[drbu_strings][savings_label]"]').val(d.savings_label).trigger('input');
			$('input[name*="[drbu_strings][ship_free_text]"]').val(d.ship_free_text).trigger('input');
			$('input[name*="[drbu_strings][ship_paid_prefix]"]').val(d.ship_paid_prefix).trigger('input');
			$('input[name*="[drbu_strings][free_ship_flag]"]').val(d.free_ship_flag).trigger('input');
			$('input[name*="[drbu_strings][per_unit_label]"]').val(d.per_unit_label).trigger('input');
			$('input[name*="[drbu_strings][total_label]"]').val(d.total_label).trigger('input');
			$('input[name*="[drbu_strings][pack_total_label]"]').val(d.pack_total_label).trigger('input');
			$('input[name*="[drbu_strings][cart_pack_label]"]').val(d.cart_pack_label).trigger('input');
		});
		$(document).on('change', '.drbu-pricing-model-group input', function () {
			var val = $(this).val();
			$('.drbu-pm-btn').removeClass('selected');
			$(this).closest('.drbu-pm-btn').addClass('selected');

			var $colHeader = $('#drbu-discount-col-header');
			var $logicList = $('#drbu-logic-list');

			if (val === 'model_b') {
				$colHeader.text('Discount on ALL Items (% or $)');
				if ($logicList.length) {
					$logicList.html('<li><strong>Model B — Full Volume Discount:</strong> Discount entered applies across ALL items in the bundle (e.g. 2 pcs at 40% off = $21.60 total).</li>');
				}
			} else if (val === 'model_c') {
				$colHeader.text('Fixed Package Price ($ / RSD)');
				if ($logicList.length) {
					$logicList.html('<li><strong>Model C — Fixed Total Bundle Price:</strong> The value entered is the exact fixed total price for the entire pack (e.g. Tier 1 = $18.00, Tier 2 = $28.80, Tier 3 = $39.99).</li>');
				}
			} else if (val === 'model_d') {
				$colHeader.text('Fixed Price Per Unit ($ / RSD)');
				if ($logicList.length) {
					$logicList.html('<li><strong>Model D — Fixed Price Per Unit:</strong> The value entered is the exact fixed price per single item for each tier (e.g. Tier 2 = $14.40/unit -> $28.80 total).</li>');
				}
			} else {
				$colHeader.text('Discount on Additional Item (% or $)');
				if ($logicList.length) {
					$logicList.html('<li><strong>Tier 1 (1 piece):</strong> Customer pays full regular price (0% discount).</li><li><strong>Tier 2 (2 pieces):</strong> The discount entered (e.g. 40%) applies to the SECOND item in the pack.</li><li><strong>Tier 3 (3 pieces):</strong> The discount entered (e.g. 25%) applies to the THIRD item in the pack.</li>');
				}
			}

			if (typeof updateLivePreview === 'function') {
				updateLivePreview();
			}
		});
	}

	function initFreemiusCheckout() {
		$(document).on('click', '.drbu-open-checkout, .drbu-open-trial, a[href*="drbu-tiered-buy-box-pricing"]', function (e) {
			if (typeof FS !== 'undefined' && FS.Checkout) {
				e.preventDefault();
				var $this = $(this);
				var href = $this.attr('href') || '';
				var btnText = ($this.text() || '').toLowerCase();
				var isTrial = $this.hasClass('drbu-open-trial') ||
					(href.indexOf('trial=true') !== -1) ||
					(btnText.indexOf('trial') !== -1) ||
					(btnText.indexOf('besplatn') !== -1) ||
					(btnText.indexOf('free') !== -1 && btnText.indexOf('version') === -1);

				var licenses = $this.data('licenses') || 1;

				var cfg = (window.drbuAdminData && window.drbuAdminData.freemius_config) ? window.drbuAdminData.freemius_config : {};
				var handler = new FS.Checkout({
					product_id: cfg.product_id || '37209',
					plan_id: cfg.plan_id || '61804',
					public_key: cfg.public_key || 'pk_1ed69d2634756f08c2a7bf2187d37'
				});

				var syncAndReload = function () {
					// Freemius Checkout kreira trial/kupovinu direktno na svojim serverima;
					// lokalni WP install ne zna za to dok se ne izvuče svez plan/licenca.
					// Freemius SDK nema javnu "sync_license()" AJAX komandu — jedini
					// pravi javni nacin da se to izvuce je GET na Account stranicu sa
					// fs_action=..._sync_license (drbuAdminData.fs_sync_license_url),
					// koju SDK interno obradjuje. Fetch sa credentials:'same-origin'
					// salje admin kolacic pa se izvrsava kao ulogovan admin, a mi
					// ignorisemo HTML odgovor (korisnik nikad ne vidi tu stranicu).
					var reload = function () { window.location.reload(); };
					var syncUrl = (window.drbuAdminData && drbuAdminData.fs_sync_license_url) ? drbuAdminData.fs_sync_license_url : '';

					var finishUp = function () {
						var ajaxUrl = (window.drbuAdminData && drbuAdminData.ajax_url) ? drbuAdminData.ajax_url : (window.ajaxurl || '');
						var nonce = (window.drbuAdminData && drbuAdminData.nonce) ? drbuAdminData.nonce : '';
						$.post(ajaxUrl, {
							action: 'drbu_sync_freemius_license',
							security: nonce
						}).always(reload);
					};

					if (!syncUrl) {
						finishUp();
						return;
					}

					fetch(syncUrl, { credentials: 'same-origin' }).then(finishUp).catch(finishUp);
				};

				handler.open({
					name: 'Discount Rules Box',
					licenses: licenses,
					trial: isTrial ? 'free' : false,
					purchaseCompleted: syncAndReload,
					success: syncAndReload
				});
			}
		});
	}

	/**
	 * "Sync License Now" dugme na License tabu — poziva istu
	 * drbu_sync_freemius_license AJAX komandu koja sad forsira pravu
	 * Freemius sinhronizaciju server-side (vidi ajax_sync_freemius_license()
	 * u class-drbu-settings.php), pa je dovoljno samo POST + reload, bez
	 * potrebe za fs_sync_license_url fetch koraka koji koristi checkout tok.
	 */
	function initManualLicenseSync() {
		$(document).on('click', '.drbu-sync-license-btn', function () {
			var $btn = $(this);
			if ($btn.prop('disabled')) {
				return;
			}
			var originalText = $btn.text();
			$btn.prop('disabled', true).text('⏳ Syncing…');

			var ajaxUrl = (window.drbuAdminData && drbuAdminData.ajax_url) ? drbuAdminData.ajax_url : (window.ajaxurl || '');
			var nonce = (window.drbuAdminData && drbuAdminData.nonce) ? drbuAdminData.nonce : '';

			$.post(ajaxUrl, {
				action: 'drbu_sync_freemius_license',
				security: nonce
			}).always(function () {
				window.location.reload();
			});

			// Ako reload ne stigne u razumnom roku (npr. Freemius API spor/nedostupan),
			// vrati dugme u normalno stanje umesto da ostane zaglavljeno na "Syncing…".
			setTimeout(function () {
				$btn.prop('disabled', false).text(originalText);
			}, 15000);
		});
	}

	/**
	 * Freemius-ov pricing widget (Upgrade stranica) je u potpunosti
	 * klijentski-renderovan (React bundle učitan iz freemius-pricing.js) i
	 * povlači naziv plana / cenu / feature listu / support status ŽIVO sa
	 * Freemius API-ja — ništa od toga ne prolazi kroz naš PHP, pa se ne može
	 * trajno promeniti iz plugin koda. Ispravan način je da se ti podaci
	 * urede direktno na Freemius Developer Dashboard-u (Monetization →
	 * Pricing → feature liste / support kanali / discount %).
	 *
	 * OVO JE PRIVREMENA ZAKRPA dok se Dashboard ne sredi: posle renderovanja
	 * widget-a (MutationObserver, jer React ubacuje kartice asinhrono),
	 * prepravlja tekst unutar svake ".fs-package" kartice preko poznatih
	 * SDK CSS klasa (potvrđenih čitanjem freemius-pricing.js: .fs-plan-title,
	 * .fs-plan-support, .fs-plan-features-with-value, .fs-upgrade-button-container,
	 * .fs-selected-pricing-amount) da liči na landing stranicu — zamenjuje
	 * "No Support" sa "Includes 30-Day Free Trial", dodaje feature bullet-e,
	 * i "Most Popular" bedž na 5 Sites.
	 *
	 * NAPOMENA: nema "was $X / you save $Y" linije — plan ima samo godišnje
	 * cene (nema mesečnog plana od kog bi godišnji bio "popust"), pa bi
	 * takva linija implicirala nepostojeći popust. Korisnik je eksplicitno
	 * tražio da se ukloni kada je ubačena po uzoru na landing stranicu.
	 *
	 * KRHKO PO DIZAJNU: Ako Freemius ikad promeni CSS klase u svom bundle-u,
	 * ova zakrpa jednostavno prestaje da nešto radi (nema greške, samo se
	 * kartice ne menjaju) — ne ruši widget.
	 */
	function initFreemiusPricingPatch() {
		var $wrapper = $('#fs_pricing_wrapper');
		if ( ! $wrapper.length ) {
			return;
		}

		var COPY = {
			1: {
				title: '1 Site',
				tagline: 'Test risk-free for 30 days, cancel anytime'
			},
			5: {
				title: '5 Sites',
				tagline: '⚡ Only $1.58/mo per store ($19/yr)',
				badge: 'Most Popular'
			},
			10: {
				title: '10 Sites',
				tagline: '🔥 Only $1.03/mo per store ($12.40/yr)'
			}
		};

		function patchCard( card ) {
			var $card = $( card );

			if ( $card.data( 'drbuPatched' ) || $card.hasClass( 'fs-free-plan' ) ) {
				return;
			}

			var $title    = $card.find( '.fs-plan-title' ).first();
			var titleText = $.trim( $title.text() );
			var match     = titleText.match( /(\d+)/ );
			var count     = match ? parseInt( match[1], 10 ) : 1;
			var cfg       = COPY[ count ];

			if ( ! cfg ) {
				return;
			}

			$card.data( 'drbuPatched', true );

			if ( titleText && /single site/i.test( titleText ) ) {
				$title.text( cfg.title );
			}

			// "No Support" -> "Includes 30-Day Free Trial" (zeleno, kao landing).
			var $supportStrong = $card.find( '.fs-plan-support strong' ).first();
			if ( $supportStrong.length && /no support/i.test( $supportStrong.text() ) ) {
				$supportStrong.closest( '.fs-plan-support' )
					.addClass( 'drbu-fs-trial-note' )
					.html( 'Includes 30-Day Free Trial' );
			}

			// Feature bullet-i (samo ako Freemius Dashboard još nema podešene).
			var $features = $card.find( '.fs-plan-features-with-value' ).first();
			if ( $features.length && 0 === $features.children( 'li' ).length ) {
				$features.append( '<li class="drbu-fs-feature">All Pro features included</li>' );
				$features.append( '<li class="drbu-fs-feature">Use on up to ' + count + ' site' + ( count > 1 ? 's' : '' ) + '</li>' );
			}

			// Tagline iznad Upgrade Now dugmeta.
			var $btnContainer = $card.find( '.fs-upgrade-button-container' ).first();
			if ( $btnContainer.length && ! $card.find( '.drbu-fs-tagline' ).length ) {
				$btnContainer.before( '<p class="drbu-fs-tagline">' + cfg.tagline + '</p>' );
			}

			// "Most Popular" bedž.
			if ( cfg.badge && ! $card.find( '.drbu-fs-badge' ).length ) {
				$card.addClass( 'drbu-fs-featured-card' ).prepend( '<span class="drbu-fs-badge">' + cfg.badge + '</span>' );
			}
		}

		function patchAllCards() {
			$wrapper.find( '.fs-package' ).each( function () {
				patchCard( this );
			} );
		}

		patchAllCards();

		if ( window.MutationObserver ) {
			var observer = new MutationObserver( patchAllCards );
			observer.observe( $wrapper[0], { childList: true, subtree: true } );
		}
	}

	// NAPOMENA: ranije je ovdje postojala initLicenseActivation() — ručna
	// reimplementacija fs_activate_license_* AJAX poziva preko $.post(). U praksi
	// je povremeno padala sa "Invalid license key." bez jasnog razloga, dok je
	// Freemius-ov sopstveni native dijalog (Plugins stranica → "Change License")
	// sa ISTIM ključem uvijek radio pouzdano. Umjesto dalje reimplementacije,
	// "Have a License Key?" dugme sada ima klasu "activate-license-trigger
	// {unique_affix}" i direktno otvara taj isti native dijalog — SDK-ov
	// sopstveni JS (forms/license-activation.php, injektovan preko
	// DRBU_Core::maybe_inject_freemius_license_dialog()) se sam vezuje na taj
	// selektor, nema više posebnog JS-a ovdje.

	$(document).ready(function () {
		initProductRestrictionsPicker();
		initQuickLanguagePresets();
		initFreemiusCheckout();
		initManualLicenseSync();
		initFreemiusPricingPatch();
	});

})(jQuery);
