(function () {
    "use strict";

    var _ = cockpit.gettext;

    var HELPER = "/usr/sbin/edubuntu-menu-admin-helper";
    var QUERY  = "/usr/share/cockpit/edubuntu-menu-admin/query.py";

    var state = null;   // loaded from query.py
    var activeTab = "tab-global";
    var initialGlobal = [];  // initial set of hidden app ids
    var initialPerUser = {}; // username -> [hidden ids]

    /* ── Translate dynamic HTML elements ───────────────────────── */

    function initTranslations() {
        document.getElementById("global-desc").innerHTML =
            _("Select applications to <strong>hide</strong> for all non-administrator users.");
        document.getElementById("peruser-desc").innerHTML =
            _("Select applications to <strong>hide</strong> for a specific user.");
        document.getElementById("global-filter").placeholder =
            _("Filter applications…");
        document.getElementById("user-filter").placeholder =
            _("Filter applications…");
    }
    initTranslations();

    /* ── Tab switching (plain JS, no Bootstrap JS needed) ───────── */

    var tabLinks = document.querySelectorAll(".nav-tabs a[data-toggle=tab]");
    tabLinks.forEach(function (a) {
        a.addEventListener("click", function (ev) {
            ev.preventDefault();
            tabLinks.forEach(function (l) {
                l.parentElement.classList.remove("active");
            });
            document.querySelectorAll(".tab-pane").forEach(function (p) {
                p.classList.remove("active");
            });
            a.parentElement.classList.add("active");
            var target = a.getAttribute("href").substring(1);
            document.getElementById(target).classList.add("active");
            activeTab = target;
            if (target === "tab-peruser" && state) {
                renderPerUser();
                var sel = document.getElementById("user-select");
                if (sel.value && !initialPerUser[sel.value]) {
                    initialPerUser[sel.value] = checkedValues("user-list");
                }
                checkChanges();
            }
        });
    });

    /* ── Filter logic ──────────────────────────────────────────── */

    function wireFilter(inputId, listId) {
        var input = document.getElementById(inputId);
        input.addEventListener("input", function () {
            var term = input.value.toLowerCase();
            var labels = document.getElementById(listId).querySelectorAll("label");
            labels.forEach(function (lbl) {
                var text = lbl.textContent.toLowerCase();
                if (text.indexOf(term) >= 0)
                    lbl.classList.remove("hidden-row");
                else
                    lbl.classList.add("hidden-row");
            });
        });
    }
    wireFilter("global-filter", "global-list");
    wireFilter("user-filter",   "user-list");

    /* ── Rendering ─────────────────────────────────────────────── */

    function renderChecklist(containerId, apps, hiddenSet, disabledSet) {
        var container = document.getElementById(containerId);
        container.innerHTML = "";
        apps.forEach(function (app) {
            var lbl = document.createElement("label");
            var cb  = document.createElement("input");
            cb.type = "checkbox";
            cb.value = app.id;
            var isDisabled = disabledSet && disabledSet.indexOf(app.id) >= 0;
            cb.checked = hiddenSet.indexOf(app.id) >= 0 || isDisabled;
            if (isDisabled) {
                cb.disabled = true;
                lbl.classList.add("disabled-row");
            }
            cb.addEventListener("change", checkChanges);
            lbl.appendChild(cb);
            var nameText = " " + (app.name || app.id);
            if (isDisabled) {
                nameText += "  (" + _("hidden globally") + ")";
            }
            lbl.appendChild(document.createTextNode(nameText));
            container.appendChild(lbl);
        });
    }

    function renderGlobal() {
        var hidden = state.apps
            .filter(function (a) { return a.hidden_global; })
            .map(function (a) { return a.id; });
        renderChecklist("global-list", state.apps, hidden, null);
    }

    function currentGlobalHidden() {
        var result = [];
        var cbs = document.getElementById("global-list")
                          .querySelectorAll("input[type=checkbox]:checked");
        cbs.forEach(function (cb) { result.push(cb.value); });
        return result;
    }

    function renderPerUser() {
        var sel = document.getElementById("user-select");
        var username = sel.value;
        if (!username) {
            document.getElementById("user-list").innerHTML =
                "<p class='text-muted' style='padding:12px'>" + _("No non-administrator users found.") + "</p>";
            return;
        }
        var udata = state.users.find(function (u) {
            return u.username === username;
        });
        var hidden = udata ? udata.hidden : [];
        var globalHidden = currentGlobalHidden();
        renderChecklist("user-list", state.apps, hidden, globalHidden);
    }

    function populateUsers() {
        var sel = document.getElementById("user-select");
        sel.innerHTML = "";
        state.users.forEach(function (u) {
            var opt = document.createElement("option");
            opt.value = u.username;
            opt.textContent = u.username;
            sel.appendChild(opt);
        });
        sel.addEventListener("change", function () {
            renderPerUser();
            var uname = sel.value;
            if (uname && !initialPerUser[uname]) {
                initialPerUser[uname] = checkedValues("user-list");
            }
            checkChanges();
        });
    }

    /* ── Data loading ──────────────────────────────────────────── */

    function loadState() {
        document.getElementById("loading").style.display = "";
        document.getElementById("content").style.display = "none";
        document.getElementById("error-bar").style.display = "none";

        cockpit.spawn(["python3", QUERY], { err: "message" })
            .then(function (data) {
                state = JSON.parse(data);
                populateUsers();
                renderGlobal();
                renderPerUser();
                // Capture initial state
                initialGlobal = checkedValues("global-list");
                var sel = document.getElementById("user-select");
                if (sel.value) {
                    initialPerUser[sel.value] = checkedValues("user-list");
                }
                document.getElementById("btn-apply").disabled = true;
                document.getElementById("loading").style.display = "none";
                document.getElementById("content").style.display = "";
            })
            .catch(function (err) {
                showError(_("Failed to load state: ") + err.message);
            });
    }

    /* ── Apply ─────────────────────────────────────────────────── */

    function checkedValues(containerId) {
        var cbs = document.getElementById(containerId)
                          .querySelectorAll("input[type=checkbox]:checked");
        var result = [];
        cbs.forEach(function (cb) { result.push(cb.value); });
        return result;
    }

    function arraysEqual(a, b) {
        if (a.length !== b.length) return false;
        var sa = a.slice().sort();
        var sb = b.slice().sort();
        for (var i = 0; i < sa.length; i++) {
            if (sa[i] !== sb[i]) return false;
        }
        return true;
    }

    function checkChanges() {
        var btn = document.getElementById("btn-apply");
        var currentGlobal = checkedValues("global-list");
        if (!arraysEqual(currentGlobal, initialGlobal)) {
            btn.disabled = false;
            return;
        }
        var sel = document.getElementById("user-select");
        if (sel.value && initialPerUser[sel.value]) {
            var currentUser = checkedValues("user-list");
            if (!arraysEqual(currentUser, initialPerUser[sel.value])) {
                btn.disabled = false;
                return;
            }
        }
        btn.disabled = true;
    }

    function applyChanges() {
        var btn = document.getElementById("btn-apply");
        btn.disabled = true;
        document.getElementById("status-msg").textContent = "";

        var globalHidden = checkedValues("global-list");
        var globalCmd = [HELPER, "global"].concat(globalHidden);

        var chain = cockpit.spawn(globalCmd, { superuser: "require", err: "message" });

        var sel = document.getElementById("user-select");
        if (sel.value) {
            var userHidden = checkedValues("user-list");
            var userCmd = [HELPER, "user", sel.value].concat(userHidden);
            chain = chain.then(function () {
                return cockpit.spawn(userCmd, { superuser: "require", err: "message" });
            });
        }

        chain
            .then(function () {
                document.getElementById("status-msg").textContent = _("Changes applied.");
                btn.disabled = false;
                loadState();
            })
            .catch(function (err) {
                showError(_("Apply failed: ") + err.message);
                btn.disabled = false;
            });
    }

    /* ── Error display ─────────────────────────────────────────── */

    function showError(msg) {
        document.getElementById("loading").style.display = "none";
        document.getElementById("error-text").textContent = msg;
        document.getElementById("error-bar").style.display = "";
    }

    /* ── Wire buttons ──────────────────────────────────────────── */

    document.getElementById("btn-apply").addEventListener("click", applyChanges);
    document.getElementById("btn-reload").addEventListener("click", function () {
        document.getElementById("status-msg").textContent = "";
        loadState();
    });

    /* ── Bootstrap ─────────────────────────────────────────────── */

    loadState();
})();
