document.addEventListener('DOMContentLoaded',()=>{
const pole=document.getElementById('poleSelect');
const discipline=document.getElementById('disciplineSelect');
const publicSelect=document.getElementById('publicSelect');
const preview=document.getElementById('courseCodePreview');
const warning=document.getElementById('musicChildWarning');

const refreshDisciplines=()=>{
    const poleId=pole?.value || '';

    Array.from(discipline?.options || []).forEach(option=>{
        if(!option.value){
            option.hidden=false;
            return;
        }

        option.hidden=option.dataset.pole!==poleId;
    });

    const selected=discipline?.selectedOptions?.[0];

    if(selected?.value && selected.dataset.pole!==poleId){
        discipline.value='';
    }
};

const refreshCode=()=>{
    const poleCode=
        pole?.selectedOptions?.[0]?.dataset?.code || 'POL';
    const disciplineCode=
        discipline?.selectedOptions?.[0]?.dataset?.code || 'DISC';
    const publicCode=
        publicSelect?.selectedOptions?.[0]?.dataset?.code || 'PUB';

    if(preview){
        preview.textContent=
            poleCode+'-'+disciplineCode+'-'+publicCode;
    }

    if(warning){
        warning.hidden=!(
            poleCode==='MUS' && publicCode==='ENF'
        );
    }
};

pole?.addEventListener('change',()=>{
    refreshDisciplines();
    refreshCode();
});

discipline?.addEventListener('change',refreshCode);
publicSelect?.addEventListener('change',refreshCode);

refreshDisciplines();
refreshCode();
});
