<!-- ========================================================================= -->
<!-- 🎈 ЧАСТЬ 1: SaaS-ЯДРО, МГНОВЕННЫЙ СБРОС НУЛЕЙ, СЛУШАТЕЛИ КАЛЬКУЛЯТОРА v40.0 -->
<!-- ========================================================================= -->
<script>



// Центральный бэкенд-шлюз Google Apps Script (Ядро библиотеки)
var GOOGLE_SCRIPT_URL = 'https://script.google.com/macros/s/AKfycbyCCpCWjCRIKMNwR5JmHHyWBH7ZihmQzrBtKQwx_CXDqlnmDI1UlIKdbF2vM-X45K-6/exec';

// Глобальное ОЗУ-состояние системы Balloon CRM
window.st = { isLoading: true, catalog: [], deals: [], expenses: [], payments: [], team: [], statuses: [], clients: [], marketing_channels: [], role: 'staff', login: 'admin', sheetId: '', compName: '' };
window.currentStatusFilter = 'all'; // Принудительный эталонный нижний регистр для старта
window.frozenPricesMemory = {};
window.customServicesCount = 0;

// Переменные накопительной постраничной пагинации (Лимит 30 записей)
window.crmDealsLimit = 30;
window.crmClientsLimit = 30;

window.openCrmGoogleSheet = function() {
if (window.st && window.st.sheetId) {
var googleSheetUrl = "https://docs.google.com/spreadsheets/d/" + window.st.sheetId;
window.open(googleSheetUrl, '_blank');
} else {
alert("🛑 Ошибка: Не удалось определить ID Google Таблицы. Проверьте авторизацию в CRM.");
}
};


// ✅ ВСПОМОГАТЕЛЬНАЯ ФУНКЦИЯ: Конвертирует ГГГГ-ММ-ДД в ДД.ММ.ГГГГ
window.formatCrmDateToRu = function(dateStr) {
var cleanStr = String(dateStr || '').trim();
if (!cleanStr || cleanStr === 'undefined' || cleanStr === 'null' || cleanStr.indexOf('-') === -1) {
return cleanStr || 'не указано';
}
if (cleanStr.indexOf('T') !== -1) { cleanStr = cleanStr.split('T')[0]; }
var parts = cleanStr.split('-');
if (parts.length !== 3) return cleanStr;
return parts[2] + '.' + parts[1] + '.' + parts[0]; // Результат: День.Месяц.Год
};

// 1. АВТОМАТИЧЕСКАЯ ИНИЦИАЛИЗАЦИЯ И ЖИВЫЕ СЛУШАТЕЛИ КЛИКОВ
document.addEventListener("DOMContentLoaded", function() {
initAppTabsLogic();
checkSavedSession();
// Логика управления модальным окном быстрого добавления клиента
var modal = document.getElementById("crmAddClientModal");
var btnOpen = document.getElementById("btnOpenAddClientModal");
var btnClose = document.getElementById("btnCloseAddClientModal");
var btnCancel = document.getElementById("btnCancelAddClient");

if (btnOpen && modal) {
btnOpen.addEventListener("click", function(e) {
if (e) e.preventDefault();
var form = document.getElementById("crmAddClientForm");
if (form) form.reset();

// Автоподстановка сегодняшней даты в календарь
var dateInput = document.getElementById("modalClientLastDate");
if (dateInput) {
var today = new Date();
var yyyy = today.getFullYear();
var mm = String(today.getMonth() + 1).padStart(2, '0');
var dd = String(today.getDate()).padStart(2, '0');
dateInput.value = yyyy + '-' + mm + '-' + dd;
}
modal.style.display = "flex";
});
}

var closeModal = function(e) {
if (e) e.preventDefault();
if (modal) modal.style.display = "none";
};

if (btnClose) btnClose.addEventListener("click", closeModal);
if (btnCancel) btnCancel.addEventListener("click", closeModal);
if (modal) {
modal.addEventListener("click", function(e) {
if (e.target === modal) closeModal(e);
});
}


// Переименовываем вкладку Расходы для красоты интерфейса
document.querySelectorAll('#nav-tabs .tab-btn').forEach(function(btn) {
if (btn.dataset.tab === 'expenses' || btn.innerText.indexOf('Расходы') !== -1) {
btn.innerHTML = '₽ Расходы';
}
});

var loginBtn = document.getElementById('login-btn');
var linkToReg = document.getElementById('link-to-reg');
var linkToLogin = document.getElementById('link-to-login');
var compGroup = document.getElementById('comp-group');
var authErr = document.getElementById('auth-err');

// 🔄 Оживляем переключатели режимов формы (Вход / Регистрация)
if (linkToReg && linkToLogin && compGroup && loginBtn) {
linkToReg.addEventListener('click', function(e) {
e.preventDefault();
if (authErr) authErr.innerText = '';
compGroup.style.display = 'block';
linkToReg.style.display = 'none';
linkToLogin.style.display = 'inline';
loginBtn.innerText = 'Зарегистрироваться';
});

linkToLogin.addEventListener('click', function(e) {
e.preventDefault();
if (authErr) authErr.innerText = '';
compGroup.style.display = 'none';
linkToReg.style.display = 'inline';
linkToLogin.style.display = 'none';
loginBtn.innerText = 'Войти в систему';
});
}

// 🚀 Умная кнопка: определяет Вход или Регистрация
if (loginBtn) {
loginBtn.onclick = function(e) {
if (e && e.preventDefault) e.preventDefault();

// 🔒 ПЕРЕХВАТ РЕЖИМА ВОССТАНОВЛЕНИЯ ПАРОЛЯ БЕЗ УЩЕРБА ДЛЯ РЕГИСТРАЦИИ v50.0
var currentBtnText = loginBtn ? loginBtn.innerText : '';
if (currentBtnText === 'Восстановить и выслать пароль') {
if (typeof window.handleCrmAuthSubmit === 'function') {
window.handleCrmAuthSubmit();
}
return; // Мгновенно останавливаем выполнение, не пуская код во Вход/Регистрацию!
}

var email = document.getElementById('login-input').value.trim();
var pass = document.getElementById('pass-input').value.trim();
var compName = document.getElementById('auth-comp') ? document.getElementById('auth-comp').value.trim() : '';
var isRegisterMode = (compGroup && compGroup.style.display === 'block');

// 🔥 БРОНЕБОЙНАЯ SaaS-БЛОКИРОВКА НЕВЕРНЫХ EMAIL НА ХОДУ
var emailInputField = document.getElementById('login-input');
if (emailInputField && typeof window.validateCrmEmailField === 'function') {
if (!window.validateCrmEmailField(emailInputField)) {
if (authErr) authErr.innerText = "❌ Ошибка: Введите корректный Email со знаком '@' и точкой (например: name@mail.ru)!";
emailInputField.style.borderColor = '#d93025';
emailInputField.focus();
return; // Намертво гасим отправку неверного Email в Google Ядро!
}
}

if (!email || !pass) {
if (authErr) authErr.innerText = '⚠ Заполните логин и пароль!';
return;
}

if (authErr) authErr.innerText = '⏳ Секунду, отправляем запрос...';

if (isRegisterMode) {
if (authErr) authErr.innerText = '⏳ Секунду, создаем ваш личный кабинет...';

var payload = {
action: 'register',
email: email,
password: pass,
compName: compName || 'Студия аэродизайна'
};

// 🎯 Включаем локальный триггер: мы регистрируем эту почту прямо сейчас!
window.crmJustRegistered = email.toLowerCase().trim();

fetch(GOOGLE_SCRIPT_URL, {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify(payload)
})
.then(function() {
// Быстрый фоновый микро-запрос для мгновенной проверки записи в Мастере
var checkUrl = GOOGLE_SCRIPT_URL + "?act=refresh&sheetId=15lc3jj5D4eadrrx0amG-rOE0yCPo2D1P51Hu-T-aV0c&login=" + encodeURIComponent(email);

var xhr = new XMLHttpRequest();
xhr.open("GET", checkUrl, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var serverResponse = xhr.responseText;

// 🟢 ЕСЛИ ПОЧТА НАЙДЕНА И ЭТО МЫ ТОЛЬКО ЧТО ЕЁ СОЗДАЛИ — БЕСШОВНО ВХОДИМ!
if (window.crmJustRegistered === email.toLowerCase().trim()) {
window.crmJustRegistered = false; // сбрасываем триггер

if (authErr) authErr.innerText = '';
alert("🎉 Поздравляем! Ваш личный кабинет Balloon CRM успешно создан.\n\nДоступы и инструкция уже отправлены роботом на вашу почту. Сейчас система автоматически авторизует вас.");

if (typeof loginCRM === 'function') { loginCRM(); }
}
// ⛔ ЕСЛИ ПОЧТА НАЙДЕНА, НО МЫ ЕЁ НЕ СОЗДАВАЛИ СЕЙЧАС — ЭТО РЕАЛЬНЫЙ ДУБЛИКАТ!
else if (serverResponse.indexOf("wrong_credentials") !== -1 || serverResponse.indexOf("base_crm") !== -1) {
window.crmJustRegistered = false;
if (authErr) authErr.innerText = "🛑 Ошибка: Этот Email уже зарегистрирован в системе! Используйте форму восстановления пароля.";
alert("🛑 Этот Email уже зарегистрирован в системе CRM!\n\nIf вы забыли доступы, нажмите кнопку 'Забыли пароль?' на экране входа, и робот повторно вышлет их вам.");
location.reload();
}
}
};
xhr.send();
})
.catch(function(err) {
if (authErr) authErr.innerText = '❌ Ошибка отправки данных сети';
});
} else {
// РЕЖИМ ОБЫЧНОГО ВХОДА
if (typeof loginCRM === 'function') loginCRM();
}
};
}

var saveBtn = document.getElementById('save-deal-btn'); if (saveBtn) saveBtn.onclick = window.saveDealToServer;
var delBtn = document.getElementById('delete-deal-btn'); if (delBtn) delBtn.onclick = window.deleteDealFromServer;

document.addEventListener('click', function(e) {
if (e.target && (e.target.id === 'save-exp-btn' || e.target.closest('#save-exp-btn'))) {
window.saveExpensesToServer();
}
});

// Навешиваем живой трекер телефона на поле ввода карточки заказа
var phoneInp = document.getElementById('f-phone');
if (phoneInp) {
phoneInp.addEventListener("input", window.checkLivePhoneTrigger);
}

// Навешиваем авто-исчезновение финансовых нулей при клике
window.initFinancialFieldsFix();

// Навешиваем слушатель на кнопку "+ Добавить заказ"
var addBtn = document.getElementById('tab-add-deal-btn');
if (addBtn) {
addBtn.addEventListener("click", function() {
var rowInp = document.getElementById('f-row'); if (rowInp) rowInp.value = '0';
var fTitle = document.getElementById('form-title'); if (fTitle) fTitle.innerText = 'Новая карточка клиента';
var dBtn = document.getElementById('delete-deal-btn'); if (dBtn) dBtn.style.display = 'none';
var badgeBox = document.getElementById('live-phone-badge'); if (badgeBox) badgeBox.style.display = 'none';
window.frozenPricesMemory = {};
resetFormFields();
window.renderAllElements();
});
}
});

// ✅ УМНАЯ ЛОГИКА ВКЛАДОК CRM С ПАМЯТЬЮ ПОСЛЕ ПЕРЕЗАГРУЗКИ СТРАНИЦЫ
function initAppTabsLogic() {
document.querySelectorAll('#nav-tabs .tab-btn').forEach(function(btn) {
window.scrollTo(0, 0);
if (window.saveScrollPos) window.saveScrollPos = 0;
localStorage.setItem('crm_scroll_pos', '0');

btn.onclick = function() {
var tabName = btn.dataset.tab;
localStorage.setItem('active_crm_tab', tabName); // Намертво запоминаем вкладку в браузере
document.querySelectorAll('#nav-tabs .tab-btn, .tab-panel').forEach(function(el) { el.classList.remove('active'); });
btn.classList.add('active');
var targetPanel = document.getElementById('tab-' + tabName);
if (targetPanel) targetPanel.classList.add('active');
if (tabName === 'crmcalendar') window.renderCrmCalendar();
if (tabName === 'customers') {
window.crmClientsLimit = 30;
if (!window.st.clients || window.st.clients.length === 0) {
var container = document.getElementById('customers-list-container');
if (container) container.innerHTML = '<div style="color:#999; text-align:center; padding:20px;">⏳ Синхронизация сквозной базы... Секунду.</div>';
var checkDatabaseInterval = setInterval(function() {
if (window.st.clients && window.st.clients.length > 0) {
clearInterval(checkDatabaseInterval);
window.renderCustomersTab();
}
}, 200);
} else {
window.renderCustomersTab();
}
}
if (tabName === 'deals') { window.crmDealsLimit = 30; if (typeof window.renderStatusTabs === 'function') window.renderStatusTabs(); if (typeof renderDealsList === 'function') renderDealsList(); }
if (tabName === 'profile' && typeof window.renderCrmTeamList === 'function') window.renderCrmTeamList();
if (tabName === 'analytics' && typeof renderAnalytics === 'function') renderAnalytics();
if (tabName === 'expenses' && typeof window.renderExpensesTab === 'function') window.renderExpensesTab();
if (tabName === 'products' && typeof window.crmRenderProductsTab === 'function') window.crmRenderProductsTab();
};
});

// Автоматический возврат на вкладку, где работал пользователь до обновления страницы
var savedTab = localStorage.getItem('active_crm_tab') || 'deals';
var targetBtn = document.querySelector('#nav-tabs .tab-btn[data-tab="' + savedTab + '"]');
if (targetBtn) {
targetBtn.click();
}
}


// 🎯 УМНЫЙ ПЕРЕХВАТ КЛИКОВ ВНУТРИ ГЕНЕРИРУЕМОГО КАЛЬКУЛЯТОРА ТОВАРОВ
// Позволяет запускать расчеты мгновенно по событию change, не дожидаясь изменения количества
window.attachLiveCalculatorClickListeners = function() {
document.querySelectorAll('.p-chk').forEach(function(chk) {
if (!chk.dataset.hasListener) {
chk.dataset.hasListener = "true";
chk.addEventListener('change', function() {
window.recalcDealTotal(); // Живой мгновенный пересчет при клике на галочку!
});
}
});
};

// Умный трекер телефона — вывод зеленого бейджа «Повторный» на лету при создании заказа
window.checkLivePhoneTrigger = function() {
var phoneInp = document.getElementById('f-phone'); if (!phoneInp) return;
var cleanVal = phoneInp.value.replace(/\D/g, '');
var badgeBox = document.getElementById('live-phone-badge');
if (!badgeBox) {
badgeBox = document.createElement('span');
badgeBox.id = 'live-phone-badge';
badgeBox.style.cssText = 'display:none; background:#25d366; color:#fff; font-size:11px; font-weight:700; padding:3px 8px; border-radius:4px; margin-left:10px; text-transform:uppercase; vertical-align:middle;';
badgeBox.innerText = 'Повторный';
phoneInp.parentNode.insertBefore(badgeBox, phoneInp.nextSibling);
}

// КРИТЕРИЙ: Проверяем, есть ли этот клиент уже в базе прошлых успешных заказов
var isRepeat = window.st.clients.some(function(c) { return c.cleanPhone === cleanVal; });
badgeBox.style.display = isRepeat ? 'inline-block' : 'none';
};

function loginCRM() {
var lInp = document.getElementById('login-input');
var pInp = document.getElementById('pass-input');
var err = document.getElementById('auth-err');

if (!lInp || !pInp) return;

var l = lInp.value.trim();
var p = pInp.value.trim();

if (!l || !p) {
if (err) err.innerText = "⚠ Заполните поля!";
return;
}

if (err) err.innerText = "Вход...";

// 🔥 ФИКС ОЧЕРЕДИ: Ждем 50мс, чтобы все вынесенные блоки T123 гарантированно склеились в памяти браузера
setTimeout(function() {
if (typeof sendJsonRequest === 'function') {
sendJsonRequest({ act: 'login', login: l, pass: p });
} else if (typeof window.sendJsonRequest === 'function') {
window.sendJsonRequest({ act: 'login', login: l, pass: p });
} else {
if (err) err.innerText = "❌ Системная ошибка: Шлюз отправки недоступен. Перезагрузите страницу.";
}
}, 50);
}


function sendJsonRequest(params) {
var callbackName = 'balloon_cb_' + Math.floor(Math.random() * 100000);

window[callbackName] = function(response) {
var el = document.getElementById(callbackName);
if (el) el.remove();
delete window[callbackName];

if (response) {
// 🔒 1. ПЕРЕХВАТ ТРИАЛА И БЛОКИРОВОК ПОДПИСКИ
if (response && (response.error === "subscription_expired" || response.error === "account_blocked")) {
localStorage.clear();

var appInterface = document.getElementById('app-interface'); if (appInterface) appInterface.style.display = 'none';
var authScreen = document.getElementById('auth-screen'); if (authScreen) authScreen.style.display = 'none';

var userSheetId = response.sheetId || window.crm_sheet_id || localStorage.getItem('balloon_sheet_id') || "";
var tableLinkHtml = "";

if (userSheetId && userSheetId !== "" && userSheetId !== "undefined") {
var fullTableUrl = "https://google.com" + userSheetId + "/edit";
tableLinkHtml = ' (<a href="' + fullTableUrl + '" target="_blank" style="color: #007bff; font-weight: bold; text-decoration: underline;">открыть таблицу ↗️</a>)';
}

var lockScreen = document.createElement('div');
lockScreen.id = "crm-lock-screen-modal";
lockScreen.style.cssText = 'position:fixed; top:0; left:0; width:100%; height:100%; background:#f4f6f9; z-index:999999; display:flex; justify-content:center; align-items:center; box-sizing:border-box; padding:20px;';

lockScreen.innerHTML =
'<div style="max-width:480px; width:100%; background:#fff; padding:35px 25px; border-radius:12px; box-shadow:0 10px 25px rgba(0,0,0,0.08); font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif; text-align:center; box-sizing:border-box;">' +
'<div style="font-size:45px; margin-bottom:15px; line-height:1;">⏳</div>' +
'<h3 style="margin:0 0 15px 0; font-size:18px; color:#e53e3e; font-weight:700; line-height:1.4; text-transform:uppercase; letter-spacing:0.5px;">Срок действия триал-периода или подписки ИСТЕК</h3>' +
'<p style="margin:0 0 20px 0; font-size:14px; color:#4a5568; line-height:1.6; text-align:left;">' +
'Ваша изолированная база находится в полной безопасности в вашем облаке Google' + tableLinkHtml + ', но доступ к интерфейсу CRM временно заблокирован.' +
'</p>' +
'<p style="margin:0 0 25px 0; font-size:14px; color:#4a5568; line-height:1.6; text-align:left; font-weight:500;">' +
'Для продления доступа обратитесь к администратору платформы.' +
'</p>' +
// КНОПКА 1. TELEGRAM С АВТО-ТЕКСТОМ СЛОВАМИ ПРЕДЫДУЩЕГО ТЗ
'<div style="width:100%; box-sizing:border-box;">' +
'<a href="https://t.me/k_andrey_sv" target="_blank" style="display:block; background:#0088cc; color:#fff; text-decoration:none; padding:12px 20px; border-radius:8px; font-weight:700; font-size:15px; box-shadow:0 4px 12px rgba(0,136,204,0.2); transition:background 0.2s; text-align:center; box-sizing:border-box; width:100%;">💬 Написать в Telegram</a>' +
'</div>' +

// КНОПКА 2. MAX С ОТСТУПОМ 12PX И СВОИМ АВТО-ТЕКСТОМ (ЗАМЕНИТЕ ССЫЛКУ НА СВОЮ, ЕСЛИ НАДО)
'<div style="width:100%; margin-top: 12px; box-sizing:border-box;">' +
'<a href="https://max.ru/u/f9LHodD0cOI3Z6ohO8FzsGRU6UCJ25r3CbvzbAWm2Om10DA9PevB71kw4Vo" target="_blank" style="display:block; background:#0088cc; color:#fff; text-decoration:none; padding:12px 20px; border-radius:8px; font-weight:700; font-size:15px; box-shadow:0 4px 12px rgba(0,136,204,0.2); transition:background 0.2s; text-align:center; box-sizing:border-box; width:100%;">💬 Написать в MAX</a>' +
'</div>' +

'</div>';

var oldLock = document.getElementById('crm-lock-screen-modal'); if (oldLock) oldLock.remove();
document.body.appendChild(lockScreen);
return;
}


// 💾 2. ЕСЛИ ЭТО БЫЛ ВХОД (LOGIN) — ЗАПИСЫВАЕМ ВСЕ ВАРИАНТЫ КЛЮЧЕЙ СЕССИИ В ПАМЯТЬ
if (params && params.act === 'login' && response.success) {
localStorage.setItem('balloon_sheet_id', response.sheetId);
localStorage.setItem('balloon_login', response.login);
localStorage.setItem('crm_sheet_id', response.sheetId);
localStorage.setItem('crm_login', response.login);
localStorage.setItem('crm_user_role', response.role || 'owner');

if (!window.st) window.st = {};
window.st.sheetId = response.sheetId;
window.st.login = response.login;
window.st.role = response.role || 'owner';
}

// 🔥 МГНОВЕННЫЙ ТРИГГЕР: Вызываем чтение базы сразу после авторизации
if (params && params.act === 'login' && response.success) {
// 🔥 SaaS-ПЕРЕКЛЮЧАТЕЛЬ ЭКРАНОВ: На лету открываем интерфейс CRM, пряча форму входа
var loginBox = document.getElementById('auth-screen') || document.getElementById('auth-block') || document.querySelector('.v-group').parentNode.parentNode;
if (loginBox) loginBox.style.display = 'none';

var crmUi = document.getElementById('app-interface') || document.getElementById('main-crm-app');
if (crmUi) crmUi.style.display = 'block';

// Отправляем моментальный запрос на выгрузку сделок
sendJsonRequest({ act: 'refresh', id: response.sheetId, sheetId: response.sheetId, login: response.login, owner: response.login });

} else if (typeof window.refreshCB === 'function') {
window.refreshCB(response);
}
}
};

// Автоподстановка ID таблицы при фоновом обновлении
params.callback = callbackName;
var savedId = localStorage.getItem('balloon_sheet_id') || localStorage.getItem('crm_sheet_id') || localStorage.getItem('sheetId');
if (savedId && !params.id && !params.sheetId) {
params.id = savedId;
params.sheetId = savedId;
}

// Формируем тег скрипта для отправки GET/JSONP запроса в сеть Google
var script = document.createElement('script');
script.id = callbackName;
script.src = GOOGLE_SCRIPT_URL + '?' + Object.keys(params).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
}).join('&');

document.body.appendChild(script);
}


// =========================================================================
// 🔐 SaaS-МОДУЛЬ АВТОРИЗАЦИИ, ВАЛИДАЦИИ И СБРОСА ПАРОЛЕЙ v50.0
// =========================================================================

// 🧼 1. ОРИГИНАЛЬНАЯ ФУНКЦИЯ ВАЛИДАЦИИ EMAIL ДЛЯ ОЧИСТКИ КОНСОЛИ
window.validateCrmEmailField = function(inputElement) {
if (!inputElement || !inputElement.value) return false;
var emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
var isValid = emailReg.test(inputElement.value.trim());

// Меняем цвет рамки динамически (поддерживает любой регистр букв)
inputElement.style.borderColor = isValid ? "#dadce0" : "#ff4d4f";
return isValid;
};

// 🔄 2. ОРИГИНАЛЬНАЯ ФУНКЦИЯ ПЕРЕКЛЮЧЕНИЯ В РЕЖИМ ВОССТАНОВЛЕНИЯ ПАРОЛЯ
window.toggleCrmForgotMode = function(linkElement) {
var passGroup = document.getElementById('pass-group');
var compGroup = document.getElementById('comp-group');
var loginBtn = document.getElementById('login-btn');
var authErr = document.getElementById('auth-err');

if (authErr) authErr.innerText = '';
if (compGroup) compGroup.style.display = 'none'; // Скрываем регистрацию, если была открыта

if (passGroup && passGroup.style.display !== 'none') {
// Переключаем в режим восстановления
passGroup.style.display = 'none';
if (loginBtn) loginBtn.innerText = 'Восстановить и выслать пароль';
if (linkElement) linkElement.innerText = 'Вернуться ко входу';
} else {
// Возвращаем в режим обычного входа
if (passGroup) passGroup.style.display = 'block';
if (loginBtn) loginBtn.innerText = 'Войти в систему';
if (linkElement) linkElement.innerText = 'Забыли пароль?';
}
};

// 🔐 3. ОРИГИНАЛЬНЫЙ ДВИЖОК ОТПРАВКИ ЗАПРОСА ВОССТАНОВЛЕНИЯ НА БЭКЕНД
window.handleCrmAuthSubmit = function() {
var emailInput = document.getElementById('login-input');
var authErr = document.getElementById('auth-err');
var loginBtn = document.getElementById('login-btn');
var email = emailInput ? emailInput.value.trim() : '';

if (!window.validateCrmEmailField(emailInput)) {
if (authErr) authErr.innerText = '⚠️ Введите корректный Email!';
return;
}

if (loginBtn) { loginBtn.disabled = true; loginBtn.innerText = '⏳ Отправляем...'; }
if (authErr) { authErr.style.color = '#1a73e8'; authErr.innerText = '⏳ Робот проверяет базу данных...'; }

// Формируем POST JSON запрос под архитектуру вашей регистрации
var payload = {
action: "forgot_password",
email: email
};

fetch(GOOGLE_SCRIPT_URL, {
method: 'POST',
body: JSON.stringify(payload)
})
.then(function(res) { return res.text(); }) // Считываем ответ от базы как чистый текст
.then(function(responseText) {
if (loginBtn) { loginBtn.disabled = false; loginBtn.innerText = 'Восстановить и выслать пароль'; }

// Если бэкенд Google Таблицы успешно записал флаг PENDING и вернул success
if (responseText && responseText.indexOf("success") !== -1) {
if (authErr) {
authErr.style.color = '#25d366'; // Красивый зеленый статус успеха
authErr.innerHTML = '🎉 <b>Готово!</b> Пароль успешно отправлен на почту ' + email;
}
alert("🎈 Запрос на восстановление отправлен!\n\nПроверьте почту через 1-2 минуты.");
} else {
if (authErr) {
authErr.style.color = '#d93025';
authErr.innerHTML = '🛑 <b>Ошибка:</b> Пользователь с таким Email не найден в реестре CRM.';
}
}
})
.catch(function(err) {
if (loginBtn) { loginBtn.disabled = false; loginBtn.innerText = 'Восстановить и выслать пароль'; }
if (authErr) { authErr.style.color = '#d93025'; authErr.innerText = '❌ Ошибка сети с сервером Google.'; }
console.error("Критическая ошибка fetch:", err);
});
};


function checkSavedSession() {
// Считываем и старые, и новые ключи сессии для идеальной стабильности
var sId = localStorage.getItem('balloon_sheet_id') || localStorage.getItem('crm_sheet_id') || localStorage.getItem('sheetId');
var uLog = localStorage.getItem('balloon_login') || localStorage.getItem('crm_login') || localStorage.getItem('login');
var uRole = localStorage.getItem('crm_user_role') || localStorage.getItem('role') || 'owner';

if (sId && uLog) {
if (!window.st) window.st = {};
window.st.sheetId = sId;
window.st.login = uLog;
window.st.role = uRole;

var aScr = document.getElementById('auth-screen'); if (aScr) aScr.style.display = 'none';
var aInt = document.getElementById('app-interface'); if (aInt) aInt.style.display = 'block';

// 🟢 ВНУТРИ CRM: Показываем кнопку перехода в Excel
var sheetBtnBox = document.getElementById('open-spreadsheet-box');
if (sheetBtnBox) sheetBtnBox.style.display = 'block';

sendJsonRequest({ act: 'refresh', id: sId, sheetId: sId, login: uLog, owner: uLog });
} else {
var aScr = document.getElementById('auth-screen'); if (aScr) aScr.style.display = 'block';
var aInt = document.getElementById('app-interface'); if (aInt) aInt.style.display = 'none';

// 🔴 НА ЭКРАНЕ ВХОДА: Намертво прячем кнопку
var sheetBtnBox = document.getElementById('open-spreadsheet-box');
if (sheetBtnBox) sheetBtnBox.style.display = 'none';
}

}



// Идеальная очистка формы бланка, аккордеонов и убирание 12:00
function resetFormFields() {
var f = document.getElementById('tab-form'); if (!f) return;
f.querySelectorAll('input[type="text"], input[type="number"], input[type="date"], input[type="tel"], textarea').forEach(function(i) { i.value = ''; });
var timeInp = document.getElementById('f-time-deliv'); if (timeInp) timeInp.value = ''; // СТРОГО ПУСТОЕ ВРЕМЯ КУРСОРA!

var discInp = document.getElementById('f-disc'); if (discInp) discInp.value = '0';
var delivInp = document.getElementById('f-deliv-sum'); if (delivInp) delivInp.value = '0';
var prepayInp = document.getElementById('f-prepay'); if (prepayInp) prepayInp.value = '0';

f.querySelectorAll('.p-chk').forEach(function(chk) { chk.checked = false; });
f.querySelectorAll('.crm-qty-val, .p-qty').forEach(function(qty) { qty.value = 1; });
document.querySelectorAll('.crm-group-content').forEach(function(content) { content.style.display = 'none'; });
document.querySelectorAll('.crm-group-wrapper').forEach(function(wrapper) { wrapper.classList.remove('open'); });

var liveList = document.getElementById('live-products-list'); if (liveList) liveList.innerHTML = "Ничего не выбрано";
var pBox = document.getElementById('photo-preview-box'); if (pBox) pBox.style.display = 'none';
var sContainer = document.getElementById('custom-services-container'); if (sContainer) sContainer.innerHTML = '';

// Возвращаем дефолтный фон финансовому блоку
var finSummary = document.getElementById('fin-summary'); if (finSummary) finSummary.style.background = '#f1f3f4';
if (typeof window.recalcDealTotal === 'function') window.recalcDealTotal();
var stField = document.getElementById('f-status'); if (stField) stField.value = '';
var rowField = document.getElementById('f-row'); if (rowField) rowField.value = '';
// ИСПРАВЛЕНО: Полностью зачищаем селектор канала привлечения при создании нового заказа
var channelField = document.getElementById('f-channel');
if (channelField) channelField.value = '';

// ИСПРАВЛЕНО: Полностью сносим старый сгенерированный блок монтажей, убирая дубли полей
var oldCustomBox = document.getElementById('custom-services-box');
if (oldCustomBox) oldCustomBox.parentNode.removeChild(oldCustomBox);
window.customServicesCount = 0;


}

// Живое авто-исчезновение финансовых нулей при фокусе
window.initFinancialFieldsFix = function() {
var fields = ['f-disc', 'f-deliv-sum', 'f-prepay'];
fields.forEach(function(id) {
var inp = document.getElementById(id);
if (inp && !inp.dataset.hasZeroFix) {
inp.dataset.hasZeroFix = "true"; inp.placeholder = "0";
inp.addEventListener('focus', function() { if (this.value === '0') this.value = ''; });
inp.addEventListener('blur', function() { if (this.value.trim() === '') this.value = '0'; });
}
});
};
// =========================================================================
// 🌐 ЧАСТЬ 2: ЦЕНТРАЛЬНЫЙ ПРИЕМНИК, РОЛИ, ДИНАМИЧЕСКИЙ СЕЛЕКТ И КАТАЛОГ v40.0
// =========================================================================

window.refreshCB = function(r) {
// 🔔 ЧЕЛОВЕЧНЫЙ ВЫВОД ОШИБОК АВТОРИЗАЦИИ И РЕГИСТРАЦИИ v50.0
if (!r || r.error) {
console.error("Ошибка бэкенда:", r);

var errBox = document.getElementById('auth-err');
var lBtn = document.getElementById('login-btn');

// Размораживаем кнопку входа, возвращая ей исходное состояние
if (lBtn) {
lBtn.removeAttribute('disabled');
if (lBtn.innerText === 'Вход...') {
lBtn.innerText = 'Войти в систему';
}
}

if (errBox) {
if (r && r.error === 'wrong_credentials') {
errBox.innerText = "❌ Ошибка: Неверный логин или пароль! Проверьте символы или восстановите доступ.";
} else if (r && r.error === 'user_exists') {
errBox.innerText = "🛑 Этот Email уже зарегистрирован! Используйте форму восстановления пароля.";
} else {
errBox.innerText = "❌ Ошибка: " + (r ? r.error : "Неизвестный сбой сервера");
}
}
return;
}
try {
document.querySelectorAll('.saas-sync-loader, #sync-loader, .sync-overlay, [class*="sync"], #loader-text, #deals-list-loader').forEach(function(l) {
l.style.display = 'none';
l.innerHTML = '';
});
var appInterface = document.getElementById('app-interface'); if (appInterface) appInterface.style.display = 'block';

// 🎈 РЕАКТИВНЫЙ SaaS-ПОДПИСЫВАТЕЛЬ ШАПКИ КОМПАНИИ v50.0
var userInfoEl = document.getElementById('user-info');
if (userInfoEl) {
var displayCompName = (r && r.compName) ? r.compName : (window.st.compName || localStorage.getItem('balloon_comp_name') || 'Моя студия');
var displayRole = (window.st.role === 'owner' || localStorage.getItem('crm_user_role') === 'owner') ? 'Владелец' : 'Менеджер';

if (r && r.compName) localStorage.setItem('balloon_comp_name', r.compName);
window.st.compName = displayCompName;

userInfoEl.innerHTML = "🎈 <span style='color:#fff; font-weight:700;'>" + displayCompName + "</span> <span style='font-size:11px; opacity:0.8; font-weight:normal;'>(" + displayRole + ")</span>";
}
} catch(eLoader) { console.error("Сбой скрытия лоадеров:", eLoader); }


var authScreen = document.getElementById('auth-screen'); if (authScreen) authScreen.style.display = 'none';
var appInterface = document.getElementById('app-interface'); if (appInterface) appInterface.style.display = 'block';
var currentScrollPos = window.scrollY || document.documentElement.scrollTop;

// Раскладываем массивы из Excel в оперативную память браузера
console.log("=== ЧТО ПРИСЛАЛ GOOGLE СКРИПТ В ТИЛЬДУ ===", r.catalog);

window.st.catalog = r.catalog || [];
window.st.deals = r.deals || [];
window.st.expenses = r.expenses || [];
window.st.payments = r.payments || [];
window.st.team = r.team || [];
window.st.statuses = r.statuses || [];
window.st.clients = r.clients || [];
window.st.marketing_channels = r.marketing_channels || [];
window.st.isLoading = false;

// // ✅ ЭТАЛОННЫЙ SaaS-ФИКС РОЛЕЙ И ИМЕНИ СТУДИИ v50.0
window.st.login = (r.login || window.st.login || '').toLowerCase().trim();
window.st.sheetId = r.sheetId || window.st.sheetId;



// Обновляем плашку в шапке CRM
var uInfo = document.getElementById('user-info');
if (uInfo) {
var roleText = (window.st.role === 'owner') ? 'Владелец' : 'Сотрудник';
uInfo.innerText = window.st.compName + ' (' + roleText + ')';
}


// // ✅ АВТОНОМНЫЙ SaaS-РЕНДЕРИНГ КАНАЛОВ МАРКЕТИНГА v50.0
var channelSelect = document.getElementById('f-channel');
if (channelSelect) {
// Пытаемся взять каналы из ответа сервера, если их нет — берем готовый дефолтный список
var channelsData = (r && r.marketing_channels && r.marketing_channels.length > 0)
? r.marketing_channels
: ["ВКонтакте", "Instagram", "WhatsApp", "Сайт Tilda", "Рекомендация"];

var channelsHtml = '<option value="">-- Выберите канал привлечения --</option>';
channelsData.forEach(function(channelName) {
if (channelName && String(channelName).trim() !== "") {
var cleanName = String(channelName).trim();
channelsHtml += '<option value="' + cleanName + '">' + cleanName + '</option>';
}
});
channelSelect.innerHTML = channelsHtml;
}


// СБРОС ЛИМИТОВ ПАГИНАЦИИ ДО 30 ПРИ СТАРТЕ И ЖЕСТКИЙ АВТОЗАПУСК ЛЕНТЫ
window.crmDealsLimit = 30;
window.crmClientsLimit = 30;
window.currentStatusFilter = 'all';

window.currentStatusFilter = 'all';
if (typeof window.renderStatusTabs === 'function') window.renderStatusTabs();
if (typeof window.renderAllElements === 'function') window.renderAllElements();
if (typeof renderDealsList === 'function') renderDealsList();
if (typeof renderAnalytics === 'function') renderAnalytics();
if (typeof window.initFinancialFieldsFix === 'function') window.initFinancialFieldsFix();
if (typeof window.renderCrmTeamList === 'function') window.renderCrmTeamList();
if (typeof window.renderExpensesTab === 'function') window.renderExpensesTab();
if (typeof window.initInteractiveCalendar === 'function') {
window.initInteractiveCalendar();
}
// Жесткое удержание скролла во время тяжелого рендеринга Tilda
var scrollCounter = 0;
var scrollInterval = setInterval(function() {
window.scrollTo(0, currentScrollPos);
scrollCounter++;
if (scrollCounter > 10) clearInterval(scrollInterval); // Держим позицию 500мс (10 раз по 50мс)
}, 50);

};

window.renderAllElements = function() {
if (typeof window.renderStatusRulesList === 'function') window.renderStatusRulesList();

var cBox = document.getElementById('calc-accordion-box');
if (cBox) {
cBox.innerHTML = '';
var cat = window.st.catalog || [];
if (!cat.length) {
cBox.innerHTML = '<div style="color:#d93025; padding:10px 0; font-weight:600;">⚠ Лист "Товары" пуст или не прогрузился!</div>';
} else {
var html = ''; var currentGroup = ""; var insideGroup = false;

cat.forEach(function(item, idx) {
if (!item || !item.name) return;
var pName = String(item.name).trim();
if (!pName) return;

if (item.isGroup || (!item.price && pName !== "")) {
if (insideGroup) { html += '</div></div>'; }
currentGroup = pName.replace(/[📦📂📁]/g, '').trim();
insideGroup = true;
html += '<div class="crm-group-wrapper" id="saas-g-' + idx + '" style="margin-bottom: 10px;">' +
'<div class="crm-group-header" style="padding:12px; background:#f8f9fa; border:1px solid #e0e0e0; border-radius:6px; cursor:pointer; font-weight:bold; display:flex; justify-content:space-between; align-items:center; user-select:none;" onclick="var c=this.nextElementSibling; if(c){ c.style.display=(c.style.display===\'none\'?\'block\':\'none\'); }">' +
'<span>🎈 ' + currentGroup + '</span>' +
'<span style="color:#999;">▼</span>' +
'</div>' +
'<div class="crm-group-content" style="display:none; padding:8px; border:1px solid #e0e0e0; border-top:none; border-bottom-left-radius:6px; border-bottom-right-radius:6px; background:#fff;">';
return;
}

var cur = window.crmCurrentDisplayCurrency || 'rub';
var finalItemPrice = 0;

if (cur === 'rub') finalItemPrice = parseFloat(item.price_rub || item.price || 0);
if (cur === 'usd') finalItemPrice = parseFloat(item.price_usd || 0);
if (cur === 'eur') finalItemPrice = parseFloat(item.price_eur || 0);
if (cur === 'kzt') finalItemPrice = parseFloat(item.price_kzt || 0);

var priceToRender = (window.frozenPricesMemory && window.frozenPricesMemory[pName.toLowerCase()] !== undefined) ? window.frozenPricesMemory[pName.toLowerCase()] : finalItemPrice;

var symbols = { 'rub': '₽', 'usd': '$', 'eur': '€', 'kzt': '₸' };
var activeSign = symbols[cur] || '₽';

html += '<div class="crm-product-item" style="display:flex; align-items:center; justify-content:space-between; padding:10px 4px; border-bottom:1px solid #f0f0f0;">' +
'<label class="crm-product-label" style="display:flex; align-items:center; gap:10px; margin:0; cursor:pointer; flex:1;">' +
// Записываем правильную цену выбранной валюты в data-baseprice, чтобы калькулятор считал без ошибок
'<input type="checkbox" class="p-chk" data-idx="' + idx + '" data-name="' + pName + '" data-baseprice="' + finalItemPrice + '" style="transform:scale(1.2); cursor:pointer;">' +
'<span style="font-size:15px; font-weight:600;">' + pName + '</span>' +
'</label>' +
'<div style="display:flex; align-items:center; gap:15px;">' +
// Выводим цену на экран с поддержкой центов (.toFixed(2)) и динамическим знаком валюты
'<div class="crm-product-price" style="font-weight:bold; color:#333; min-width:60px; text-align:right;">' + priceToRender.toFixed(2) + ' ' + activeSign + '</div>' +
'<div class="crm-qty-box" style="display:flex; align-items:center; border:1px solid #ccc; border-radius:6px; overflow:hidden; background:#fff;">' +
'<div class="crm-qty-btn minus" onclick="window.changeCrmQtyInline(' + idx + ', -1)" style="padding:4px 10px; background:#f1f3f4; cursor:pointer; font-weight:bold; user-select:none;">-</div>' +
'<input type="text" class="crm-qty-val p-qty" data-idx="' + idx + '" id="crm-q-val-' + idx + '" value="1" onchange="window.changeCrmQtyInline(' + idx + ', 0)" style="width:35px; text-align:center; border:none; font-weight:bold;">' +
'<div class="crm-qty-btn plus" onclick="window.changeCrmQtyInline(' + idx + ', 1)" style="padding:4px 10px; background:#f1f3f4; cursor:pointer; font-weight:bold; user-select:none;">+</div>' +
'</div>' +
'</div>' +
'</div>';
});

if (insideGroup) { html += '</div></div>'; }
cBox.innerHTML = html;
}
}



// ✅ ФИКС ДУБЛИРОВАНИЯ СТАТУСОВ: Чистый рендеринг селекта в бланке заказа из Excel
var fStatus = document.getElementById('f-status');
if (fStatus) {
var oldVal = fStatus.value; fStatus.innerHTML = '';
var sList = window.st.statuses || [];
if(!sList.length) {
sList = [{name:'Новое обращение'}, {name:'Общение'}, {name:'Согласован'}, {name:'Внесена оплата'}, {name:'Готов'}, {name:'Выполнен'}, {name:'Отказ'}, {name:'Не целевой'}];
}
sList.forEach(function(st) {
var stName = String(st.name || st).trim();
if (stName) {
var opt = document.createElement('option'); opt.value = stName; opt.innerText = stName; fStatus.appendChild(opt);
}
});
if(oldVal) fStatus.value = oldVal;
}

var existingBox = document.getElementById('custom-services-box');
if (!existingBox && cBox) { // Проверяем, нет ли уже блока custom-services-box на странице
var sDiv = document.createElement('div');
sDiv.id = 'custom-services-box';
sDiv.style.marginTop = '15px';
sDiv.innerHTML = '<h3 style="font-size:14px; color:#1a73e8; margin-bottom:8px; margin-top:0px; font-weight:700;">🛠 Дополнительные услуги ручного ввода:</h3>' +
'<div id="custom-services-container"></div>' +
'<button type="button" class="btn-out" onclick="window.addCustomServiceField()" style="width:100%; margin-top:8px; font-weight:700;">+ Добавить услугу (Монтаж / Демонтаж)</button>';
cBox.parentNode.insertBefore(sDiv, cBox.nextSibling);
}


// 🎯 НАВЕШИВАЕМ МГНОВЕННЫЕ СЛУШАТЕЛИ КЛИКОВ НА ВСЕ ЧЕКБОКСЫ ПОСЛЕ ОТРЕСОВКИ
if (typeof window.attachLiveCalculatorClickListeners === 'function') {
window.attachLiveCalculatorClickListeners();
}
};

window.changeCrmQtyInline = function(idx, delta) {
var inp = document.getElementById('crm-q-val-' + idx); if (!inp) return;
var val = parseInt(inp.value, 10) || 1;
inp.value = Math.max(1, val + delta);
window.recalcDealTotal();
};

window.addCustomServiceField = function() {
var container = document.getElementById('custom-services-container'); if (!container) return;
window.customServicesCount++;

var row = document.createElement('div'); row.className = 'custom-service-row';
row.style.display = 'flex'; row.style.gap = '10px'; row.style.marginBottom = '8px';

// 🌟 ОПРЕДЕЛЯЕМ ЗНАЧОК АКТИВНОЙ ВАЛЮТЫ ДЛЯ РУЧНОГО ВВОДА УСЛУГ
var cur = window.crmCurrentDisplayCurrency || 'rub';
var activeSign = { 'rub': '₽', 'usd': '$', 'eur': '€', 'kzt': '₸' }[cur] || '₽';

// В инпут цены добавляем step="0.01" для поддержки центов и копеек
row.innerHTML = '<input type="text" class="c-srv-name" placeholder="Наименование услуги" oninput="window.recalcDealTotal()" style="flex:2; padding:8px; border:1px solid #cbd5e1; border-radius:6px;">' +
'<input type="number" step="0.01" min="0" class="c-srv-price" placeholder="Цена ' + activeSign + '" oninput="window.recalcDealTotal()" style="flex:1; padding:8px; border:1px solid #cbd5e1; border-radius:6px;">';

container.appendChild(row);
};

window.recalcDealTotal = function() {
var subtotal = 0; var selectedProducts = []; var cat = window.st.catalog || [];

// 1. Собираем товары из каталога (чекбоксы)
document.querySelectorAll('.p-chk').forEach(function(chk) {
if (chk.checked) {
var idx = parseInt(chk.getAttribute('data-idx'), 10);
var pName = chk.getAttribute('data-name');
var qty = parseInt(document.getElementById('crm-q-val-' + idx).value, 10) || 1;

// 🌟 УЛЬТРА-СТАБИЛЬНЫЙ ОДНОКОЛОНОЧНЫЙ ВЫБОР ЦЕНЫ ДО ЦЕНТА
var finalPrice = 0;
if (cat[idx]) {
finalPrice = parseFloat(cat[idx].price) || 0;
} else {
finalPrice = parseFloat(chk.getAttribute('data-baseprice')) || 0;
}


// Карта символов валют для красивой строки состава на экране
var symbols = { 'rub': 'руб.', 'usd': '$', 'eur': '€', 'kzt': '₸' };
var currentSymbol = symbols[cur] || 'руб.';

// Подставляем динамический символ валюты вместо жесткого "руб/шт"
var textLine = pName + " (" + finalPrice + " " + currentSymbol + " x " + qty + " шт)";
if (selectedProducts.indexOf(textLine) === -1) {
subtotal += (finalPrice * qty);
selectedProducts.push(textLine);
}
}
});

var customServicesPrice = 0;
var cur = window.crmCurrentDisplayCurrency || 'rub';
var simpleSymbol = { 'rub': '₽', 'usd': '$', 'eur': '€', 'kzt': '₸' }[cur] || '₽';

document.querySelectorAll('.custom-service-row').forEach(function(row) {
var sNameInput = row.querySelector('.c-srv-name');
var sPriceInput = row.querySelector('.c-srv-price');

if (sNameInput && sPriceInput) {
var sName = sNameInput.value.trim();
var sPrice = parseFloat(sPriceInput.value) || 0;
if (sName && sPrice > 0) {
customServicesPrice += sPrice;

// Подставляем динамический знак активной валюты ($ / € / ₸ / ₽) вместо жесткого ₽
var textLineSrv = sName + " (" + sPrice.toFixed(2) + " " + simpleSymbol + ")";

// Ваша оригинальная защита от дублирования строк на экране
if (selectedProducts.indexOf(textLineSrv) === -1 && selectedProducts.map(function(x){return x.toLowerCase();}).indexOf(sName.toLowerCase()) === -1) {
selectedProducts.push(textLineSrv);
}
}
}
});


var liveList = document.getElementById('live-products-list');
if (liveList) liveList.innerHTML = selectedProducts.length ? selectedProducts.join(", ") : "Ничего не выбрано";

var discInp = document.getElementById('f-disc'); if (discInp && !discInp.dataset.bound) { discInp.dataset.bound = true; discInp.oninput = window.recalcDealTotal; }
var delivInp = document.getElementById('f-deliv-sum'); if (delivInp && !delivInp.dataset.bound) { delivInp.dataset.bound = true; delivInp.oninput = window.recalcDealTotal; }
var prepayInp = document.getElementById('f-prepay'); if (prepayInp && !prepayInp.dataset.bound) { prepayInp.dataset.bound = true; prepayInp.oninput = window.recalcDealTotal; }

var discPercent = Math.min(100, Math.max(0, parseInt(document.getElementById('f-disc').value, 10) || 0));
var delivPrice = parseFloat(document.getElementById('f-deliv-sum').value) || 0;
var prepayPrice = parseFloat(document.getElementById('f-prepay').value) || 0;
var totalItemsPrice = subtotal + customServicesPrice;
var discountAmount = parseFloat((totalItemsPrice * (discPercent / 100)).toFixed(2));
var totalWithDiscount = totalItemsPrice - discountAmount;
var finalTotalToPay = totalWithDiscount + delivPrice;
var leftPayDebt = finalTotalToPay - prepayPrice;

// Русский дашборд расчетов стоимости заказа
var finSummary = document.getElementById('fin-summary');
if (finSummary) {
finSummary.style.display = 'block';

if (leftPayDebt <= 0 && finalTotalToPay > 0) {
finSummary.style.cssText = 'margin-top:20px; padding:15px; background:#e6f4ea; border-radius:8px; border:1px solid #137333; transition:all 0.3s;';
} else {
finSummary.style.cssText = 'margin-top:20px; padding:15px; background:#f1f3f4; border-radius:8px; border:none; transition:all 0.3s;';
}
Made on
Tilda