const additionalFieldLevel = '16832009'; // id доп поля с уровнем
const additionalFieldStream = '16832001'; // id доп поля с потоком

// Склонение числительных: pluralize(5, 'урок', 'урока', 'уроков') → 'уроков'
const pluralize = (n, one, few, many) => {
  const mod10 = n % 10;
  const mod100 = n % 100;
  if (mod100 >= 11 && mod100 <= 19) return many;
  if (mod10 === 1) return one;
  if (mod10 >= 2 && mod10 <= 4) return few;
  return many;
};

const handleUserPath = async () => {
    const userPathContainer = document.querySelector('.hmns-user__path');
    
    if(!userPathContainer) return;
    
    try {
        const res = await fetch(`/chtm/level/get?field=${additionalFieldLevel}`);
        const data = await res.text();
        
        const pathName = data == 'null' ? 'Не выбрана' : data;
        
        const userPathName = document.querySelector('.hmns-user__path-name');
        userPathName.innerHTML = `
${pathName}
<br>
<small>Ваша траектория</small>
`;
        const userPathBtn = document.querySelector('.hmns-user__path-btn');
        const selectPath = document.querySelector('.hmns-user__path-select');

        userPathBtn.addEventListener('click', () => {
			selectPath.classList.toggle('hidden');
        	userPathContainer.classList.toggle('js-open');
        });
        document.addEventListener('click', (e) => {
            if(!e.target.closest('.hmns-user__path')) {
                selectPath.classList.add('hidden');
                userPathContainer.classList.remove('js-open');            
            }
        });
        selectPath.addEventListener('click', async (e) => {
            if(e.target.dataset.path) {
            	selectPath.innerHTML = '<span class="hmns-fallback">Меняем траекторию...</span>';
            	document.querySelector('.dots').classList.add('dots-animate');
            const pathRes = await fetch(`/chtm/level/set?level=${e.target.dataset.path}&field=${additionalFieldLevel}`);
            	if(!pathRes.ok) throw new Error('Failed to change level');
            	window.location.reload();
            }
        })
    } catch(error) {
        console.error('Failed to user path: ' + error);
    }
}

document.addEventListener('DOMContentLoaded', () => {
	handleUserPath();
})