/**
 * AUTO TESTER - Unified Design System JavaScript
 * Common functions and utilities for all HTML pages
 * Created: 2026-04-22
 * Version: 1.0.0
 */

// ============================================
// Global Variables
// ============================================
const AUTO_TESTER = {
    version: '1.0.0',
    apiBase: '/core/api/',
    assetsBase: '/assets/',
    currentUser: null,
    theme: 'dark',
    language: 'ar',
    notifications: [],
    
    // Initialize system
    init() {
        this.loadCurrentUser();
        this.initializeTheme();
        this.initializeLanguage();
        this.setupEventListeners();
        this.initializeComponents();
        console.log('AUTO TESTER Design System Initialized v' + this.version);
    },
    
    // Load current user from session
    loadCurrentUser() {
        const userSession = sessionStorage.getItem('currentUser');
        if (userSession) {
            try {
                this.currentUser = JSON.parse(userSession);
                this.updateUserMenu();
            } catch (e) {
                console.error('Failed to parse user session:', e);
            }
        }
    },
    
    // Update user menu
    updateUserMenu() {
        const userInfo = document.getElementById('userInfo');
        const userName = document.getElementById('userName');
        const userRole = document.getElementById('userRole');
        const loginBtn = document.getElementById('loginBtn');
        const logoutBtn = document.getElementById('logoutBtn');
        
        if (this.currentUser && userInfo) {
            if (userName) userName.textContent = this.currentUser.name || 'User';
            if (userRole) userRole.textContent = this.currentUser.role || 'User';
            if (userInfo) userInfo.style.display = 'block';
            if (loginBtn) loginBtn.style.display = 'none';
            if (logoutBtn) logoutBtn.style.display = 'block';
        } else {
            if (userInfo) userInfo.style.display = 'none';
            if (loginBtn) loginBtn.style.display = 'block';
            if (logoutBtn) logoutBtn.style.display = 'none';
        }
    },
    
    // Initialize theme
    initializeTheme() {
        const savedTheme = localStorage.getItem('theme') || 'dark';
        this.theme = savedTheme;
        document.documentElement.setAttribute('data-theme', savedTheme);
    },
    
    // Initialize language
    initializeLanguage() {
        const savedLanguage = localStorage.getItem('language') || 'ar';
        this.language = savedLanguage;
        document.documentElement.setAttribute('lang', savedLanguage);
        document.documentElement.setAttribute('dir', savedLanguage === 'ar' ? 'rtl' : 'ltr');
    },
    
    // Setup event listeners
    setupEventListeners() {
        // Navbar scroll effect
        window.addEventListener('scroll', this.handleNavbarScroll.bind(this));
        
        // Theme toggle
        const themeToggle = document.getElementById('themeToggle');
        if (themeToggle) {
            themeToggle.addEventListener('click', this.toggleTheme.bind(this));
        }
        
        // Language toggle
        const languageToggle = document.getElementById('languageToggle');
        if (languageToggle) {
            languageToggle.addEventListener('click', this.toggleLanguage.bind(this));
        }
        
        // Mobile menu toggle
        const mobileMenuToggle = document.getElementById('mobileMenuToggle');
        if (mobileMenuToggle) {
            mobileMenuToggle.addEventListener('click', this.toggleMobileMenu.bind(this));
        }
        
        // Close modals on outside click
        document.addEventListener('click', this.handleModalOutsideClick.bind(this));
        
        // Form submissions
        document.addEventListener('submit', this.handleFormSubmit.bind(this));
        
        // Initialize tooltips
        this.initializeTooltips();
    },
    
    // Initialize components
    initializeComponents() {
        // Initialize all modals
        this.initializeModals();
        
        // Initialize all dropdowns
        this.initializeDropdowns();
        
        // Initialize all tabs
        this.initializeTabs();
        
        // Initialize all accordions
        this.initializeAccordions();
        
        // Initialize all carousels
        this.initializeCarousels();
        
        // Initialize file uploads
        this.initializeFileUploads();
        
        // Initialize data tables
        this.initializeDataTables();
    },
    
    // ============================================
    // Navigation Functions
    // ============================================
    
    // Handle navbar scroll
    handleNavbarScroll() {
        const navbar = document.querySelector('.navbar');
        if (navbar) {
            if (window.scrollY > 50) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        }
    },
    
    // Toggle theme
    toggleTheme() {
        this.theme = this.theme === 'dark' ? 'light' : 'dark';
        document.documentElement.setAttribute('data-theme', this.theme);
        localStorage.setItem('theme', this.theme);
        
        // Update theme toggle button
        const themeToggle = document.getElementById('themeToggle');
        if (themeToggle) {
            const icon = themeToggle.querySelector('i');
            if (icon) {
                icon.className = this.theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
            }
        }
        
        this.showNotification('Theme changed to ' + this.theme, 'info');
    },
    
    // Toggle language
    toggleLanguage() {
        this.language = this.language === 'ar' ? 'en' : 'ar';
        document.documentElement.setAttribute('lang', this.language);
        document.documentElement.setAttribute('dir', this.language === 'ar' ? 'rtl' : 'ltr');
        localStorage.setItem('language', this.language);
        
        // Update language toggle button
        const languageToggle = document.getElementById('languageToggle');
        if (languageToggle) {
            languageToggle.textContent = this.language.toUpperCase();
        }
        
        this.showNotification('Language changed to ' + this.language.toUpperCase(), 'info');
        
        // Reload page to apply language changes
        setTimeout(() => {
            window.location.reload();
        }, 1000);
    },
    
    // Toggle mobile menu
    toggleMobileMenu() {
        const mobileMenu = document.getElementById('mobileMenu');
        if (mobileMenu) {
            mobileMenu.classList.toggle('show');
        }
    },
    
    // ============================================
    // Modal Functions
    // ============================================
    
    // Initialize modals
    initializeModals() {
        const modals = document.querySelectorAll('.modal');
        modals.forEach(modal => {
            const closeBtn = modal.querySelector('.modal-close');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    this.closeModal(modal.id);
                });
            }
        });
    },
    
    // Show modal
    showModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('show');
            document.body.style.overflow = 'hidden';
            
            // Focus management
            const focusableElements = modal.querySelectorAll('button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
            if (focusableElements.length > 0) {
                focusableElements[0].focus();
            }
        }
    },
    
    // Close modal
    closeModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('show');
            document.body.style.overflow = '';
        }
    },
    
    // Handle modal outside click
    handleModalOutsideClick(event) {
        if (event.target.classList.contains('modal')) {
            this.closeModal(event.target.id);
        }
    },
    
    // ============================================
    // Dropdown Functions
    // ============================================
    
    // Initialize dropdowns
    initializeDropdowns() {
        const dropdowns = document.querySelectorAll('.dropdown');
        dropdowns.forEach(dropdown => {
            const toggle = dropdown.querySelector('.dropdown-toggle');
            const menu = dropdown.querySelector('.dropdown-menu');
            
            if (toggle && menu) {
                toggle.addEventListener('click', (e) => {
                    e.preventDefault();
                    this.toggleDropdown(dropdown);
                });
                
                // Close on outside click
                document.addEventListener('click', (e) => {
                    if (!dropdown.contains(e.target)) {
                        this.closeDropdown(dropdown);
                    }
                });
            }
        });
    },
    
    // Toggle dropdown
    toggleDropdown(dropdown) {
        const menu = dropdown.querySelector('.dropdown-menu');
        if (menu) {
            menu.classList.toggle('show');
            
            // Close other dropdowns
            document.querySelectorAll('.dropdown-menu.show').forEach(otherMenu => {
                if (otherMenu !== menu) {
                    otherMenu.classList.remove('show');
                }
            });
        }
    },
    
    // Close dropdown
    closeDropdown(dropdown) {
        const menu = dropdown.querySelector('.dropdown-menu');
        if (menu) {
            menu.classList.remove('show');
        }
    },
    
    // ============================================
    // Tab Functions
    // ============================================
    
    // Initialize tabs
    initializeTabs() {
        const tabGroups = document.querySelectorAll('.tabs');
        tabGroups.forEach(tabGroup => {
            const tabs = tabGroup.querySelectorAll('.tab');
            const panes = tabGroup.querySelectorAll('.tab-pane');
            
            tabs.forEach(tab => {
                tab.addEventListener('click', (e) => {
                    e.preventDefault();
                    this.showTab(tabGroup, tab.dataset.target);
                });
            });
        });
    },
    
    // Show tab
    showTab(tabGroup, targetId) {
        const tabs = tabGroup.querySelectorAll('.tab');
        const panes = tabGroup.querySelectorAll('.tab-pane');
        
        // Remove active class from all tabs and panes
        tabs.forEach(tab => tab.classList.remove('active'));
        panes.forEach(pane => pane.classList.remove('active'));
        
        // Add active class to clicked tab and corresponding pane
        const activeTab = tabGroup.querySelector(`[data-target="${targetId}"]`);
        const activePane = document.getElementById(targetId);
        
        if (activeTab) activeTab.classList.add('active');
        if (activePane) activePane.classList.add('active');
    },
    
    // ============================================
    // Accordion Functions
    // ============================================
    
    // Initialize accordions
    initializeAccordions() {
        const accordions = document.querySelectorAll('.accordion');
        accordions.forEach(accordion => {
            const items = accordion.querySelectorAll('.accordion-item');
            
            items.forEach(item => {
                const header = item.querySelector('.accordion-header');
                const content = item.querySelector('.accordion-content');
                
                if (header && content) {
                    header.addEventListener('click', () => {
                        this.toggleAccordionItem(item);
                    });
                }
            });
        });
    },
    
    // Toggle accordion item
    toggleAccordionItem(item) {
        const content = item.querySelector('.accordion-content');
        const icon = item.querySelector('.accordion-icon');
        
        if (content) {
            const isOpen = content.style.maxHeight && content.style.maxHeight !== '0px';
            
            // Close other items in the same accordion
            const accordion = item.closest('.accordion');
            if (accordion) {
                const otherItems = accordion.querySelectorAll('.accordion-item');
                otherItems.forEach(otherItem => {
                    if (otherItem !== item) {
                        const otherContent = otherItem.querySelector('.accordion-content');
                        const otherIcon = otherItem.querySelector('.accordion-icon');
                        if (otherContent) {
                            otherContent.style.maxHeight = '0px';
                            otherItem.classList.remove('active');
                        }
                        if (otherIcon) {
                            otherIcon.style.transform = 'rotate(0deg)';
                        }
                    }
                });
            }
            
            // Toggle current item
            if (isOpen) {
                content.style.maxHeight = '0px';
                item.classList.remove('active');
                if (icon) icon.style.transform = 'rotate(0deg)';
            } else {
                content.style.maxHeight = content.scrollHeight + 'px';
                item.classList.add('active');
                if (icon) icon.style.transform = 'rotate(180deg)';
            }
        }
    },
    
    // ============================================
    // Form Functions
    // ============================================
    
    // Handle form submission
    handleFormSubmit(event) {
        const form = event.target;
        
        // Add loading state
        const submitBtn = form.querySelector('[type="submit"]');
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="loading"></span> Processing...';
        }
        
        // Simulate form processing
        setTimeout(() => {
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.innerHTML = 'Submit';
            }
        }, 2000);
    },
    
    // Validate form
    validateForm(form) {
        const inputs = form.querySelectorAll('input[required], select[required], textarea[required]');
        let isValid = true;
        
        inputs.forEach(input => {
            if (!input.value.trim()) {
                this.showFieldError(input, 'This field is required');
                isValid = false;
            } else {
                this.clearFieldError(input);
            }
        });
        
        return isValid;
    },
    
    // Show field error
    showFieldError(field, message) {
        field.classList.add('error');
        
        let errorElement = field.parentNode.querySelector('.field-error');
        if (!errorElement) {
            errorElement = document.createElement('div');
            errorElement.className = 'field-error';
            field.parentNode.appendChild(errorElement);
        }
        
        errorElement.textContent = message;
    },
    
    // Clear field error
    clearFieldError(field) {
        field.classList.remove('error');
        const errorElement = field.parentNode.querySelector('.field-error');
        if (errorElement) {
            errorElement.remove();
        }
    },
    
    // ============================================
    // File Upload Functions
    // ============================================
    
    // Initialize file uploads
    initializeFileUploads() {
        const fileUploads = document.querySelectorAll('.file-upload');
        fileUploads.forEach(upload => {
            const input = upload.querySelector('input[type="file"]');
            const dropZone = upload.querySelector('.drop-zone');
            const preview = upload.querySelector('.file-preview');
            
            if (input && dropZone) {
                // Click to upload
                dropZone.addEventListener('click', () => input.click());
                
                // Drag and drop
                dropZone.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    dropZone.classList.add('dragover');
                });
                
                dropZone.addEventListener('dragleave', () => {
                    dropZone.classList.remove('dragover');
                });
                
                dropZone.addEventListener('drop', (e) => {
                    e.preventDefault();
                    dropZone.classList.remove('dragover');
                    this.handleFileSelect(e.dataTransfer.files[0], upload);
                });
                
                // File selection
                input.addEventListener('change', (e) => {
                    if (e.target.files.length > 0) {
                        this.handleFileSelect(e.target.files[0], upload);
                    }
                });
            }
        });
    },
    
    // Handle file selection
    handleFileSelect(file, uploadElement) {
        const preview = uploadElement.querySelector('.file-preview');
        const fileName = uploadElement.querySelector('.file-name');
        const fileSize = uploadElement.querySelector('.file-size');
        
        if (preview && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = (e) => {
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
        
        if (fileName) fileName.textContent = file.name;
        if (fileSize) fileSize.textContent = this.formatFileSize(file.size);
        
        uploadElement.classList.add('has-file');
    },
    
    // Format file size
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // ============================================
    // Data Table Functions
    // ============================================
    
    // Initialize data tables
    initializeDataTables() {
        const tables = document.querySelectorAll('.data-table');
        tables.forEach(table => {
            this.initializeDataTable(table);
        });
    },
    
    // Initialize data table
    initializeDataTable(table) {
        const searchInput = table.querySelector('.table-search');
        const pagination = table.querySelector('.table-pagination');
        
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.filterTable(table, e.target.value);
            });
        }
        
        if (pagination) {
            this.initializeTablePagination(table);
        }
    },
    
    // Filter table
    filterTable(table, searchTerm) {
        const rows = table.querySelectorAll('tbody tr');
        const term = searchTerm.toLowerCase();
        
        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(term) ? '' : 'none';
        });
    },
    
    // Initialize table pagination
    initializeTablePagination(table) {
        const rows = Array.from(table.querySelectorAll('tbody tr'));
        const pagination = table.querySelector('.table-pagination');
        const itemsPerPage = 10;
        let currentPage = 1;
        
        const showPage = (page) => {
            const start = (page - 1) * itemsPerPage;
            const end = start + itemsPerPage;
            
            rows.forEach((row, index) => {
                row.style.display = index >= start && index < end ? '' : 'none';
            });
            
            this.updatePaginationControls(pagination, page, Math.ceil(rows.length / itemsPerPage));
        };
        
        showPage(1);
    },
    
    // Update pagination controls
    updatePaginationControls(pagination, currentPage, totalPages) {
        // Implementation for pagination controls
    },
    
    // ============================================
    // Notification Functions
    // ============================================
    
    // Show notification
    showNotification(message, type = 'info', duration = 5000) {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type} fade-in`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas fa-${this.getNotificationIcon(type)}"></i>
                <span>${message}</span>
                <button class="notification-close" onclick="this.parentElement.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        // Add to notifications container
        let container = document.getElementById('notifications');
        if (!container) {
            container = document.createElement('div');
            container.id = 'notifications';
            container.className = 'notifications-container';
            document.body.appendChild(container);
        }
        
        container.appendChild(notification);
        
        // Auto remove
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, duration);
    },
    
    // Get notification icon
    getNotificationIcon(type) {
        const icons = {
            success: 'check-circle',
            error: 'exclamation-circle',
            warning: 'exclamation-triangle',
            info: 'info-circle'
        };
        return icons[type] || 'info-circle';
    },
    
    // ============================================
    // API Functions
    // ============================================
    
    // Make API request
    async apiRequest(endpoint, options = {}) {
        const url = this.apiBase + endpoint;
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        };
        
        const finalOptions = { ...defaultOptions, ...options };
        
        try {
            const response = await fetch(url, finalOptions);
            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.message || 'Request failed');
            }
            
            return data;
        } catch (error) {
            console.error('API request error:', error);
            this.showNotification(error.message, 'error');
            throw error;
        }
    },
    
    // Upload file
    async uploadFile(file, category, referenceId = null, description = '') {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('category', category);
        formData.append('reference_id', referenceId);
        formData.append('description', description);
        
        return this.apiRequest('file-storage.php?endpoint=upload', {
            method: 'POST',
            body: formData,
            headers: {} // Let browser set Content-Type for FormData
        });
    },
    
    // ============================================
    // Utility Functions
    // ============================================
    
    // Format date
    formatDate(date, format = 'short') {
        const d = new Date(date);
        const options = {
            short: { year: 'numeric', month: 'short', day: 'numeric' },
            long: { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' },
            time: { hour: '2-digit', minute: '2-digit' }
        };
        
        return d.toLocaleDateString(this.language === 'ar' ? 'ar-EG' : 'en-US', options[format] || options.short);
    },
    
    // Format number
    formatNumber(number, decimals = 0) {
        return new Intl.NumberFormat(this.language === 'ar' ? 'ar-EG' : 'en-US', {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals
        }).format(number);
    },
    
    // Format currency
    formatCurrency(amount, currency = 'EGP') {
        return new Intl.NumberFormat(this.language === 'ar' ? 'ar-EG' : 'en-US', {
            style: 'currency',
            currency: currency
        }).format(amount);
    },
    
    // Debounce function
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // Throttle function
    throttle(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },
    
    // Generate unique ID
    generateId(prefix = 'id') {
        return prefix + '_' + Math.random().toString(36).substr(2, 9);
    },
    
    // Copy to clipboard
    async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            this.showNotification('Copied to clipboard', 'success');
        } catch (err) {
            console.error('Failed to copy text: ', err);
            this.showNotification('Failed to copy to clipboard', 'error');
        }
    },
    
    // Download file
    downloadFile(url, filename) {
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    },
    
    // Print element
    printElement(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                    <head>
                        <title>Print</title>
                        <link rel="stylesheet" href="${this.assetsBase}css/unified-design-system.css">
                    </head>
                    <body>
                        ${element.innerHTML}
                    </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.print();
        }
    },
    
    // ============================================
    // Authentication Functions
    // ============================================
    
    // Show login dialog
    showLoginDialog() {
        // Implementation for login dialog
        this.showModal('loginModal');
    },
    
    // Login
    async login(email, password) {
        try {
            const result = await this.apiRequest('auth.php?endpoint=login', {
                method: 'POST',
                body: JSON.stringify({ email, password })
            });
            
            if (result.success) {
                this.currentUser = result.user;
                sessionStorage.setItem('currentUser', JSON.stringify(this.currentUser));
                this.updateUserMenu();
                this.showNotification('Login successful', 'success');
                return true;
            }
        } catch (error) {
            return false;
        }
    },
    
    // Logout
    logout() {
        sessionStorage.removeItem('currentUser');
        this.currentUser = null;
        this.updateUserMenu();
        this.showNotification('Logged out successfully', 'info');
        
        // Redirect to login page if needed
        setTimeout(() => {
            window.location.href = '/login.html';
        }, 1000);
    },
    
    // Check authentication
    isAuthenticated() {
        return this.currentUser !== null;
    },
    
    // Check authorization
    hasRole(role) {
        return this.currentUser && this.currentUser.role === role;
    },
    
    // ============================================
    // Animation Functions
    // ============================================
    
    // Animate element
    animateElement(element, animation, duration = 500) {
        element.style.animation = `${animation} ${duration}ms ease-in-out`;
        
        return new Promise(resolve => {
            setTimeout(() => {
                element.style.animation = '';
                resolve();
            }, duration);
        });
    },
    
    // Fade in element
    fadeIn(element, duration = 500) {
        element.style.opacity = '0';
        element.style.display = 'block';
        
        return this.animateElement(element, 'fadeIn', duration);
    },
    
    // Fade out element
    fadeOut(element, duration = 500) {
        return this.animateElement(element, 'fadeOut', duration).then(() => {
            element.style.display = 'none';
        });
    },
    
    // Slide up element
    slideUp(element, duration = 500) {
        return this.animateElement(element, 'slideUp', duration);
    },
    
    // Slide down element
    slideDown(element, duration = 500) {
        return this.animateElement(element, 'slideDown', duration);
    },
    
    // ============================================
    // Tooltip Functions
    // ============================================
    
    // Initialize tooltips
    initializeTooltips() {
        const tooltipElements = document.querySelectorAll('[data-tooltip]');
        tooltipElements.forEach(element => {
            element.addEventListener('mouseenter', (e) => {
                this.showTooltip(e.target);
            });
            
            element.addEventListener('mouseleave', (e) => {
                this.hideTooltip();
            });
        });
    },
    
    // Show tooltip
    showTooltip(element) {
        const text = element.getAttribute('data-tooltip');
        if (!text) return;
        
        // Remove existing tooltip
        this.hideTooltip();
        
        const tooltip = document.createElement('div');
        tooltip.className = 'tooltip';
        tooltip.textContent = text;
        
        document.body.appendChild(tooltip);
        
        // Position tooltip
        const rect = element.getBoundingClientRect();
        tooltip.style.left = rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2) + 'px';
        tooltip.style.top = rect.top - tooltip.offsetHeight - 10 + 'px';
        
        // Show tooltip
        setTimeout(() => {
            tooltip.classList.add('show');
        }, 10);
    },
    
    // Hide tooltip
    hideTooltip() {
        const tooltip = document.querySelector('.tooltip');
        if (tooltip) {
            tooltip.remove();
        }
    }
};

// ============================================
// Initialize on DOM ready
// ============================================
document.addEventListener('DOMContentLoaded', () => {
    AUTO_TESTER.init();
});

// ============================================
// Global functions for backward compatibility
// ============================================
window.showModal = (modalId) => AUTO_TESTER.showModal(modalId);
window.closeModal = (modalId) => AUTO_TESTER.closeModal(modalId);
window.showNotification = (message, type, duration) => AUTO_TESTER.showNotification(message, type, duration);
window.formatDate = (date, format) => AUTO_TESTER.formatDate(date, format);
window.formatNumber = (number, decimals) => AUTO_TESTER.formatNumber(number, decimals);
window.copyToClipboard = (text) => AUTO_TESTER.copyToClipboard(text);

// Export for module usage
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AUTO_TESTER;
}
