// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Client-side column sorting for the dashboard élèves × compétences
 * cross-tabs (Évaluations/Stages/CAPP): every row for the selected item is
 * already rendered server-side, so sorting is a pure in-place DOM reorder —
 * no request, no full page reload, no scroll-to-top. Each header cell
 * carries a data-sort-type ("text" for the élève column, "niveau" for a
 * compétence column) and each cell in that column carries a
 * data-sort-value the header compares on (a folded name string, or the
 * niveau's numeric sortorder — never the niveau label text, so an empty
 * cell sorts predictably instead of by locale rules on "").
 *
 * @module     local_kid/sortable_table
 * @copyright  2026 INSP
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

const SELECTORS = {
    TABLE: '[data-region="kid-sortable-table"]',
    HEADER: 'th.kid-sortable',
    BUTTON: '.kid-sort-btn',
};

/**
 * @param {Element} table
 * @param {Element} header the clicked <th>
 */
const sortBy = (table, header) => {
    const col = parseInt(header.dataset.col, 10);
    const type = header.dataset.sortType;
    const currentcol = table.dataset.sortCol;
    const currentdir = table.dataset.sortDir;
    const dir = (currentcol === String(col) && currentdir === 'asc') ? 'desc' : 'asc';

    const tbody = table.querySelector('tbody');
    if (!tbody) {
        return;
    }
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const cellAt = (row) => row.children[col];

    rows.sort((a, b) => {
        const cella = cellAt(a);
        const cellb = cellAt(b);
        const rawa = cella ? cella.dataset.sortValue : '';
        const rawb = cellb ? cellb.dataset.sortValue : '';
        let cmp;
        if (type === 'niveau') {
            cmp = (parseFloat(rawa) || -1) - (parseFloat(rawb) || -1);
        } else {
            cmp = String(rawa).localeCompare(String(rawb), undefined, {sensitivity: 'base'});
        }
        return dir === 'asc' ? cmp : -cmp;
    });

    rows.forEach((row) => tbody.appendChild(row));

    table.dataset.sortCol = String(col);
    table.dataset.sortDir = dir;
    table.querySelectorAll(SELECTORS.HEADER).forEach((th) => {
        th.setAttribute('aria-sort', th === header ? (dir === 'asc' ? 'ascending' : 'descending') : 'none');
    });
};

/**
 * @param {Element} table
 */
const bindTable = (table) => {
    table.querySelectorAll(SELECTORS.HEADER).forEach((header) => {
        header.setAttribute('aria-sort', 'none');
        const button = header.querySelector(SELECTORS.BUTTON) || header;
        button.addEventListener('click', () => sortBy(table, header));
    });
};

/**
 * Entry point, called once by the dashboard page controller after
 * rendering an élèves × compétences cross-tab.
 */
export const init = () => {
    document.querySelectorAll(SELECTORS.TABLE).forEach(bindTable);
};
