/**
 * Progressive Loading for AngularJS Pages
 * 
 * This script prevents blank pages by showing loading indicators
 * while AngularJS initializes and loads data.
 */

// Initialize progressive loading when document is ready
document.addEventListener('DOMContentLoaded', function () {
    console.log('📄 Progressive loading initialized');

    // Skip initialization if this is a login page (no AngularJS)
    if (window.location.pathname === '/login' || window.location.pathname.startsWith('/login/')) {
        console.log('🔐 Login page detected - skipping Angular loading overlay');
        document.body.classList.add('angular-ready');
        return;
    }

    // Set a flag when AngularJS app is ready
    function setAngularReady() {
        // Try to get the AngularJS app scope
        var appElement = document.querySelector('[ng-app]') ||
            document.querySelector('[ng-controller]') ||
            document.getElementById('bookings_page') ||
            document.getElementById('stock_page') ||
            document.getElementById('sales_page') ||
            document.getElementById('clients_page');

        if (appElement) {
            try {
                var scope = angular.element(appElement).scope();
                if (scope && scope.$root) {
                    scope.$apply(function () {
                        scope.$root.angular_ready = true;
                        console.log('✅ AngularJS app ready - hiding loading indicators');
                    });

                    // Also add CSS class to body to hide overlay and show content
                    document.body.classList.add('angular-ready');
                    console.log('✅ Added angular-ready class to body');
                }
            } catch (error) {
                console.warn('⚠️ Could not set angular_ready flag:', error);
                // Fallback: hide loading indicators after a delay
                setTimeout(function () {
                    var loadingIndicators = document.querySelectorAll('[ng-show="!$root.angular_ready"]');
                    loadingIndicators.forEach(function (indicator) {
                        indicator.style.display = 'none';
                    });
                }, 2000);
            }
        }
    }

    // Wait for AngularJS to be available and bootstrap
    function waitForAngular() {
        if (typeof angular !== 'undefined') {
            // AngularJS is loaded, wait for app to bootstrap
            setTimeout(function () {
                setAngularReady();
            }, 500); // Give AngularJS time to bootstrap
        } else {
            // AngularJS not loaded yet, wait a bit more
            setTimeout(waitForAngular, 100);
        }
    }

    // Start waiting for AngularJS
    waitForAngular();
});

// Also try to set the flag when AngularJS runs
if (typeof angular !== 'undefined') {
    angular.module('archDB').run(['$rootScope', '$timeout', function ($rootScope, $timeout) {
        console.log('🚀 AngularJS run block executed');

        $timeout(function () {
            $rootScope.angular_ready = true;
            console.log('✅ AngularJS $rootScope.angular_ready set to true');

            // Add CSS class to body to hide overlay and show content
            document.body.classList.add('angular-ready');
            console.log('✅ Added angular-ready class to body from run block');
        }, 100);

        // Also set it when route changes complete
        $rootScope.$on('$routeChangeSuccess', function () {
            $rootScope.angular_ready = true;
        });

        // Set it when view content loads
        $rootScope.$on('$viewContentLoaded', function () {
            $rootScope.angular_ready = true;
        });
    }]);
}

// Enhanced fallback for apps that don't use the 'archDB' module or non-Angular pages
document.addEventListener('DOMContentLoaded', function () {
    // Skip fallback if already handled by login page detection
    if (window.location.pathname === '/login' || window.location.pathname.startsWith('/login/')) {
        return;
    }

    // Set a general fallback timer for any page
    setTimeout(function () {
        // Check if Angular is ready - if not, this might be a non-Angular page
        if (!document.body.classList.contains('angular-ready')) {
            console.log('⏰ Fallback timer: No AngularJS detected after 3 seconds - showing content');

            var loadingIndicators = document.querySelectorAll('[ng-show="!$root.angular_ready"]');
            loadingIndicators.forEach(function (indicator) {
                indicator.style.display = 'none';
            });

            // Show the main content by adding CSS class
            document.body.classList.add('angular-ready');
            console.log('✅ Fallback: Added angular-ready class to body after timeout');
        }
    }, 3000);
});