/* Main Single Page Application (SPA) Controller */

const App = {
    contentArea: '#app-content',
    
    init: function() {
        const _this = this;
        
        // Handle hash changes
        window.addEventListener('hashchange', function() {
            _this.route();
        });
        
        // Initial route
        this.route();
    },
    
    route: function() {
        let fullHash = window.location.hash.substring(1) || 'dashboard';
        
        // Parse hash for parameters (e.g., #purchase?id=123)
        const parts = fullHash.split('?');
        const page = parts[0];
        const params = {};
        
        if (parts[1]) {
            const urlParams = new URLSearchParams(parts[1]);
            for (const [key, value] of urlParams) {
                params[key] = value;
            }
        }

        // Store for modules to access
        this.params = params;

        // Auth guard: If not logged in, force login page
        if (!API.isLoggedIn() && page !== 'login') {
            window.location.hash = '#login';
            return;
        }

        // If logged in and trying to access login, redirect to dashboard
        if (API.isLoggedIn() && page === 'login') {
            window.location.hash = '#dashboard';
            return;
        }

        // Show/hide sidebar based on login state
        if (page === 'login') {
            $('#sidebar, .header').hide();
            $('.main-content').css({ 'margin-right': '0', 'width': '100%' });
        } else {
            $('#sidebar, .header').show();
            $('.main-content').css({ 'margin-right': '', 'width': '' });
            
            // Update header with current user info
            const currentUser = API.getCurrentUser();
            if (currentUser) {
                // Role Mapping
                const roleMap = {
                    'admin': 'ایڈمن',
                    'operator': 'آپریٹر',
                    'manager': 'مینیجر',
                    'user': 'عام صارف'
                };
                
                $('#userName').text(currentUser.full_name);
                $('#userRole').text(roleMap[currentUser.role] || currentUser.role);
            }
        }

        this.loadPage(page);
    },
    
    loadPage: function(page) {
        const _this = this;
        const vSuffix = (typeof APP_VERSION !== 'undefined') ? `?v=${APP_VERSION}` : '';
        const url = `pages/${page}.php` + vSuffix;
        
        // Fade out current content
        $(_this.contentArea).css('opacity', 0);
        
        // Use timeout to allow fade transition
        setTimeout(() => {
            $.ajax({
                url: url,
                dataType: 'html',
                success: function(html) {
                    $(_this.contentArea).html(html).css('opacity', 1);
                    
                    // Update sidebar state
                    if (typeof Sidebar !== 'undefined') {
                        Sidebar.setActive(page);
                    }

                    // Apply permissions to the new content
                    Utils.applyPermissions();
                    
                    // Call page-specific init if it exists
                    _this.initModule(page);
                },
                error: function() {
                    Toast.danger("صفحہ لوڈ کرنے میں غلطی ہوئی۔");
                    if (page !== 'dashboard') {
                        window.location.hash = '#dashboard';
                    }
                }
            });
        }, 150);
    },
    
    // Dynamically call module init functions (e.g., initPurchase)
    initModule: function(page) {
        const _this = this; // Store context
        // Convert kebab-case to camelCase (e.g., setup-party -> initSetupParty)
        const parts = page.split('-');
        let funcName = 'init' + parts.map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('');
        
        // Check if function exists and call it
        if (typeof window[funcName] === 'function') {
            window[funcName](_this.params); // Pass params to init!
        } else {
            console.warn(`Module init function not found: ${funcName}() - Load JS?`);
            // Dynamic script loading for separate modules
            const vSuffix = (typeof APP_VERSION !== 'undefined') ? `?v=${APP_VERSION}` : '';
            const scriptUrl = `js/${page}.js` + vSuffix;
            $.getScript(scriptUrl)
                .done(function() {
                    if (typeof window[funcName] === 'function') {
                        window[funcName](_this.params); // Pass params using stored context!
                    }
                })
                .fail(function() {
                     console.log(`No JS logic found for module: ${page}`);
                });
        }
    }
};

$(function() {
    App.init();
});
