// 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/>.

/**
 * Read-only version history for one competency's commentaire, opened from
 * the "Voir l'historique (N versions)" link rendered under the textarea by
 * entry_grid_form.php/capp_grid_form.php
 * (classes/local/comment_history_service::render_link()). Shared by the
 * three domains, one module.
 *
 * Zero AJAX round-trip: the whole version list travels as a `data-history`
 * JSON attribute on the link itself, already rendered server-side — same
 * pattern as the Comparateur's detail drawer (amd/src/comparateur.js:
 * "data already in the DOM via data-* attributes ... no server
 * round-trip"). Uses `core/modal` rather than the Comparateur's own drawer
 * markup for the same accessibility reason documented in
 * amd/src/unsaved_guard.js and amd/src/conflict_view.js: core/modal's
 * focus trap / Escape / backdrop-click / return-focus are already correct,
 * the Comparateur's hand-rolled drawer has none of them.
 *
 * Strictly consultative — no button here writes anything; the version list
 * this reads is one entry_conflict_service concern removed, not touched by
 * this module at all.
 *
 * @module     local_kid/comment_history
 * @copyright  2026 INSP
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
import Modal from 'core/modal';
import {get_strings as getStrings} from 'core/str';

const SELECTORS = {
    LINK: '[data-role="kid-history-link"]',
};

/**
 * @param {String} text
 * @returns {String} HTML-escaped
 */
const esc = (text) => {
    const div = document.createElement('div');
    div.textContent = text ?? '';
    return div.innerHTML;
};

/**
 * @param {Object} version {commentaire, fullname, initials, timelabel}
 * @param {Boolean} iscurrent
 * @param {String} currentbadge pre-fetched "Version actuelle" string
 * @returns {String}
 */
const renderVersion = (version, iscurrent, currentbadge) => `
    <div class="kid-history-version${iscurrent ? ' kid-history-version--current' : ''}">
        <div class="kid-history-version__head">
            <span class="kid-history-version__avatar" aria-hidden="true">${esc(version.initials)}</span>
            <span class="kid-history-version__author">${esc(version.fullname)}</span>
            <span class="kid-history-version__date">· ${esc(version.timelabel)}</span>
            ${iscurrent ? `<span class="kid-history-version__badge">${esc(currentbadge)}</span>` : ''}
        </div>
        <div class="kid-history-version__text">${esc(version.commentaire)}</div>
    </div>
`;

export const init = () => {
    document.addEventListener('click', (e) => {
        const link = e.target.closest(SELECTORS.LINK);
        if (!link) {
            return;
        }

        let data;
        try {
            data = JSON.parse(link.dataset.history);
        } catch (err) {
            return;
        }

        const stringkeys = [
            {key: 'history_modal_title', component: 'local_kid'},
            {key: 'history_current_badge', component: 'local_kid'},
        ];

        getStrings(stringkeys).then(([modaltitle, currentbadge]) => {
            const body = '<p class="kid-history-subtitle">' + esc(data.title) + '</p>'
                + data.versions.map((v, i) => renderVersion(v, i === 0, currentbadge)).join('');

            return Modal.create({
                title: modaltitle,
                body,
                large: true,
                show: true,
                removeOnClose: true,
                returnElement: link,
            });
        }).catch(() => {
            // No fallback needed — this is a read-only convenience view;
            // if it fails to build, the link simply stays clickable again.
        });
    });
};
