
const menuJSON_url = {};
const panelTheme = document.getElementById('themes-panel');
var loadTimeout = null;

function startAppTab(initApp) {
    if (typeof openInTab == 'function') {
        openInTab(apl_default, 'init_tab', '', '', '<i class="mb_icon fas fa-home"></i>', '_self', true);
    } else {
        $('#app-frames').find('iframe').addClass('loading');
        if (loadTimeout) {
            clearTimeout(loadTimeout);
        }
        loadTimeout = setTimeout(function () {
            $('#app-frames iframe').removeClass('loading');
        }, 10000);
        $('.nm_frame_app').attr('src', apl_default);
    }
}
function layoutControl(offsetX) {
    const thresholdX = offsetX ? offsetX : 16;
    const menubar_vertical = document.querySelector('.ae-menubar.menubar[aria-orientation="vertical"]');
    const toolbar = document.querySelector('.ae-menubar.toolbar');
    const switch_menu_pos_button = document.getElementById('switch-menu-position');
    const sc_main_content = document.getElementById('sc-main-content');
    const checkRTL = document.querySelector('html').getAttribute('dir') == "RTL";

    sc_main_content.parentElement.style.height = '100%';

    if(checkRTL) {
        if(window.getComputedStyle(menubar_vertical).left !== 'auto') {
            menubar_vertical.style.right = '0';
            menubar_vertical.style.left = 'auto';
        }
    }

    const layout = () => {
        if(checkRTL) {
            sc_main_content.style.paddingRight = menubar_vertical.offsetWidth + 'px';

            if(toolbar) {
                setTimeout(() => {
                    toolbar.style.width = sc_main_content.offsetWidth - menubar_vertical.offsetWidth - thresholdX - 16 + 'px';
                }, 251)
            }

        } else {
            sc_main_content.style.paddingLeft = menubar_vertical.offsetWidth + 'px';
        }
    }

    // init
    layout();

    // click
    switch_menu_pos_button.addEventListener('click', () => {
        setTimeout(layout, 350);
    });
}
function themeApply(themeName) {
    panelTheme.querySelectorAll('[data-themeapply]').forEach(button => {
        button.addEventListener('click', () => {
            $('[data-themeapply]').closest('li.theme-name.button ').removeClass('active');
            $(button).closest('li.theme-name.button ').addClass('active');
            document.querySelectorAll('.ae-menubar').forEach(menubar => {
                menubar.setAttribute('data-aetheme', button.getAttribute('data-theme'));
            });
            $('ul.context-menu-list.context-menu-root').attr('data-aetheme', button.getAttribute('data-theme'));
            $('#app-frames').attr('data-aetheme', button.getAttribute('data-theme'));
        });
    });
}

function loadJSON(url) {
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error(`Erro na solicitação ${response.status}`)
            }

            return response.json();
        })
        .then(data => {
            //console.log(data);
        })
        .catch(error => {
            console.error('Erro ao carregar o arquivo JSON:', error);
        })
}


function updateNavMenu() {
    var vert = document.querySelector('.ae-menubar.menubar').getAttribute('aria-orientation') == 'vertical';
    if (vert) {
        layoutControl(4);
    }
    document.getElementById('nav_list').innerHTML = renderItems(items_data, vert);
    if (document.getElementById('nav_mobile')) {
        document.getElementById('nav_mobile').innerHTML = renderItems(items_data, true);
    }
    if ($('#user_menu_list')[0]) {
        if (user_menu_data.length > 0) {
            $('#user_menu_list')[0].innerHTML = renderItems(user_menu_data, true);
        } else {
            $('#user_menu_list').closest('.section.actions.ae-menubar-accordion').remove();
            $('.user-info').addClass('inactive').off('click');
            $('.user-menu').remove();
        }
    }
    $('.ae-menubar.menubar[aria-orientation="vertical"] a,.ae-menubar.menubar[aria-orientation="vertical"] a span').on('click.closeVertMenu', function() {
        $('.ae-menubar.menubar[aria-orientation="vertical"]').removeClass('expanded-mob');
    });
}
function renderUserImage(arr_items, is_vert) {
    var el = $('.user_image');
    if (el.length > 0) {
        var src = el.attr('src');
        if (src.trim() == '') {
            el.replaceWith('<i class="mb_icon fa-solid fa-user" aria-hidden="true"></i>');
        }
    }
}
function renderLogo() {
    var el_list = $('.logo img');
    el_list.each(function(i, el) {
        var src = $(el).attr('src');
        if (src.trim() != '') {
            $(el).css('visibility', 'visible');
        }
    });
}
function renderMenuUser(arr_items){
    var ret_html = '';
    arr_items.forEach(function (item) {
        var has_icon = item.icon_check == 'S';
        var icon = item.icon_fa;
        var label = item.label;
        var url = item.link;
        var id = item.id;
        var target = item.target;

        ret_html += '<li class="wrapper" role="none">'+"\n";
        ret_html += "<a href=\"" + url + "\" tab-name=\""+ id + "\" tab-title=\""+ label + "\" target=\""+ target + "\" role=\"menuitem\" aria-haspopup=\"false\" aria-expanded=\"false\" data-active=\"false\">"+"\n";

        if (has_icon) {
            ret_html += '   <i class="mb_icon ' + icon + '" aria-hidden="true"> </i>'+"\n";
        }
        ret_html += '       <span class="label">' + label + '</span>'+"\n";
        ret_html += '</a>'+"\n";
        ret_html += '</li>'+"\n";
    });
    return ret_html;
}
function getTarget(target_name) {
    var ret = 'nm_frame_app';
    try {
        var targets = targets_list;
        if (targets[target_name] !== undefined) {
            ret = targets[target_name];
        }
    } catch (e) {
        ret = 'nm_frame_app';
    }
    return ret
}
function renderItems(arr_items, is_vert) {
    var ret_html = '';
    arr_items.forEach(function (item) {
        var has_icon = item.icon_check == 'S';
        var icon = item.icon_fa;
        var disabled = (item.disabled == 'Y') ? 'disabled="disabled"' : '';
        var label = item.label;
        var hint = item.hint;
        var url = item.link;
        var id = item.id;
        var link_target = item.link_target;
        var fav_check = item.fav_check;
        var children = Object.values(item.itens);
        var has_popup = 'true';

        try {
            link_target = getTarget(link_target);
            if (link_target == '_self' && url == '#' && (!children || !children.length)) {
                url = 'javascript: window.close();';
            }
        } catch (e) {
            link_target = 'nm_frame_app';
        }

        ret_html += '<li class="wrapper" ' + disabled + ' role="none">'+"\n";
        if (!children || !children.length) {
            has_popup = 'false';
            ret_html += "<a href=\"" + url + "\" tab-name=\""+ id + "\" title=\"" + hint + "\" tab-title=\""+ label + "\" target=\""+ link_target + "\" role=\"menuitem\" aria-haspopup=\""+ has_popup + "\" aria-expanded=\"false\" data-active=\"false\">"+"\n";
        } else {
            ret_html += '   <span role="menuitem" aria-haspopup="' + has_popup + '" aria-expanded="false" aria-controls="submenu-' + id + '" data-active="false">' + "\n";
        }
        if (has_icon) {
            ret_html += '   <i class="mb_icon ' + icon + '" aria-hidden="true"> </i>'+"\n";
        }
        ret_html += '       <span class="label">' + label + '</span>'+"\n";
        if (!children || !children.length) {
        } else {
            if (is_vert) {
                ret_html += '   </span>' + "\n";
            }
        }
        if (children && children.length > 0) {
            if (is_vert) {
                ret_html += '<div class="wrapper">' + "\n";
            }
            ret_html += '   <ul class="submenu" id="submenu-' + id + '" role="menu" aria-label="' + label + '" aria-hidden="true">'+"\n";
            ret_html +=         renderItems(children, is_vert);
            ret_html += '   </ul>'+"\n";
            if (is_vert) {
                ret_html += '</div>'+"\n";
            }
        } else {
            ret_html += '</a>'+"\n";
        }
        if (!children || !children.length) {
        } else {
            if (!is_vert) {
                ret_html += '   </span>' + "\n";
            }
        }
        ret_html += '</li>'+"\n";
    });
    return ret_html;
}

function hideTBButton(panel_name) {
    $('[aria-controls="'+panel_name+'-panel"]').hide();
}
function showTBButton(panel_name) {
    $('[aria-controls="'+panel_name+'-panel"]').show();
}

function finishLoadingTab(tabName) {
    var frame_el = $('#' + tabName + ' iframe');
    var tab_el = $('#id_tab_' + tabName);
    if ($('#id_tab_' + tabName + ' a').is('.active')) {
        bodyColorUpdate(frame_el[0].parentNode);
    }
    tab_el.removeClass('loading');
    frame_el.removeClass('loading');
}
function setLoadingTab(tabName) {
    var frame_el = $('#' + tabName + ' iframe');
    var tab_el = $('#id_tab_' + tabName);
    tab_el.addClass('loading');
    if (typeof use_load != 'undefined' && use_load) {
        frame_el.addClass('loading');
    }
}

function bodyColorUpdate(el_wrap) {
    try {
        var iFrameEl = $(el_wrap).find('iframe')[0];
        var bgcolor = '#efefef';
        var iframeDoc = iFrameEl.contentDocument || iFrameEl.contentWindow.document;
        bgcolor = iFrameEl.contentWindow.getComputedStyle(iframeDoc.body).backgroundColor;
        $('body').css('background-color', bgcolor);
    } catch (e) {
        console.log(e);
    }
}

function activateItem(id) {
    var vert = document.querySelector('.ae-menubar.menubar').getAttribute('aria-orientation') == 'vertical';
    var activeItem =  $('[tab-name="' + id + '"]');
    $('[role="menuitem"]').attr('data-active', 'false');
    activeItem.attr('data-active', 'true');
    if (vert) {
        activeItem.parents('.wrapper').find(' > [role="menuitem"]').attr('data-active', 'true');
    } else {
        activeItem.parents('[role="menuitem"]').attr('data-active', 'true');
    }
}
function handleLinks(e) {
    if ($('a[tab-name="' + e + '"]').attr('target') == '_self' && ($('a[tab-name="' + e + '"]').attr('href') == '#' || $('a[tab-name="' + e + '"]').attr('href') == '')) {
        window.close();
        return false;
    }
    if ($('a[tab-name="' + e + '"]').attr('href') == '#' || $('a[tab-name="' + e + '"]').attr('href') == '') {
        event.preventDefault();
        event.stopPropagation();
        return false;
    }
    // $('body').removeAttr("style");
    activateItem(e);
    if (typeof use_load != 'undefined' && use_load) {
        $('#app-frames').find('iframe').addClass('loading');
    }
    // if (!$('#app-frames').find('iframe').hasClass('loading')) {
    //     bodyColorUpdate($('#app-frames'));
    // }
    if (typeof use_load != 'undefined' && use_load) {
        if (loadTimeout) {
            clearTimeout(loadTimeout);
        }
        loadTimeout = setTimeout(function() {
            $('#app-frames iframe').removeClass('loading');
        }, 10000);
    }
}
function flattenItems(arr_items) {

    return arr_items.reduce((acc, x) => {
        acc = acc.concat(x);
        if (typeof x.itens == typeof {}) {
            acc = acc.concat(flattenItems(Object.values(x.itens)));
            // x.itens = [];
        }
        return acc;
    }, []);


}

var SCMenubar;
window.addEventListener('load', () => {

    // Inicialização da aplicação de temas
    //-------------------------------------
    if (panelTheme) {
        themeApply();
    }

    // Sistema de busca do menu
    //-------------------------------------

    renderUserImage();
    renderLogo();
    // Controle de layout
    //---------------------------------
    /**
     * @param {number} offsetX - deslocamento entre a toolbar e a menubar vertical
     */
    updateNavMenu();
    if (typeof startCrumbs == 'function') {
        startCrumbs();
    }
    if (typeof searchInit == 'function') {
        searchInit();
    }
    if (typeof startTabs == 'function') {
        startTabs();
    } else {
        $('#app-frames iframe').on('load', function () {
            bodyColorUpdate($('#app-frames')); $('#app-frames iframe').removeClass('loading');
        });
        $('a[tab-name], a[tab-name] > span').on('click', function (e) {
            var el = $(this).closest('a[tab-name]');
            if (el.attr('target') == 'nm_frame_app') {
                handleLinks(el.attr('tab-name'));
            }
        });
    }
    // Inicialização do menu
    //-------------------------------------
    SCMenubar = new Menubar({
        animation: {
            show: true,
            name: 'slide-left'
        }
    });

    document.addEventListener('panel-oppened', function(e) {
        if (e.detail.panel.id == 'search-panel') {
            $('#main-search').focus();
        }
        $('#' + e.detail.panel.id).after('<div class="panel-backdrop-overlay"></div>');
        $('.panel-backdrop-overlay').off('click');
        $('.panel-backdrop-overlay').on('click', function () {
            SCMenubar.closePanel();
        });
    });
    document.addEventListener('panel-closed', function(e) {
        $('.panel-backdrop-overlay').remove();
        $('#main-search').val('');
        $('#search-result .result-links').html('');
    });

    $('.button.expand-button').on('click', function () {
        $('.ae-menubar.menubar[aria-orientation="vertical"]').addClass('expanded-mob');
    });
    $('#close-menu-expand').on('click', function () {
        $('.ae-menubar.menubar[aria-orientation="vertical"]').removeClass('expanded-mob');
    });
    if (apl_default != '') {
        startAppTab('');
    }
    if (!start_expanded) {
        $('#switch-menu-position').click();
    }
})