/* ==========================================================================
   Student Welcome Guide — "Build my personal route" (configurator)
   Fills the selects on the landing page and, on submit, sends the visitor to
   the personal results page (my-route/) with their answers in the URL.
   The results page (my-route.js) renders the tailored, printable report.
   ========================================================================== */
(function () {
    var root = document.querySelector('.guide-route');
    if (!root) return;
    var lang = root.getAttribute('data-lang') || 'en';

    var T = {
        en: {
            need: 'Please choose at least your level and your current stage.',
            pick: 'Select',
            roles: { student: 'Student', parent: 'Parent or family member' },
            levels: { bachelor: 'Bachelor', master: 'Master' },
            phases: { exploring: 'I am exploring', applying: 'I am applying', accepted: 'I have been accepted', moving: 'I am preparing to move', arrived: 'I am already in Slovenia' },
            unis: { ul: 'University of Ljubljana', um: 'University of Maribor', up: 'University of Primorska', ung: 'University of Nova Gorica', other: 'Another institution' },
            cities: { ljubljana: 'Ljubljana', maribor: 'Maribor', koper: 'Koper', 'nova-gorica': 'Nova Gorica', celje: 'Celje', other: 'Another city' },
            budgets: { 'under-400': 'Under €400 per month', '400-600': '€400 to €600 per month', '600-800': '€600 to €800 per month', 'over-800': 'Over €800 per month', 'unsure': 'Not sure yet' }
        },
        si: {
            need: 'Izberite vsaj stopnjo študija in vašo trenutno fazo.',
            pick: 'Izberite',
            roles: { student: 'Študent', parent: 'Starš ali družinski član' },
            levels: { bachelor: 'Dodiplomski', master: 'Magistrski' },
            phases: { exploring: 'Šele raziskujem', applying: 'Prijavljam se', accepted: 'Sprejet sem', moving: 'Pripravljam se na selitev', arrived: 'Sem že v Sloveniji' },
            unis: { ul: 'Univerza v Ljubljani', um: 'Univerza v Mariboru', up: 'Univerza na Primorskem', ung: 'Univerza v Novi Gorici', other: 'Druga ustanova' },
            cities: { ljubljana: 'Ljubljana', maribor: 'Maribor', koper: 'Koper', 'nova-gorica': 'Nova Gorica', celje: 'Celje', other: 'Drugo mesto' },
            budgets: { 'under-400': 'Manj kot 400 € na mesec', '400-600': '400 do 600 € na mesec', '600-800': '600 do 800 € na mesec', 'over-800': 'Več kot 800 € na mesec', 'unsure': 'Še nisem prepričan' }
        },
        mk: {
            need: 'Изберете барем степен на студии и вашата тековна фаза.',
            pick: 'Изберете',
            roles: { student: 'Студент', parent: 'Родител или член на семејство' },
            levels: { bachelor: 'Додипломски', master: 'Магистерски' },
            phases: { exploring: 'Сè уште истражувам', applying: 'Се пријавувам', accepted: 'Примен сум', moving: 'Се подготвувам за преселба', arrived: 'Веќе сум во Словенија' },
            unis: { ul: 'Универзитет во Љубљана', um: 'Универзитет во Марибор', up: 'Универзитет на Приморска', ung: 'Универзитет во Нова Горица', other: 'Друга институција' },
            cities: { ljubljana: 'Љубљана', maribor: 'Марибор', koper: 'Копер', 'nova-gorica': 'Нова Горица', celje: 'Целје', other: 'Друг град' },
            budgets: { 'under-400': 'Помалку од 400 € месечно', '400-600': '400 до 600 € месечно', '600-800': '600 до 800 € месечно', 'over-800': 'Над 800 € месечно', 'unsure': 'Сè уште не сум сигурен' }
        }
    };
    var t = T[lang] || T.en;

    function opt(value, label) { var o = document.createElement('option'); o.value = value; o.textContent = label; return o; }
    function fillSelect(sel, obj, withPick) {
        if (!sel) return;
        if (withPick) sel.appendChild(opt('', t.pick + '…'));
        Object.keys(obj).forEach(function (k) { sel.appendChild(opt(k, obj[k])); });
    }

    var selRole = root.querySelector('[data-role="role"]');
    var selLevel = root.querySelector('[data-role="level"]');
    var selPhase = root.querySelector('[data-role="phase"]');
    var selUni = root.querySelector('[data-role="uni"]');
    var facInput = root.querySelector('[data-role="faculty"]');
    var selCity = root.querySelector('[data-role="city"]');
    var selBudget = root.querySelector('[data-role="budget"]');
    var selYear = root.querySelector('[data-role="year"]');
    var result = root.querySelector('.guide-route-result');

    fillSelect(selRole, t.roles, true);
    fillSelect(selLevel, t.levels, true);
    fillSelect(selPhase, t.phases, true);
    fillSelect(selUni, t.unis, true);
    fillSelect(selCity, t.cities, true);
    fillSelect(selBudget, t.budgets, true);
    ['2026/2027', '2027/2028'].forEach(function (y) { selYear.appendChild(opt(y, y)); });

    function esc(s) { return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }

    function collect() {
        return {
            role: selRole ? selRole.value : '',
            level: selLevel.value,
            phase: selPhase.value,
            uni: selUni.value,
            faculty: facInput ? facInput.value.replace(/^\s+|\s+$/g, '') : '',
            city: selCity.value,
            budget: selBudget ? selBudget.value : '',
            year: selYear.value
        };
    }

    // Exposed for the test harness; returns the results URL, or null if incomplete.
    function buildUrl() {
        var v = collect();
        if (!v.level || !v.phase) return null;
        var parts = [];
        Object.keys(v).forEach(function (k) { if (v[k]) parts.push(k + '=' + encodeURIComponent(v[k])); });
        parts.push('lang=' + encodeURIComponent(lang));
        return 'my-route/?' + parts.join('&');
    }
    window.__msosRouteUrl = buildUrl;

    function build() {
        var url = buildUrl();
        if (!url) {
            result.hidden = false;
            result.innerHTML = '<p class="guide-route-context">' + esc(t.need) + '</p>';
            return;
        }
        window.location.href = url;
    }

    root.querySelector('[data-action="build"]').addEventListener('click', build);
    root.querySelector('[data-action="reset"]').addEventListener('click', function () {
        [selRole, selLevel, selPhase, selUni, selCity, selBudget].forEach(function (s) { if (s) s.value = ''; });
        if (facInput) facInput.value = '';
        selYear.value = '2026/2027';
        result.hidden = true; result.innerHTML = '';
    });
})();
