(function() {
    function escapeHtml(value) {
        return String(value || '').replace(/[&<>"']/g, function(ch) {
            return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'}[ch];
        });
    }

    function ensureHelpShell() {
        var shell = document.getElementById('assetManagerHelpShell');
        if (shell) return shell;

        shell = document.createElement('aside');
        shell.id = 'assetManagerHelpShell';
        shell.className = 'assetmanager-help-shell';
        shell.innerHTML =
            '<div class="assetmanager-help-header">' +
                '<div><div class="small text-muted">Help</div><div class="fw-bold" id="assetManagerHelpTitle">Asset Manager</div></div>' +
                '<button type="button" class="btn btn-sm btn-secondary" id="assetManagerHelpClose"><i class="fad fa-times"></i></button>' +
            '</div>' +
            '<div class="assetmanager-help-body" id="assetManagerHelpBody">Choose a help topic.</div>';
        document.body.appendChild(shell);
        document.getElementById('assetManagerHelpClose').addEventListener('click', function() {
            shell.classList.remove('open');
        });
        return shell;
    }

    function renderTopic(topic) {
        var shell = ensureHelpShell();
        var title = document.getElementById('assetManagerHelpTitle');
        var body = document.getElementById('assetManagerHelpBody');
        title.textContent = topic.title || 'Asset Manager';
        body.innerHTML =
            '<p class="text-muted">' + escapeHtml(topic.summary || '') + '</p>' +
            (Array.isArray(topic.sections) ? topic.sections.map(function(section) {
                return '<div class="assetmanager-help-section">' +
                    '<div class="fw-bold">' + escapeHtml(section.heading || '') + '</div>' +
                    '<p>' + escapeHtml(section.body || '') + '</p>' +
                '</div>';
            }).join('') : '');
        shell.classList.add('open');
    }

    window.assetManagerOpenHelp = function(topicKey) {
        var base = (window.ROOT_URL || '..') + '/assetmanager/help/json/';
        fetch(base + encodeURIComponent(topicKey || 'dashboard') + '.json')
            .then(function(response) {
                return response.json();
            })
            .then(renderTopic)
            .catch(function() {
                renderTopic({
                    title: 'Help unavailable',
                    summary: 'This help topic could not be loaded.',
                    sections: []
                });
            });
    };
})();
