138 lines
5.0 KiB
JavaScript

document.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById('careerTestForm');
if (!form) return;
const steps = Array.from(form.querySelectorAll('.career-step'));
const prevBtn = document.getElementById('careerTestPrevBtn');
const nextBtn = document.getElementById('careerTestNextBtn');
const submitBtn = document.getElementById('careerTestSubmitBtn');
const fill = document.getElementById('careerTestProgressFill');
const stepLabel = document.getElementById('careerTestStepLabel');
const resultBox = document.getElementById('careerTestResult');
const resultTitle = document.getElementById('careerTestResultTitle');
const resultBadges = document.getElementById('careerTestResultBadges');
const resultText = document.getElementById('careerTestResultText');
let idx = 0;
const typeTitles = {
R: '🔧 ПРАКТИК', I: '🔬 ИССЛЕДОВАТЕЛЬ', A: '🎨 ТВОРЕЦ',
S: '👥 СОЦИАЛ', E: '💼 ЛИДЕР', C: '📊 ОРГАНИЗАТОР'
};
function isAnswered(){
return !!steps[idx].querySelector('input[type="radio"]:checked');
}
function render(){
steps.forEach((s, i) => s.classList.toggle('active', i === idx));
const pct = ((idx + 1) / steps.length) * 100;
fill.style.width = pct + '%';
stepLabel.textContent = `Шаг ${idx + 1} из ${steps.length}`;
prevBtn.disabled = idx === 0;
if (idx === steps.length - 1) {
nextBtn.style.display = 'none';
submitBtn.style.display = 'inline-block';
} else {
nextBtn.style.display = 'inline-block';
submitBtn.style.display = 'none';
}
}
nextBtn.addEventListener('click', () => {
if (!isAnswered()) return alert('Выбери вариант ответа');
idx = Math.min(idx + 1, steps.length - 1);
render();
});
prevBtn.addEventListener('click', () => {
idx = Math.max(idx - 1, 0);
render();
});
form.addEventListener('submit', (e) => {
e.preventDefault();
if (!isAnswered()) return alert('Ответь на последний вопрос');
// Собери все ответы
const answers = {};
for (let i = 1; i <= 24; i++) {
const v = form.elements[`q${i}`]?.value;
if (v) answers[`q${i}`] = v;
}
// Получи ClientID из Метрики
let ym_client_id = null;
const COUNTER_ID = 105827527;
if (typeof ym !== 'undefined') {
ym(COUNTER_ID, 'getClientID', (cid) => {
ym_client_id = cid;
submitTest();
});
} else {
submitTest();
}
function submitTest() {
console.log('📤 Отправляю:', { answers, ym_client_id });
fetch('/api/career-test/submit/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ answers, ym_client_id })
})
.then(r => {
console.log('📥 Ответ статус:', r.status);
if (!r.ok) {
console.error('❌ HTTP ошибка:', r.status);
return r.text().then(t => { throw new Error(t); });
}
return r.json();
})
.then(data => {
console.log('✅ Данные:', data);
const profile = data.profile;
const profileDisplay = data.profile_display;
const top3 = data.top3_profiles;
const ege = data.recommended_ege_sets;
resultTitle.textContent = `Профиль: ${profileDisplay}`;
resultBadges.innerHTML = top3.map(t => `<span class="pill">${t}</span>`).join('');
resultText.innerHTML = `
<p><strong>${ege.title}</strong></p>
<p>${ege.desc}</p>
<h4>🎯 <strong>Рекомендуемые наборы ЕГЭ (73 балла):</strong></h4>
${ege.ege.map(set => `<div style="margin:8px 0;padding:12px;background:#fff;border-radius:8px;border-left:4px solid #0071e3;">${set}</div>`).join('')}
<p style="color:#515154;margin-top:16px;"><strong>Совет:</strong> Выбирай 1-й набор (основной профиль) + 1 запасной из топ-3.</p>
`;
resultBox.style.display = 'block';
document.querySelector('#careerTestModal .career-test-actions').style.display = 'none';
steps.forEach(s => s.style.display = 'none');
if (typeof ym !== 'undefined') {
console.log('📊 Отправляю цель в Метрику:', { profile, profileDisplay });
ym(COUNTER_ID, 'reachGoal', 'career_test_completed', {
profile: profile,
profile_name: profileDisplay,
ege_main: ege.ege[0] || null
});
console.log('✅ Цель отправлена');
}
})
.catch(err => {
console.error('❌ Ошибка:', err);
alert('Ошибка при отправке результата: ' + err.message);
});
}
});
render();
});