/**
 * Монтирование секций настроек от плагинов (FR-075, FR-M-011).
 */
(function () {
    const mounted = {};

    function getSections() {
        const el = document.getElementById('settings-sections-data');
        if (!el) return [];
        try {
            return JSON.parse(el.textContent || '[]');
        } catch (e) {
            return [];
        }
    }

    function loadScript(src) {
        return new Promise(function (resolve, reject) {
            if (document.querySelector('script[src="' + src + '"]')) {
                resolve();
                return;
            }
            const s = document.createElement('script');
            s.src = src;
            s.onload = resolve;
            s.onerror = reject;
            document.body.appendChild(s);
        });
    }

    async function mountSection(sectionId) {
        if (mounted[sectionId]) return;
        const section = getSections().find(function (s) { return s.id === sectionId; });
        if (!section || !section.component) return;
        const container = document.getElementById('settings-section-' + sectionId);
        if (!container) return;
        await loadScript(section.component);
        if (window.MailSettingsPanel && sectionId === 'mail') {
            await loadScript('/static/js/plugins/mail/MailTemplates.js');
            window.MailSettingsPanel.mount(container);
            mounted[sectionId] = true;
            return;
        }
        if (section.content) {
            container.innerHTML = section.content;
            mounted[sectionId] = true;
        }
    }

    window.switchSettingsSection = function (sectionId) {
        document.querySelectorAll('.settings-section-panel').forEach(function (panel) {
            panel.classList.add('d-none');
        });
        document.querySelectorAll('#settingsSectionTabs .nav-link').forEach(function (tab) {
            tab.classList.remove('active');
        });
        const panel = document.getElementById('settings-section-' + sectionId);
        const tab = document.querySelector(
            '#settingsSectionTabs [data-section-id="' + sectionId + '"]'
        );
        if (panel) panel.classList.remove('d-none');
        if (tab) tab.classList.add('active');
        if (sectionId !== 'general') {
            mountSection(sectionId);
        }
        if (sectionId !== 'general') {
            history.replaceState(null, '', '#'.concat(sectionId));
        } else {
            history.replaceState(null, '', window.location.pathname);
        }
    };

    document.addEventListener('DOMContentLoaded', function () {
        const hash = (window.location.hash || '').replace('#', '');
        if (hash && document.getElementById('settings-section-' + hash)) {
            switchSettingsSection(hash);
        }
    });
})();
