document.addEventListener('DOMContentLoaded', () => {
    const discipline = document.getElementById('disciplineSelect');
    const course = document.getElementById('courseNameInput');
    const publicTarget = document.getElementById('publicSelect');
    const preview = document.getElementById('workshopCodePreview');

    const normalize = value => {
        return String(value ?? '')
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .toLocaleUpperCase('fr-FR')
            .replace(/[^A-Z0-9]/g, '');
    };

    const refresh = () => {
        const option = discipline?.selectedOptions?.[0];
        const disciplineLabel = option?.dataset?.label || '';
        const disciplineCode = normalize(disciplineLabel).slice(0, 4);
        const courseCode = normalize(course?.value).slice(0, 5);
        const publicCode = normalize(publicTarget?.value).slice(0, 3);

        const parts = [
            disciplineCode || 'DISC',
            courseCode || 'COURS'
        ];

        if (publicCode) {
            parts.push(publicCode);
        }

        if (preview) {
            preview.textContent = parts.join('-');
        }
    };

    discipline?.addEventListener('change', refresh);
    course?.addEventListener('input', refresh);
    publicTarget?.addEventListener('change', refresh);

    refresh();
});
