function navigateToBrowserPage(path) {
    const navMessage = {
        message: commands.MG_NAVIGATE,
        args: {
            uri: `browser://${path}`
        }
    };

    window.chrome.webview.postMessage(navMessage);
}

function resizeOptionsDropdown() {
    const wrapper = document.getElementById('dropdown-wrapper');
    if (wrapper) {
        const items = wrapper.querySelectorAll('.dropdown-item');
        let visibleCount = 0;
        items.forEach(item => {
            if (item.style.display !== 'none') visibleCount++;
        });
        const height = visibleCount * 35 + 2;
        const msg = {
            message: commands.MG_OPTIONS_RESIZE,
            args: { height: height }
        };
        window.chrome.webview.postMessage(msg);
    }
}

// Add listener for the options menu entries
function addItemsListeners() {

    // Close dropdown when item is selected
    (() => {
        const dropdownItems = Array.from(document.getElementsByClassName('dropdown-item'));
        dropdownItems.map(item => {
            item.addEventListener('click', function(e) {
                const closeMessage = {
                    message: commands.MG_OPTION_SELECTED,
                    args: {}
                };
                window.chrome.webview.postMessage(closeMessage);
            });

            // Navigate to browser page
            let entry = item.id.split('-')[1];
            switch (entry) {
                case 'settings':
                case 'history':
                case 'favorites':
                    item.addEventListener('click', function(e) {
                        navigateToBrowserPage(entry);
                    });
                    break;
            }
        });
    })();
}

function init() {
    window.chrome.webview.addEventListener('message', function(event) {
        var message = event.data.message;
        var args = event.data.args;
        switch (message) {
            case commands.MG_BUTTON_VISIBILITY:
                if (args.disableFavorites) {
                    var el = document.getElementById('item-favorites');
                    if (el) el.style.display = 'none';
                }
                if (args.disableSettings) {
                    var el = document.getElementById('item-settings');
                    if (el) el.style.display = 'none';
                }
                if (args.disableHistory) {
                    var el = document.getElementById('item-history');
                    if (el) el.style.display = 'none';
                }
                resizeOptionsDropdown();
                break;
        }
    });
    addItemsListeners();
}

init();
