// AUTO TESTER - Toast Notification System

// Toast Configuration
const toastConfig = {
    defaultDuration: 4000,
    maxToasts: 5,
    position: 'top-right',
    animationDuration: 300,
    types: {
        success: { icon: 'fa-check-circle', color: '#16a34a' },
        error: { icon: 'fa-exclamation-circle', color: '#dc2626' },
        warning: { icon: 'fa-exclamation-triangle', color: '#f59e0b' },
        info: { icon: 'fa-info-circle', color: '#0ea5e9' },
        loading: { icon: 'fa-spinner', color: '#6366f1' }
    }
};

// Toast container
let toastContainer = null;
let toastCounter = 0;

// Create toast container
function createToastContainer() {
    if (toastContainer) return;
    
    toastContainer = document.createElement('div');
    toastContainer.id = 'toastContainer';
    toastContainer.className = 'toast-container';
    toastContainer.setAttribute('aria-live', 'polite');
    toastContainer.setAttribute('aria-label', 'Notifications');
    document.body.appendChild(toastContainer);
}

// Create toast element
function createToast(message, type = 'success', options = {}) {
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.id = `toast-${++toastCounter}`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', type === 'error' ? 'assertive' : 'polite');
    
    const config = toastConfig.types[type] || toastConfig.types.info;
    const duration = options.duration || toastConfig.defaultDuration;
    const closable = options.closable !== false;
    const persistent = options.persistent || false;
    
    toast.innerHTML = `
        <div class="toast-content">
            <div class="toast-icon">
                <i class="fas ${config.icon} ${type === 'loading' ? 'fa-spin' : ''}"></i>
            </div>
            <div class="toast-message">${message}</div>
            ${closable ? '<button type="button" class="toast-close" aria-label="Close notification"><i class="fas fa-times"></i></button>' : ''}
        </div>
        ${options.progress ? '<div class="toast-progress"><div class="toast-progress-bar"></div></div>' : ''}
    `;
    
    // Store options
    toast.dataset.duration = duration;
    toast.dataset.persistent = persistent;
    toast.dataset.closable = closable;
    toast.dataset.type = type;
    
    return toast;
}

// Show toast
function showToast(message, type = 'success', options = {}) {
    createToastContainer();
    
    // Remove old toasts if max reached
    const existingToasts = toastContainer.querySelectorAll('.toast');
    if (existingToasts.length >= toastConfig.maxToasts) {
        const oldestToast = existingToasts[0];
        hideToast(oldestToast);
    }
    
    // Create new toast
    const toast = createToast(message, type, options);
    toastContainer.appendChild(toast);
    
    // Trigger animation
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    // Auto-hide if not persistent
    if (!options.persistent) {
        const duration = options.duration || toastConfig.defaultDuration;
        setTimeout(() => {
            hideToast(toast);
        }, duration);
        
        // Start progress bar if enabled
        if (options.progress) {
            startProgress(toast, duration);
        }
    }
    
    // Add close functionality
    const closeBtn = toast.querySelector('.toast-close');
    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            hideToast(toast);
        });
    }
    
    return toast;
}

// Hide toast
function hideToast(toast) {
    if (!toast || !toast.parentNode) return;
    
    toast.classList.remove('show');
    toast.classList.add('hide');
    
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, toastConfig.animationDuration);
}

// Start progress bar
function startProgress(toast, duration) {
    const progressBar = toast.querySelector('.toast-progress-bar');
    if (!progressBar) return;
    
    progressBar.style.transition = `width ${duration}ms linear`;
    progressBar.style.width = '0%';
    
    setTimeout(() => {
        progressBar.style.width = '100%';
    }, 10);
}

// Toast types
function showSuccessToast(message, options = {}) {
    return showToast(message, 'success', { ...options, progress: true });
}

function showErrorToast(message, options = {}) {
    return showToast(message, 'error', { ...options, duration: 6000, progress: true });
}

function showWarningToast(message, options = {}) {
    return showToast(message, 'warning', { ...options, duration: 5000, progress: true });
}

function showInfoToast(message, options = {}) {
    return showToast(message, 'info', options);
}

function showLoadingToast(message = 'Loading...', options = {}) {
    return showToast(message, 'loading', { ...options, persistent: true, closable: false });
}

// Update loading toast
function updateLoadingToast(toast, message, type = 'loading') {
    if (!toast || !toast.parentNode) return;
    
    const messageEl = toast.querySelector('.toast-message');
    const iconEl = toast.querySelector('.toast-icon i');
    
    if (messageEl) {
        messageEl.textContent = message;
    }
    
    if (iconEl) {
        iconEl.className = `fas ${toastConfig.types[type].icon} ${type === 'loading' ? 'fa-spin' : ''}`;
    }
    
    // Update toast type
    toast.classList.remove(`toast-${toast.dataset.type}`);
    toast.classList.add(`toast-${type}`);
    toast.dataset.type = type;
    
    // Make it closable if not loading anymore
    if (type !== 'loading') {
        toast.dataset.persistent = 'false';
        toast.dataset.closable = 'true';
        
        // Add close button if not present
        if (!toast.querySelector('.toast-close')) {
            const closeBtn = document.createElement('button');
            closeBtn.type = 'button';
            closeBtn.className = 'toast-close';
            closeBtn.setAttribute('aria-label', 'Close notification');
            closeBtn.innerHTML = '<i class="fas fa-times"></i>';
            closeBtn.addEventListener('click', () => hideToast(toast));
            
            const content = toast.querySelector('.toast-content');
            content.appendChild(closeBtn);
        }
        
        // Auto-hide after delay
        setTimeout(() => {
            hideToast(toast);
        }, toastConfig.defaultDuration);
    }
}

// Clear all toasts
function clearAllToasts() {
    if (!toastContainer) return;
    
    const toasts = toastContainer.querySelectorAll('.toast');
    toasts.forEach(toast => {
        hideToast(toast);
    });
}

// Toast queue system
const toastQueue = [];
let isProcessingQueue = false;

function processToastQueue() {
    if (isProcessingQueue || toastQueue.length === 0) return;
    
    isProcessingQueue = true;
    const nextToast = toastQueue.shift();
    
    showToast(nextToast.message, nextToast.type, nextToast.options);
    
    setTimeout(() => {
        isProcessingQueue = false;
        processToastQueue();
    }, 500);
}

function queueToast(message, type, options) {
    toastQueue.push({ message, type, options });
    processToastQueue();
}

// Context-specific toasts
function showLoginSuccess() {
    return showSuccessToast('Login successful! Welcome back.');
}

function showLoginError() {
    return showErrorToast('Login failed. Please check your credentials.');
}

function showLogoutSuccess() {
    return showInfoToast('You have been logged out successfully.');
}

function showSaveSuccess() {
    return showSuccessToast('Changes saved successfully!');
}

function showSaveError() {
    return showErrorToast('Failed to save changes. Please try again.');
}

function showNetworkError() {
    return showErrorToast('Network error. Please check your connection.');
}

function showValidationError(message) {
    return showWarningToast(message || 'Please check your input and try again.');
}

function showUploadSuccess(filename) {
    return showSuccessToast(`${filename} uploaded successfully!`);
}

function showUploadError(filename) {
    return showErrorToast(`Failed to upload ${filename}. Please try again.`);
}

function showDeleteSuccess(item) {
    return showSuccessToast(`${item} deleted successfully!`);
}

function showDeleteError(item) {
    return showErrorToast(`Failed to delete ${item}. Please try again.`);
}

// Export functions for global use
window.showToast = showToast;
window.showSuccessToast = showSuccessToast;
window.showErrorToast = showErrorToast;
window.showWarningToast = showWarningToast;
window.showInfoToast = showInfoToast;
window.showLoadingToast = showLoadingToast;
window.updateLoadingToast = updateLoadingToast;
window.hideToast = hideToast;
window.clearAllToasts = clearAllToasts;
window.queueToast = queueToast;

// Context-specific exports
window.showLoginSuccess = showLoginSuccess;
window.showLoginError = showLoginError;
window.showLogoutSuccess = showLogoutSuccess;
window.showSaveSuccess = showSaveSuccess;
window.showSaveError = showSaveError;
window.showNetworkError = showNetworkError;
window.showValidationError = showValidationError;
window.showUploadSuccess = showUploadSuccess;
window.showUploadError = showUploadError;
window.showDeleteSuccess = showDeleteSuccess;
window.showDeleteError = showDeleteError;

// Initialize toast system
document.addEventListener('DOMContentLoaded', () => {
    // Create container
    createToastContainer();
    
    // Handle page visibility changes
    document.addEventListener('visibilitychange', () => {
        if (!document.hidden) {
            // Clear toasts when page becomes visible again
            const toasts = toastContainer.querySelectorAll('.toast');
            toasts.forEach(toast => {
                if (!toast.dataset.persistent) {
                    hideToast(toast);
                }
            });
        }
    });
    
    // Handle escape key to close all toasts
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            clearAllToasts();
        }
    });
    
    // Auto-hide toasts on page unload
    window.addEventListener('beforeunload', () => {
        clearAllToasts();
    });
});

// Development helpers (remove in production)
if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    window.testToast = {
        success: () => showSuccessToast('Success message test'),
        error: () => showErrorToast('Error message test'),
        warning: () => showWarningToast('Warning message test'),
        info: () => showInfoToast('Info message test'),
        loading: () => showLoadingToast('Loading test'),
        clear: () => clearAllToasts(),
        queue: () => {
            queueToast('Queued message 1', 'info');
            queueToast('Queued message 2', 'success');
            queueToast('Queued message 3', 'warning');
        }
    };
}
