/**
 * Collapsible "Import & backup" section in the maca Restu admin submenu.
 */
(function () {
    'use strict';

    var cfg = window.macaMenulistAdminMenuGroups;
    if (!cfg || !cfg.groupSlug || !Array.isArray(cfg.childPages)) {
        return;
    }

    var COLLAPSED_CLASS = 'maca-import-group-collapsed';
    var OPEN_CLASS = 'maca-import-group-open';
    var BODY_COLLAPSED = 'maca-import-group-collapsed';
    var BODY_OPEN = 'maca-import-group-open';

    function getToplevel() {
        return document.getElementById('toplevel_page_maca-restu');
    }

    function pageSlugFromHref(href) {
        if (!href) {
            return '';
        }

        var match = href.match(/[?&]page=([^&]+)/);
        return match ? decodeURIComponent(match[1]) : '';
    }

    function findHeadingLink(top) {
        var links = top.querySelectorAll('.wp-submenu a');
        var i;
        var slug;
        var toggle;

        for (i = 0; i < links.length; i += 1) {
            slug = pageSlugFromHref(links[i].getAttribute('href') || '');
            if (slug === cfg.groupSlug) {
                return links[i];
            }

            toggle = links[i].querySelector('.maca-menulist-submenu-heading--toggle');
            if (toggle) {
                return links[i];
            }
        }

        return top.querySelector('a[href*="page=' + cfg.groupSlug + '"]');
    }

    function markChildItems(top) {
        cfg.childPages.forEach(function (slug) {
            var links = top.querySelectorAll('.wp-submenu a[href*="page=' + slug + '"]');
            var j;

            for (j = 0; j < links.length; j += 1) {
                if (links[j].parentElement) {
                    links[j].parentElement.classList.add('maca-menulist-import-child');
                }
            }
        });
    }

    function readStoredOpenState() {
        try {
            return localStorage.getItem(cfg.storageKey);
        } catch (error) {
            return null;
        }
    }

    function storeOpenState(isOpen) {
        try {
            localStorage.setItem(cfg.storageKey, isOpen ? '1' : '0');
        } catch (error) {
            // Ignore private browsing / disabled storage.
        }
    }

    function persistOpenState(isOpen) {
        storeOpenState(isOpen);

        if (!cfg.ajaxUrl || !cfg.nonce) {
            return;
        }

        var body = new FormData();
        body.append('action', 'maca_menulist_import_group_toggle');
        body.append('nonce', cfg.nonce);
        body.append('open', isOpen ? '1' : '0');

        fetch(cfg.ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            body: body
        }).catch(function () {
            // Non-blocking preference save.
        });
    }

    function updateHeadingAria(heading, isOpen) {
        heading.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
        heading.setAttribute('aria-controls', 'maca-menulist-import-backup-submenu');
    }

    function applyOpenState(isOpen, persist) {
        var top = getToplevel();
        var heading = top ? findHeadingLink(top) : null;
        var body = document.body;

        if (top) {
            top.classList.toggle(COLLAPSED_CLASS, !isOpen);
            top.classList.toggle(OPEN_CLASS, isOpen);
        }

        if (body) {
            body.classList.toggle(BODY_COLLAPSED, !isOpen);
            body.classList.toggle(BODY_OPEN, isOpen);
        }

        if (heading) {
            updateHeadingAria(heading, isOpen);
        }

        if (persist) {
            persistOpenState(isOpen);
        }
    }

    function prepareHeading(heading) {
        heading.setAttribute('role', 'button');
        heading.setAttribute('href', '#maca-menulist-import-backup-submenu');
        heading.classList.add('maca-menulist-import-group-toggle');
    }

    function shouldStartOpen() {
        if (cfg.isOpen === true || cfg.isOpen === '1') {
            return true;
        }

        if (cfg.isOpen === false || cfg.isOpen === '0') {
            return false;
        }

        var stored = readStoredOpenState();
        if (stored === '1') {
            return true;
        }
        if (stored === '0') {
            return false;
        }

        return cfg.childPages.indexOf(cfg.currentPage || '') !== -1;
    }

    function toggleGroup(event) {
        var top = getToplevel();
        if (!top) {
            return;
        }

        var heading = findHeadingLink(top);
        if (!heading || !heading.contains(event.target)) {
            return;
        }

        event.preventDefault();
        event.stopPropagation();
        if (typeof event.stopImmediatePropagation === 'function') {
            event.stopImmediatePropagation();
        }

        var isOpen = document.body.classList.contains(BODY_OPEN);
        applyOpenState(!isOpen, true);
    }

    function onHeadingKeydown(event) {
        if (event.key !== 'Enter' && event.key !== ' ') {
            return;
        }

        var top = getToplevel();
        var heading = top ? findHeadingLink(top) : null;
        if (!heading || !heading.contains(event.target)) {
            return;
        }

        event.preventDefault();
        toggleGroup(event);
    }

    function bindInteractions(top, heading) {
        prepareHeading(heading);

        var adminMenu = document.getElementById('adminmenu');
        if (adminMenu) {
            adminMenu.addEventListener('click', toggleGroup, true);
            adminMenu.addEventListener('keydown', onHeadingKeydown, true);
        } else {
            heading.addEventListener('click', toggleGroup, true);
            heading.addEventListener('keydown', onHeadingKeydown, true);
        }
    }

    function init() {
        var top = getToplevel();
        if (!top) {
            return;
        }

        markChildItems(top);

        var heading = findHeadingLink(top);
        if (!heading) {
            return;
        }

        bindInteractions(top, heading);
        applyOpenState(shouldStartOpen(), false);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
