
Neutralino.init();
$(document).ready(async function() {
    // Load navbar
    $('#navbar').load('components/navbar.html', function() {
        // Attach click event to navbar links
        $('#navbar a').on('click', function(event) {
            event.preventDefault();
            const view = $(this).data('view');
            loadView(view);
        });
    });

    // Load footer
    $('#footer').load('components/footer.html');

    // Load the initial view
    const initialView = location.hash.replace('#', '') || 'home';
    loadView(initialView);

    // Enable window close event
    await Neutralino.events.on('windowClose', async () => {
        quit();
    });

    await initStorage();
});

async function quit() {
    console.log('Window close event received.')
    let data = window.localStorage.getItem('config');
    await Neutralino.storage.setData('config', data);
    Neutralino.app.exit();
}

function loadView(view) {
    $("#content").fadeOut(200, function() {
        const viewPath = `views/${view}/${view}`;
        $('#content').load(`${viewPath}.html`, function() {
            // Remove existing view-specific styles and scripts
            $('head').find('link[data-view], script[data-view]').remove();

            // Load view-specific CSS
            $('<link>')
                .attr('rel', 'stylesheet')
                .attr('href', `${viewPath}.css`)
                .attr('data-view', view)
                .appendTo('head');

            // Load view-specific JS by creating a script element
            const scriptElement = document.createElement('script');
            scriptElement.src = `${viewPath}.js`;
            scriptElement.setAttribute('data-view', view);
            scriptElement.onload = function() {
                console.log(`Initializing ${view}.js...`);
            };
            document.head.appendChild(scriptElement);
            $("#content").fadeIn(200);
        });
    });

}

async function initStorage() {
    let data = await Neutralino.storage.getData('config');
    console.log("Data from storage: ", data);
    if(data != null) {
        window.localStorage.setItem('config', data);
    }
}