document.addEventListener('DOMContentLoaded', () => {
    const navigation = document.querySelector('.fi-main-nav');
    if (!navigation) return;

    const KEY = 'navigation_state';
    const TABLE_PAGES_KEY = 'table_pages_state';

    // Function to get the state from session via a custom endpoint
    const getState = () => {
        return JSON.parse(sessionStorage.getItem(KEY)) || {};
    };

    // Function to save the state to session via a custom endpoint
    const saveState = (state) => {
        sessionStorage.setItem(KEY, JSON.stringify(state));
        const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        fetch('/api/admin/navigation-state', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
            },
            body: JSON.stringify({ groups: state }),
        });
    };

    // Function to get table page state
    const getTablePageState = () => {
        return JSON.parse(sessionStorage.getItem(TABLE_PAGES_KEY)) || {};
    };

    // Function to save table page state
    const saveTablePageState = (tableId, page) => {
        let tablePages = getTablePageState();
        tablePages[tableId] = page;
        sessionStorage.setItem(TABLE_PAGES_KEY, JSON.stringify(tablePages));
    };

    let currentState = getState();
    let currentTablePages = getTablePageState();

    // Apply the saved navigation state on page load
    const groups = navigation.querySelectorAll('.fi-nav-group');
    groups.forEach(group => {
        const label = group.querySelector('.fi-nav-group-label').textContent.trim();
        if (currentState[label] === 'collapsed') {
            group.classList.add('collapsed');
        }
    });

    // Add event listeners to save navigation state on click
    navigation.addEventListener('click', (e) => {
        const labelElement = e.target.closest('.fi-nav-group-label');
        if (!labelElement) return;

        const group = labelElement.closest('.fi-nav-group');
        const label = labelElement.textContent.trim();

        if (group.classList.contains('collapsed')) {
            currentState[label] = 'expanded';
            group.classList.remove('collapsed');
        } else {
            currentState[label] = 'collapsed';
            group.classList.add('collapsed');
        }

        saveState(currentState);
    });

    // Livewire hook to save table page when pagination changes
    Livewire.hook('component.initialized', (component) => {
        if (component.name.includes('table')) {
            const tableId = component.el.id;
            if (currentTablePages[tableId]) {
                component.set('tablePage', currentTablePages[tableId], false);
            }
        }
    });

    Livewire.on('table-pagination-updated', (tableId, page) => {
        saveTablePageState(tableId, page);
    });
});
