(function ($) {
	"use strict";
	
	var ajaxURL =
		(window.kc_contracts && window.kc_contracts.ajax_url) ||
		window.ajaxurl ||
		(window.wc_checkout_params && window.wc_checkout_params.ajax_url) ||
		"/wp-admin/admin-ajax.php";
	var kcSettings = window.kc_contracts || {};
	var kcStrings = kcSettings.strings || {};
	var ajaxNonce = kcSettings.nonce || "";
	
	var $fieldBir = $();
	var $fieldIki = $();

	var tpl1 = "";
	var tpl2 = "";
	var cartSummaryHTML = "";
	var cartTotal = "";
	var cartSummaryLoading = false;
	var cartSummaryPending = false;
	var modalHtml1 = "";
	var modalHtml2 = "";
	var modalTitles = { 1: "", 2: "" };
	var modalInstances = { 1: null, 2: null };
	var modalStrings = window.kc_modal_strings || {};
	
	/* Döngü ve gereksiz istekleri engellemek için bayrak + önbellek */
	var isUpdating = false;
	var lastRendered1 = "";
	var lastRendered2 = "";
	var lastReportedMissingFieldsKey = null;
	
	function debounce(fn, ms) {
		var t;
		return function () {
			clearTimeout(t);
			var self = this,
				args = arguments;
			t = setTimeout(function () {
				fn.apply(self, args);
			}, ms || 400);
		};
	}
	
	function txt(v) {
		return (v || "").toString().trim();
	}

	function escapeHtml(value) {
		return String(value || "")
			.replace(/&/g, "&amp;")
			.replace(/</g, "&lt;")
			.replace(/>/g, "&gt;")
			.replace(/"/g, "&quot;")
			.replace(/'/g, "&#39;");
	}

	function i18nString(key, fallback) {
		return kcStrings[key] || fallback || "";
	}

	function classicCheckoutForm() {
		return $("form.checkout").first();
	}

	function ensureClassicHiddenFields() {
		var $form = classicCheckoutForm();
		if (!$form.length) {
			$fieldBir = $("#billing_satis_sozlesme");
			$fieldIki = $("#billing_mesafeli_sozlesme");
			return;
		}

		$('[id="billing_satis_sozlesme"]').slice(1).remove();
		$('[id="billing_mesafeli_sozlesme"]').slice(1).remove();

		var $holder = $("#manuel_checkout_alanlari").first();
		if (!$holder.length) {
			$holder = $('<div id="manuel_checkout_alanlari" class="kc-classic-contract-meta-fields" aria-hidden="true"></div>');
			var $anchor = $("#order_review, .woocommerce-checkout-review-order").first();
			if ($anchor.length) {
				$anchor.before($holder);
			} else {
				$form.append($holder);
			}
		}

		$fieldBir = $("#billing_satis_sozlesme").first();
		if (!$fieldBir.length) {
			$fieldBir = $('<textarea name="billing_satis_sozlesme" class="input-text kc-contract-snapshot-field" id="billing_satis_sozlesme" tabindex="-1"></textarea>');
			$holder.append($fieldBir);
		}

		$fieldIki = $("#billing_mesafeli_sozlesme").first();
		if (!$fieldIki.length) {
			$fieldIki = $('<textarea name="billing_mesafeli_sozlesme" class="input-text kc-contract-snapshot-field" id="billing_mesafeli_sozlesme" tabindex="-1"></textarea>');
			$holder.append($fieldIki);
		}

		if ($('input[name="kc_contract_nonce"]').not($holder.find('input[name="kc_contract_nonce"]')).length) {
			$holder.find('input[name="kc_contract_nonce"]').remove();
		}

		if (
			kcSettings.approval_required &&
			kcSettings.approval_nonce &&
			!$('input[name="kc_contract_nonce"]').length
		) {
			$holder.append(
				$('<input type="hidden" name="kc_contract_nonce" />').val(kcSettings.approval_nonce)
			);
		}
	}

	function normalizeSelectors(selectors) {
		if (!selectors) return [];
		return Array.isArray(selectors) ? selectors : [selectors];
	}

	function isPlaceholderText(value) {
		var normalized = txt(value).toLowerCase();
		return (
			!normalized ||
			normalized === "bir seçenek belirleyin…" ||
			normalized === "bir seçenek belirleyin..." ||
			normalized === "select an option" ||
			normalized === "choose an option" ||
			normalized === "seçiniz" ||
			normalized === "seciniz"
		);
	}

	function textValueOf($el) {
		var $select = $el.is("select") ? $el : $el.find("select").first();
		if ($select.length) {
			if (!txt($select.val())) return "";
			return txt($select.find("option:selected").text()) || txt($select.val());
		}

		var $field = $el.is("input, textarea") ? $el : $el.find("input, textarea").first();
		if ($field.length) return txt($field.val());

		var $select2 = $el.is(".select2-selection__rendered") ? $el : $el.find(".select2-selection__rendered").first();
		if ($select2.length) {
			var select2Text = txt($select2.attr("title")) || txt($select2.text());
			return isPlaceholderText(select2Text) ? "" : select2Text;
		}

		return txt($el.text()) || txt($el.val());
	}
	
	function valOf(selector, asText) {
		var selectors = normalizeSelectors(selector);
		var i;
		for (i = 0; i < selectors.length; i++) {
			if (!selectors[i]) continue;
			var $el;
			try {
				$el = $(selectors[i]).first();
			} catch (e) {
				continue;
			}
			if (!$el.length) continue;
			var value = asText
				? textValueOf($el)
				: ($el.is("select, input, textarea") ? txt($el.val()) : (txt($el.text()) || txt($el.val())));
			if (value !== "") return value;
		}
		return "";
	}
	
	function fromMap(key, fallbackSelector, asText) {
		var map = window.korkmaz_var || {};
		var selectors = [];
		if (map[key]) selectors.push(map[key]);
		selectors = selectors.concat(normalizeSelectors(fallbackSelector));
		return valOf(selectors, !!asText);
	}

	function hasSelector(selector) {
		if (!selector) return false;
		try {
			return $(selector).length > 0;
		} catch (e) {
			return false;
		}
	}

	function hasMappedField(key, fallbackSelectors) {
		var map = window.korkmaz_var || {};
		var selectors = [];
		if (key && map[key]) selectors.push(map[key]);
		selectors = selectors.concat(normalizeSelectors(fallbackSelectors));
		return selectors.some(hasSelector);
	}
	
	function joinParts() {
		return Array.prototype.slice
			.call(arguments)
			.filter(Boolean)
			.join(" ")
			.replace(/\s+/g, " ")
			.trim();
	}
	
	function nowTR() {
		var d = new Date();
		function p(n) {
			return ("0" + n).slice(-2);
		}
		return (
			p(d.getDate()) +
			"-" +
			p(d.getMonth() + 1) +
			"-" +
			d.getFullYear() +
			" " +
			p(d.getHours()) +
			":" +
			p(d.getMinutes()) +
			":" +
			p(d.getSeconds())
		);
	}

	function normalizeCartSummary(resp) {
		if (!resp || typeof resp !== "object") return;
		var data = resp.data && typeof resp.data === "object" ? resp.data : resp;
		if (typeof data.table === "string") {
			cartSummaryHTML = data.table;
		}
		if (typeof data.total === "string") {
			cartTotal = data.total;
		}
	}

	function fetchCartSummary(callback) {
		if (cartSummaryLoading) {
			cartSummaryPending = true;
			return;
		}
		cartSummaryLoading = true;

		$.ajax({
			url: ajaxURL,
			type: "POST",
			dataType: "json",
			data: { action: "korkmaz_cart_summary", nonce: ajaxNonce },
		})
			.done(function (resp) {
				normalizeCartSummary(resp);
			})
			.always(function () {
				cartSummaryLoading = false;
				if (typeof callback === "function") callback();
				if (cartSummaryPending) {
					cartSummaryPending = false;
					fetchCartSummary(callback);
				}
			});
	}

	function getContractLinks() {
		return $(
			'.kc-contract-link, [data-kc-modal], a[href="#kc-modal-1"], a[href="#kc-modal-2"]'
		);
	}

	function syncModalTitles() {
		getContractLinks().each(function () {
			var $link = $(this);
			var dataWhich = parseInt($link.data("kc-modal"), 10);
			var href = $link.attr("href") || "";
			var label = txt($link.text());
			if (!label) return;
			if (dataWhich === 1) {
				modalTitles[1] = label;
			} else if (dataWhich === 2) {
				modalTitles[2] = label;
			} else if (href.indexOf("kc-modal-1") !== -1) {
				modalTitles[1] = label;
			} else if (href.indexOf("kc-modal-2") !== -1) {
				modalTitles[2] = label;
			}
		});
	}

	function getModalTitle(which) {
		return (
			modalTitles[which] ||
			modalStrings["title" + which] ||
			modalStrings.title ||
			modalStrings.eyebrow ||
			""
		);
	}

	function buildModalContent(which, html) {
		var title = getModalTitle(which);
		var emptyText = modalStrings.empty || "The contract is not ready yet…";
		var closeLabel = modalStrings.close || "Close";
		var body = html || '<div class="kc-modal__empty">' + escapeHtml(emptyText) + "</div>";

		return (
			'<div class="kc-modal__header">' +
			'<button type="button" class="kc-modal__close" data-kc-close="' +
			which +
			'" aria-label="' +
			escapeHtml(closeLabel) +
			'">' +
			'<span class="kc-modal__close-icon" aria-hidden="true"></span>' +
			"</button>" +
			'<h2 class="kc-modal__title">' +
			escapeHtml(title) +
			"</h2>" +
			"</div>" +
			'<div class="kc-modal__body">' +
			'<div class="kc-modal__content">' +
			body +
			"</div>" +
			"</div>"
		);
	}

	function ensureModalInstance(which) {
		if (!window.tingle || !window.tingle.modal) return null;
		if (modalInstances[which]) return modalInstances[which];

		modalInstances[which] = new window.tingle.modal({
			closeMethods: ["overlay", "escape"],
			cssClass: ["kc-modal"],
		});

		return modalInstances[which];
	}

	function updateModalContent(which) {
		var modal = ensureModalInstance(which);
		if (!modal) return;
		var html = which === 1 ? modalHtml1 : modalHtml2;
		modal.setContent(buildModalContent(which, html));
	}
	
	function paymentMethodLabel() {
		var $radio = $('input[name="payment_method"]:checked');
		if (!$radio.length) return "";
		var $label = $radio.closest("li").find("label").first();
		return txt($label.text());
	}

	function billingAddress() {
		return joinParts(
			fromMap("alan_6", [
				"#billing_address_1",
				"#billing-address_1",
				'[name="billing_address_1"]',
				'[name="billing-address_1"]',
			]),
			fromMap("alan_7", [
				"#billing_address_2",
				"#billing-address_2",
				'[name="billing_address_2"]',
				'[name="billing-address_2"]',
			]),
			fromMap("alan_9", [
				"#billing_postcode",
				"#billing-postcode",
				'[name="billing_postcode"]',
				'[name="billing-postcode"]',
			]),
			fromMap("alan_11", [
				"#billing_city",
				"#billing-city",
				'[name="billing_city"]',
				'[name="billing-city"]',
			]),
			fromMap("alan_8", [
				"#select2-billing_state-container",
				"#billing_state",
				"#billing-state",
				'[name="billing_state"]',
				'[name="billing-state"]',
			], true),
			fromMap("alan_10", [
				"#select2-billing_country-container",
				"#billing_country",
				"#billing-country",
				'[name="billing_country"]',
				'[name="billing-country"]',
			], true)
		);
	}

	function shippingAddress() {
		return joinParts(
			fromMap("alan_20", [
				"#shipping_address_1",
				"#shipping-address_1",
				'[name="shipping_address_1"]',
				'[name="shipping-address_1"]',
			]) || fromMap("alan_6", [
				"#billing_address_1",
				"#billing-address_1",
				'[name="billing_address_1"]',
				'[name="billing-address_1"]',
			]),
			fromMap("alan_21", [
				"#shipping_address_2",
				"#shipping-address_2",
				'[name="shipping_address_2"]',
				'[name="shipping-address_2"]',
			]) || fromMap("alan_7", [
				"#billing_address_2",
				"#billing-address_2",
				'[name="billing_address_2"]',
				'[name="billing-address_2"]',
			]),
			fromMap("alan_22", [
				"#shipping_city",
				"#shipping-city",
				'[name="shipping_city"]',
				'[name="shipping-city"]',
			]) || fromMap("alan_11", [
				"#billing_city",
				"#billing-city",
				'[name="billing_city"]',
				'[name="billing-city"]',
			]),
			fromMap("alan_23", [
				"#shipping_postcode",
				"#shipping-postcode",
				'[name="shipping_postcode"]',
				'[name="shipping-postcode"]',
			]) || fromMap("alan_9", [
				"#billing_postcode",
				"#billing-postcode",
				'[name="billing_postcode"]',
				'[name="billing-postcode"]',
			]),
			fromMap("alan_25", [
				"#select2-shipping_state-container",
				"#shipping_state",
				"#shipping-state",
				'[name="shipping_state"]',
				'[name="shipping-state"]',
			], true) || fromMap("alan_8", [
				"#select2-billing_state-container",
				"#billing_state",
				"#billing-state",
				'[name="billing_state"]',
				'[name="billing-state"]',
			], true),
			fromMap("alan_24", [
				"#select2-shipping_country-container",
				"#shipping_country",
				"#shipping-country",
				'[name="shipping_country"]',
				'[name="shipping-country"]',
			], true) || fromMap("alan_10", [
				"#select2-billing_country-container",
				"#billing_country",
				"#billing-country",
				'[name="billing_country"]',
				'[name="billing-country"]',
			], true)
		);
	}
	
	/* Quicktag/TinyMCE ile aynı yer tutucular */
	var TOKENS = {
		"[adsoyad]": function () {
			return joinParts(
				fromMap("alan_1", [
					"#billing_first_name",
					"#billing-first_name",
					'[name="billing_first_name"]',
					'[name="billing-first_name"]',
				]),
				fromMap("alan_2", [
					"#billing_last_name",
					"#billing-last_name",
					'[name="billing_last_name"]',
					'[name="billing-last_name"]',
				])
			);
		},
		"[adi]": function () {
			return fromMap("alan_1", [
				"#billing_first_name",
				"#billing-first_name",
				'[name="billing_first_name"]',
				'[name="billing-first_name"]',
			]);
		},
		"[soyadi]": function () {
			return fromMap("alan_2", [
				"#billing_last_name",
				"#billing-last_name",
				'[name="billing_last_name"]',
				'[name="billing-last_name"]',
			]);
		},
		
		"[firmaadi]": function () {
			return txt($("#firmaadi").val());
		},
		"[firmaadresi]": function () {
			return txt($("#firmaadresi").val());
		},
		"[firmatelno]": function () {
			return txt($("#firmatelno").val());
		},
		"[firmaverdaire]": function () {
			return txt($("#firmaverdaire").val());
		},
		"[firmaverno]": function () {
			return txt($("#firmaverno").val());
		},
		
		"[alicisirket]": function () {
			return fromMap("alan_3", [
				"#billing_company",
				"#billing-company",
				'[name="billing_company"]',
				'[name="billing-company"]',
			]);
		},
		"[alicisirketvergino]": function () {
			return fromMap("alan_4", [
				"#billing_tax_number",
				"#billing-tax-number",
				"#billing_vergi_nosu",
				"#billing-vergi-nosu",
				'[name="billing_tax_number"]',
				'[name="billing-tax-number"]',
				'[name*="billing_tax_number"]',
				'[id*="billing_tax_number"]',
				'[name*="billing-tax-number"]',
				'[id*="billing-tax-number"]',
				'[name*="billing_vergi_nosu"]',
				'[id*="billing_vergi_nosu"]',
				'[name*="billing-vergi-nosu"]',
				'[id*="billing-vergi-nosu"]',
			]);
		},
		"[alicisirketvergidairesi]": function () {
			return fromMap("alan_5", [
				"#billing_tax_office",
				"#billing-tax-office",
				"#billing_vergi_dairesi",
				"#billing-vergi-dairesi",
				'[name="billing_tax_office"]',
				'[name="billing-tax-office"]',
				'[name*="billing_tax_office"]',
				'[id*="billing_tax_office"]',
				'[name*="billing-tax-office"]',
				'[id*="billing-tax-office"]',
				'[name*="billing_vergi_dairesi"]',
				'[id*="billing_vergi_dairesi"]',
				'[name*="billing-vergi-dairesi"]',
				'[id*="billing-vergi-dairesi"]',
			]);
		},
		"[sirketbilgileri]": function () {
			return joinParts(
				TOKENS["[alicisirket]"](),
				TOKENS["[alicisirketvergino]"](),
				TOKENS["[alicisirketvergidairesi]"]()
			);
		},
		
		"[adres]": function () {
			return billingAddress();
		},
		"[telefon]": function () {
			return fromMap("alan_13", [
				"#billing_phone",
				"#billing-phone",
				'[name="billing_phone"]',
				'[name="billing-phone"]',
			]);
		},
		"[email]": function () {
			return fromMap("alan_12", [
				"#billing_email",
				"#email",
				"#billing-email",
				'[name="billing_email"]',
				'[name="email"]',
				'[name="billing-email"]',
			]);
		},
		"[tc]": function () {
			return fromMap("alan_14", [
				"#billing_tc_number",
				"#billing-tc-number",
				"#shipping_tc",
				"#shipping-tc",
				'[name="billing_tc_number"]',
				'[name="billing-tc-number"]',
				'[name*="billing_tc_number"]',
				'[id*="billing_tc_number"]',
				'[name*="billing-tc-number"]',
				'[id*="billing-tc-number"]',
				'[name*="shipping_tc"]',
				'[id*="shipping_tc"]',
				'[name*="shipping-tc"]',
				'[id*="shipping-tc"]',
			]);
		},
		
		"[satin_alinan_urunler]": function () {
			return cartSummaryHTML || "";
		},
		"[sepettoplami]": function () {
			return (
				cartTotal ||
				fromMap("alan_16", "#sepettoplami") ||
				txt($("#sepettoplami").text()) ||
				txt($("#sepettoplami").val())
			);
		},
		
		"[aliciadsoyad]": function () {
			return joinParts(
				fromMap("alan_17", [
					"#shipping_first_name",
					"#shipping-first_name",
					'[name="shipping_first_name"]',
					'[name="shipping-first_name"]',
				]) ||
				fromMap("alan_1", [
					"#billing_first_name",
					"#billing-first_name",
					'[name="billing_first_name"]',
					'[name="billing-first_name"]',
				]),
				fromMap("alan_18", [
					"#shipping_last_name",
					"#shipping-last_name",
					'[name="shipping_last_name"]',
					'[name="shipping-last_name"]',
				]) ||
				fromMap("alan_2", [
					"#billing_last_name",
					"#billing-last_name",
					'[name="billing_last_name"]',
					'[name="billing-last_name"]',
				])
			);
		},
		"[alicisirketismi]": function () {
			return (
				fromMap("alan_19", [
					"#shipping_company",
					"#shipping-company",
					'[name="shipping_company"]',
					'[name="shipping-company"]',
				]) ||
				fromMap("alan_3", [
					"#billing_company",
					"#billing-company",
					'[name="billing_company"]',
					'[name="billing-company"]',
				])
			);
		},
		"[aliciadres]": function () {
			return billingAddress();
		},
		
		"[ipadresibilgisi]": function () {
			return joinParts(
				$("#musteri_ipadresi").val(),
				$("#musteri_external_ip").val()
			);
		},
		"[odemeyontemi]": function () {
			return paymentMethodLabel();
		},
		"[tarih]": function () {
			return nowTR();
		},
		
		/* geriye dönük: yazım hatası desteği */
		"[kargo_adress]": function () {
			return shippingAddress();
		},
	};

	function addTokenAlias(alias, canonical) {
		if (!TOKENS[alias] && TOKENS[canonical]) {
			TOKENS[alias] = function () {
				return TOKENS[canonical]();
			};
		}
	}

	[
		["[customer_full_name]", "[adsoyad]"],
		["[customer_first_name]", "[adi]"],
		["[customer_last_name]", "[soyadi]"],
		["[company_name]", "[firmaadi]"],
		["[company_address]", "[firmaadresi]"],
		["[company_phone]", "[firmatelno]"],
		["[company_tax_office]", "[firmaverdaire]"],
		["[company_tax_number]", "[firmaverno]"],
		["[customer_company]", "[alicisirket]"],
		["[customer_company_tax_number]", "[alicisirketvergino]"],
		["[customer_company_tax_office]", "[alicisirketvergidairesi]"],
		["[company_info]", "[sirketbilgileri]"],
		["[customer_address]", "[adres]"],
		["[billing_address]", "[adres]"],
		["[buyer_address]", "[aliciadres]"],
		["[phone]", "[telefon]"],
		["[email_address]", "[email]"],
		["[national_id]", "[tc]"],
		["[purchased_products]", "[satin_alinan_urunler]"],
		["[cart_total]", "[sepettoplami]"],
		["[shipping_full_name]", "[aliciadsoyad]"],
		["[shipping_company]", "[alicisirketismi]"],
		["[shipping_address]", "[kargo_adress]"],
		["[delivery_address]", "[kargo_adress]"],
		["[kargo_adresi]", "[kargo_adress]"],
		["[customer_ip]", "[ipadresibilgisi]"],
		["[payment_method]", "[odemeyontemi]"],
		["[date]", "[tarih]"],
		["[contract_date]", "[tarih]"],
	].forEach(function (pair) {
		addTokenAlias(pair[0], pair[1]);
	});

	var FIELD_REQUIREMENTS = [
		{
			tokens: ["[adsoyad]", "[adi]", "[customer_full_name]", "[customer_first_name]"],
			label: i18nString("field_billing_first_name", "Billing first name"),
			key: "alan_1",
			selectors: ["#billing_first_name", "#billing-first_name", '[name="billing_first_name"]', '[name="billing-first_name"]'],
		},
		{
			tokens: ["[adsoyad]", "[soyadi]", "[customer_full_name]", "[customer_last_name]"],
			label: i18nString("field_billing_last_name", "Billing last name"),
			key: "alan_2",
			selectors: ["#billing_last_name", "#billing-last_name", '[name="billing_last_name"]', '[name="billing-last_name"]'],
		},
		{
			tokens: ["[alicisirket]", "[sirketbilgileri]", "[customer_company]", "[company_info]"],
			label: i18nString("field_billing_company", "Billing company"),
			key: "alan_3",
			selectors: ["#billing_company", "#billing-company", '[name="billing_company"]', '[name="billing-company"]'],
		},
		{
			tokens: ["[alicisirketvergino]", "[sirketbilgileri]", "[customer_company_tax_number]", "[company_info]"],
			label: i18nString("field_billing_tax_number", "Billing tax number"),
			key: "alan_4",
			selectors: ["#billing_tax_number", "#billing-tax-number", "#billing_vergi_nosu", "#billing-vergi-nosu", '[name="billing_tax_number"]', '[name="billing-tax-number"]', '[name*="billing_tax_number"]', '[id*="billing_tax_number"]', '[name*="billing-tax-number"]', '[id*="billing-tax-number"]', '[name*="billing_vergi_nosu"]', '[id*="billing_vergi_nosu"]', '[name*="billing-vergi-nosu"]', '[id*="billing-vergi-nosu"]'],
		},
		{
			tokens: ["[alicisirketvergidairesi]", "[sirketbilgileri]", "[customer_company_tax_office]", "[company_info]"],
			label: i18nString("field_billing_tax_office", "Billing tax office"),
			key: "alan_5",
			selectors: ["#billing_tax_office", "#billing-tax-office", "#billing_vergi_dairesi", "#billing-vergi-dairesi", '[name="billing_tax_office"]', '[name="billing-tax-office"]', '[name*="billing_tax_office"]', '[id*="billing_tax_office"]', '[name*="billing-tax-office"]', '[id*="billing-tax-office"]', '[name*="billing_vergi_dairesi"]', '[id*="billing_vergi_dairesi"]', '[name*="billing-vergi-dairesi"]', '[id*="billing-vergi-dairesi"]'],
		},
		{
			tokens: ["[adres]", "[aliciadres]", "[customer_address]", "[billing_address]", "[buyer_address]"],
			label: i18nString("field_billing_address", "Billing address"),
			key: "alan_6",
			selectors: ["#billing_address_1", "#billing-address_1", '[name="billing_address_1"]', '[name="billing-address_1"]'],
		},
		{
			tokens: ["[adres]", "[aliciadres]", "[customer_address]", "[billing_address]", "[buyer_address]"],
			label: i18nString("field_billing_city", "Billing city"),
			key: "alan_11",
			selectors: ["#billing_city", "#billing-city", '[name="billing_city"]', '[name="billing-city"]'],
		},
		{
			tokens: ["[telefon]", "[phone]"],
			label: i18nString("field_billing_phone", "Billing phone"),
			key: "alan_13",
			selectors: ["#billing_phone", "#billing-phone", '[name="billing_phone"]', '[name="billing-phone"]'],
		},
		{
			tokens: ["[email]", "[email_address]"],
			label: i18nString("field_billing_email", "Billing email"),
			key: "alan_12",
			selectors: ["#billing_email", "#email", "#billing-email", '[name="billing_email"]', '[name="email"]', '[name="billing-email"]'],
		},
		{
			tokens: ["[tc]", "[national_id]"],
			label: i18nString("field_national_id", "National ID field"),
			key: "alan_14",
			selectors: ["#billing_tc_number", "#billing-tc-number", "#shipping_tc", "#shipping-tc", '[name="billing_tc_number"]', '[name="billing-tc-number"]', '[name*="billing_tc_number"]', '[id*="billing_tc_number"]', '[name*="billing-tc-number"]', '[id*="billing-tc-number"]', '[name*="shipping_tc"]', '[id*="shipping_tc"]', '[name*="shipping-tc"]', '[id*="shipping-tc"]'],
		},
		{
			tokens: ["[aliciadsoyad]", "[shipping_full_name]"],
			label: i18nString("field_shipping_first_name", "Shipping first name"),
			key: "alan_17",
			selectors: ["#shipping_first_name", "#shipping-first_name", '[name="shipping_first_name"]', '[name="shipping-first_name"]'],
		},
		{
			tokens: ["[aliciadsoyad]", "[shipping_full_name]"],
			label: i18nString("field_shipping_last_name", "Shipping last name"),
			key: "alan_18",
			selectors: ["#shipping_last_name", "#shipping-last_name", '[name="shipping_last_name"]', '[name="shipping-last_name"]'],
		},
		{
			tokens: ["[alicisirketismi]", "[shipping_company]"],
			label: i18nString("field_shipping_company", "Shipping company"),
			key: "alan_19",
			selectors: ["#shipping_company", "#shipping-company", '[name="shipping_company"]', '[name="shipping-company"]'],
		},
		{
			tokens: ["[kargo_adress]", "[kargo_adresi]", "[shipping_address]", "[delivery_address]"],
			label: i18nString("field_shipping_address", "Shipping address"),
			key: "alan_20",
			selectors: ["#shipping_address_1", "#shipping-address_1", '[name="shipping_address_1"]', '[name="shipping-address_1"]'],
		},
		{
			tokens: ["[kargo_adress]", "[kargo_adresi]", "[shipping_address]", "[delivery_address]"],
			label: i18nString("field_shipping_city", "Shipping city"),
			key: "alan_22",
			selectors: ["#shipping_city", "#shipping-city", '[name="shipping_city"]', '[name="shipping-city"]'],
		},
		{
			tokens: ["[odemeyontemi]", "[payment_method]"],
			label: i18nString("field_payment_method", "Payment method"),
			key: "",
			selectors: ['input[name="payment_method"]', '.wc-block-components-radio-control__input'],
		},
	];

	function templateHasAnyToken(template, tokens) {
		return tokens.some(function (token) {
			return template.indexOf(token) !== -1;
		});
	}

	function unique(values) {
		var seen = {};
		return values.filter(function (value) {
			if (seen[value]) return false;
			seen[value] = true;
			return true;
		});
	}

	function recordMissingFieldNotice() {
		if (!kcSettings.record_admin_warnings || !kcSettings.ajax_url || !kcSettings.nonce) return;

		var template = [tpl1, tpl2].join(" ");

		if (!template) {
			reportMissingFields([]);
			return;
		}

		var missing = FIELD_REQUIREMENTS.filter(function (requirement) {
			return (
				templateHasAnyToken(template, requirement.tokens) &&
				!hasMappedField(requirement.key, requirement.selectors)
			);
		}).map(function (requirement) {
			return requirement.label;
		});

		missing = unique(missing);

		if (!missing.length) {
			reportMissingFields([]);
			return;
		}

		reportMissingFields(missing);
	}

	function reportMissingFields(fields) {
		var key = fields.join("|");
		if (key === lastReportedMissingFieldsKey) return;
		lastReportedMissingFieldsKey = key;

		$.post(kcSettings.ajax_url, {
			action: "korkmaz_contract_record_missing_checkout_fields",
			nonce: kcSettings.nonce,
			fields: fields,
		});
	}
	
	function applyTokens(template) {
		if (!template) return "";
		var out = String(template);
		Object.keys(TOKENS).forEach(function (ph) {
			var val = TOKENS[ph]() || "";
			var escaped = ph.replace(/[[\]]/g, function (m) {
				return "\\" + m;
			});
			out = out.replace(new RegExp(escaped, "g"), val);
		});
		return out;
	}
	
	function renderModal(which, html) {
		if (!which || !html) return;
		/* Sunucuya gereksiz istek atmayı önlemek için, içerik değişmediyse istek atma */
			$.ajax({
				url: ajaxURL,
				type: "POST",
				data: { action: "modal_metin_duzenle", metin: html, nonce: ajaxNonce },
			}).done(function (res) {
			if (which === 1) {
				modalHtml1 = res;
			} else if (which === 2) {
				modalHtml2 = res;
			}
			updateModalContent(which);
		});
	}
	
	/* Kendi tetiklediğimiz değişiklikleri yoksaymak için özel köken parametresi kullanıyoruz */
	function runUpdateImmediate() {
		if (isUpdating) return;
		isUpdating = true;
		ensureClassicHiddenFields();
		
		try {
			if (tpl1) {
				var filled1 = applyTokens(tpl1);
				if (filled1 !== lastRendered1) {
					renderModal(1, filled1);
					if ($fieldBir.length && $fieldBir.val() !== filled1) {
						$fieldBir.val(filled1); // .trigger('change') YOK – döngüye sebep oluyordu
					}
					lastRendered1 = filled1;
				}
			}
			
			if (tpl2) {
				var filled2 = applyTokens(tpl2);
				if (filled2 !== lastRendered2) {
					renderModal(2, filled2);
					if ($fieldIki.length && $fieldIki.val() !== filled2) {
						$fieldIki.val(filled2); // .trigger('change') YOK – döngüye sebep oluyordu
					}
					lastRendered2 = filled2;
				}
			}
		} finally {
			recordMissingFieldNotice();
			isUpdating = false;
		}
	}
	
	var update = debounce(runUpdateImmediate, 400);

	ensureClassicHiddenFields();
	syncModalTitles();
	fetchCartSummary(update);

	/* Şablonları yükle (tek sefer) */
		$.ajax({
			url: ajaxURL,
			type: "POST",
			dataType: "json",
			data: { action: "metin_getir", nonce: ajaxNonce },
		}).done(function (resp) {
		tpl1 = resp && resp.birinci ? resp.birinci : "";
		tpl2 = resp && resp.ikinci ? resp.ikinci : "";
		update();
	});
	
	/* Checkout olayları */
	$(document)
		.on(
			"input change",
			"form.checkout input, form.checkout select, form.checkout textarea",
			function () {
				if (!isUpdating) update();
			}
		)
		.on(
			"updated_checkout updated_cart_totals wc-credit-card-form-init payment_method_selected",
			function () {
				if (!isUpdating) fetchCartSummary(update);
				syncModalTitles();
			}
		);
	
	/* Son anda form submit edildiğinde güncel alanları yakala */
	$(document).on("checkout_place_order", function () {
		runUpdateImmediate();
	});
	$(document).on("submit", "form.checkout", function () {
		runUpdateImmediate();
	});
	
	/* Müşteri tipi görünürlük (mevcut davranış korunur) */
	function musteriTipiKontrol() {
		var $grp = $('input[name="musteri_tipi"]');
		if (!$grp.length) return;
		var tip = $grp.filter(":checked").val();
		if (tip === "bireysel") {
			$("#shipping_tc_field").show().find("input").prop("required", true);
			$("#shipping_tc_field .optional")
				.removeClass("optional")
				.addClass("required")
				.html('<abbr class="required" title="' + escapeHtml(i18nString("required", "required")) + '">*</abbr>');
			$(
				"#billing_company_field,#billing_vergi_dairesi_field,#billing_vergi_nosu_field"
			)
				.hide()
				.find("input")
				.prop("required", false);
			$(
				"#billing_company_field .required,#billing_vergi_dairesi_field .required,#billing_vergi_nosu_field .required"
			)
				.removeClass("required")
				.addClass("optional")
				.text(i18nString("optional", "optional"));
		} else {
			$("#shipping_tc_field").hide().find("input").prop("required", false);
			$("#shipping_tc_field .required")
				.removeClass("required")
				.addClass("optional")
				.text(i18nString("optional", "optional"));
			$(
				"#billing_company_field,#billing_vergi_dairesi_field,#billing_vergi_nosu_field"
			)
				.show()
				.find("input")
				.prop("required", true);
			$(
				"#billing_company_field .optional,#billing_vergi_dairesi_field .optional,#billing_vergi_nosu_field .optional"
			)
				.removeClass("optional")
				.addClass("required")
				.html('<abbr class="required" title="' + escapeHtml(i18nString("required", "required")) + '">*</abbr>');
		}
	}
	musteriTipiKontrol();
	$(document).on("change", 'input[name="musteri_tipi"]', musteriTipiKontrol);
	
	function openContractModal(which) {
		var modal = ensureModalInstance(which);
		if (!modal) return;
		updateModalContent(which);
		modal.open();
	}

	function resolveModalWhich($link) {
		var dataWhich = parseInt($link.data("kc-modal"), 10);
		if (dataWhich === 1 || dataWhich === 2) return dataWhich;
		var href = ($link.attr("href") || "").toString();
		if (href.indexOf("kc-modal-2") !== -1) return 2;
		return 1;
	}

	$(document).on(
		"click",
		'.kc-contract-link, [data-kc-modal], a[href="#kc-modal-1"], a[href="#kc-modal-2"]',
		function (e) {
			e.preventDefault();
			e.stopPropagation();
			var $link = $(this);
			var which = resolveModalWhich($link);
			var label = txt($link.text());
			if (label) modalTitles[which] = label;
			openContractModal(which);
		}
	);

	$(document).on(
		"keydown",
		'.kc-contract-link, [data-kc-modal], a[href="#kc-modal-1"], a[href="#kc-modal-2"]',
		function (e) {
			if (e.key === "Enter" || e.key === " ") {
				e.preventDefault();
				e.stopPropagation();
				var $link = $(this);
				var which = resolveModalWhich($link);
				var label = txt($link.text());
				if (label) modalTitles[which] = label;
				openContractModal(which);
			}
		}
	);

	$(document).on("click", ".kc-modal__close", function (e) {
		e.preventDefault();
		e.stopPropagation();
		var which = parseInt($(this).data("kc-close"), 10);
		if (which && modalInstances[which]) {
			modalInstances[which].close();
		}
	});
})(jQuery);
