document.addEventListener('DOMContentLoaded', function () { const phoneInput = document.querySelector('input[name="phone"]'); const confirmBtn = document.getElementById('confirm_order'); if (!phoneInput || !confirmBtn) return; const STATE = { internalChange: false, activated: false }; function normalizePhone(val) { let v = (val || '').replace(/\D+/g, ''); if (v.length > 9) v = v.slice(0, 9); return v; } function isValidPhone() { return normalizePhone(phoneInput.value).length === 9; } function setBtnDisabled(disabled) { if (confirmBtn.disabled !== disabled) { STATE.internalChange = true; // znacznik: to nasza zmiana confirmBtn.disabled = disabled; STATE.internalChange = false; } } function applyPhoneValidation() { const normalized = normalizePhone(phoneInput.value); if (phoneInput.value !== normalized) phoneInput.value = normalized; if (isValidPhone()) { phoneInput.classList.remove('alert'); setBtnDisabled(false); } else { phoneInput.classList.add('alert'); setBtnDisabled(true); } } // Aktywacja dopiero przy pierwszym focusie phoneInput.addEventListener('focus', function onFirstFocus() { if (STATE.activated) return; STATE.activated = true; phoneInput.addEventListener('input', applyPhoneValidation, { passive: true }); // pierwsze sprawdzenie – bez emitowania zdarzeń, by nie triggerować cudzych handlerów applyPhoneValidation(); // Pilnowanie przycisku, gdy inny skrypt zmieni jego stan const observer = new MutationObserver(function (mutations) { if (STATE.internalChange) return; // ignoruj nasze własne zmiany // Tylko jeśli numer niepoprawny – wymuś blokadę if (!isValidPhone()) setBtnDisabled(true); }); observer.observe(confirmBtn, { attributes: true, attributeFilter: ['disabled'] }); }, { once: true }); });