// Graph Loader - Updates graph image with auth and parameters
(function() {
    'use strict';
    
    function updateGraph() {
        // Get current selections
        const selection = window.YearMonthPicker ? window.YearMonthPicker.getSelection() : { periods: [{ year: new Date().getFullYear(), month: 1 }] };
        const hourTypes = window.HourTypePicker ? window.HourTypePicker.getSelection() : [];
        const hourType = hourTypes.length > 0 ? hourTypes.join(', ') : 'None';
        
        // Get auth token
        const token = window.SimpleAuth ? window.SimpleAuth.token : null;
        
        if (!token) {
            return;
        }
        
        // Build periods parameter as JSON
        const periodsParam = JSON.stringify(selection.periods);
        
        // Optional: admin viewing as another organization
        const viewAsOrg = (window.SimpleAuth && window.SimpleAuth.isAdmin() && window.SimpleAuth.selectedOrganization)
            ? window.SimpleAuth.selectedOrganization
            : '';

        // Build URL with parameters
        let url = `/api/retrieve/graph?periods=${encodeURIComponent(periodsParam)}&hourType=${encodeURIComponent(hourType)}&token=${encodeURIComponent(token)}`;
        if (viewAsOrg) {
            url += `&viewAsOrg=${encodeURIComponent(viewAsOrg)}`;
        }
        
        // Update image src
        const img = document.querySelector('#content img[src*="retrieve/graph"]');
        if (img) {
            // Add error handler for 401/403 responses
            img.onerror = function() {
                if (window.SimpleAuth) {
                    SimpleAuth.handleUnauthorized();
                }
            };
            
            img.src = url + '&_=' + new Date().getTime(); // Add timestamp to prevent caching
        }
    }
    
    // Initialize on document ready
    $(document).ready(function() {
        // Listen for year or hour type changes
        $(document).on('yearSelectionChanged', function() {
            setTimeout(updateGraph, 100); // Small delay to ensure other components are updated
        });
        
        // Initial load after login
        setTimeout(function() {
            if (window.SimpleAuth && window.SimpleAuth.isAuthenticated) {
                updateGraph();
            }
        }, 500);
    });
    
    // Public API
    window.GraphLoader = {
        update: updateGraph
    };
    
})();
