/**
 * Modern Preloader Component
 * Reusable preloader with system branding support
 */

(function() {
    'use strict';

    const PreloaderManager = {
        preloader: null,
        minDisplayTime: 1500, // Minimum 1.5 seconds
        startTime: null,

        /**
         * Initialize preloader
         */
        init: function(options = {}) {
            this.startTime = Date.now();
            
            const defaultOptions = {
                icon: 'fas fa-spinner',
                subtitle: 'Please wait',
                showSystemName: true
            };
            
            const config = { ...defaultOptions, ...options };
            
            // Create preloader HTML
            const preloaderHTML = `
                <div id="pagePreloader" class="page-preloader">
                    <div class="preloader-content">
                        <div class="preloader-logo" id="preloaderLogo"></div>
                        <div class="preloader-spinner"></div>
                        <div class="preloader-text" id="preloaderSystemName">Loading</div>
                        <div class="preloader-subtitle">${config.subtitle}<span class="preloader-dots"></span></div>
                    </div>
                </div>
            `;
            
            // Insert preloader at the beginning of body
            document.body.insertAdjacentHTML('afterbegin', preloaderHTML);
            this.preloader = document.getElementById('pagePreloader');
            
            // Load branding if enabled
            if (config.showSystemName) {
                this.loadBranding();
            }
        },

        /**
         * Load system branding
         */
        loadBranding: async function() {
            try {
                const branding = await window.SystemBranding?.get();
                if (branding) {
                    const preloaderSystemName = document.getElementById('preloaderSystemName');
                    const preloaderLogo = document.getElementById('preloaderLogo');
                    
                    // Update system name
                    if (branding.system_name && preloaderSystemName) {
                        preloaderSystemName.textContent = branding.system_name;
                    }
                    
                    // Update logo only if exists
                    if (branding.system_logo && preloaderLogo) {
                        preloaderLogo.innerHTML = `<img src="${branding.system_logo}" alt="Logo">`;
                        preloaderLogo.classList.add('has-logo');
                    }
                }
            } catch (e) {
                console.log('Using default branding for preloader');
            }
        },

        /**
         * Hide preloader with minimum display time
         */
        hide: function() {
            if (!this.preloader) return;
            
            const elapsed = Date.now() - this.startTime;
            const remainingTime = Math.max(0, this.minDisplayTime - elapsed);
            
            setTimeout(() => {
                if (this.preloader) {
                    this.preloader.classList.add('hidden');
                    setTimeout(() => {
                        if (this.preloader && this.preloader.parentNode) {
                            this.preloader.remove();
                        }
                    }, 500);
                }
            }, remainingTime);
        },

        /**
         * Show preloader again (if needed)
         */
        show: function() {
            if (this.preloader) {
                this.preloader.classList.remove('hidden');
                this.startTime = Date.now();
            }
        }
    };

    // Expose to window
    window.PreloaderManager = PreloaderManager;

    // Auto-initialize on DOM ready if data-preloader attribute exists
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            if (document.body.hasAttribute('data-preloader')) {
                const options = {};
                const icon = document.body.getAttribute('data-preloader-icon');
                const subtitle = document.body.getAttribute('data-preloader-subtitle');
                
                if (icon) options.icon = icon;
                if (subtitle) options.subtitle = subtitle;
                
                PreloaderManager.init(options);
            }
        });
    }
})();
