/**
 * Toast Notification System for MPV.Rocks Installer
 * Provides toast notifications for job completion and general messages
 * 
 * Accessibility features:
 * - ARIA live regions for screen reader announcements
 * - Keyboard dismissible (Enter/Space)
 * - High contrast support
 */

(function() {
    'use strict';

    // Toast container reference
    let toastContainer = null;

    // Default options
    const DEFAULTS = {
        duration: 5000,
        position: 'bottom-right',
        maxToasts: 5
    };

    /**
     * Initialize the toast container
     */
    function initToastContainer() {
        if (toastContainer) return;

        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container';
        toastContainer.setAttribute('role', 'region');
        toastContainer.setAttribute('aria-label', 'Notifications');
        toastContainer.setAttribute('aria-live', 'polite');
        document.body.appendChild(toastContainer);
    }

    /**
     * Show a toast notification
     * @param {string} message - The message to display
     * @param {string} type - Toast type: 'success', 'error', 'info', 'warning'
     * @param {number} duration - Duration in milliseconds (0 for no auto-dismiss)
     * @returns {HTMLElement} The toast element
     */
    window.showToast = function(message, type = 'info', duration = DEFAULTS.duration) {
        initToastContainer();

        // Limit number of toasts
        const existingToasts = toastContainer.querySelectorAll('.toast');
        if (existingToasts.length >= DEFAULTS.maxToasts) {
            existingToasts[0].remove();
        }

        // Create toast element
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.setAttribute('role', 'alert');
        toast.setAttribute('tabindex', '0');

        // Get icon based on type
        const icon = getToastIcon(type);

        // Build toast content
        toast.innerHTML = `
            <div class="toast-content">
                <span class="toast-icon" aria-hidden="true">${icon}</span>
                <span class="toast-message">${escapeHtml(message)}</span>
            </div>
            <button class="toast-close" aria-label="Dismiss notification">
                <i class="bx bx-x" aria-hidden="true"></i>
            </button>
        `;

        // Add dismiss handlers
        const dismissBtn = toast.querySelector('.toast-close');
        dismissBtn.addEventListener('click', () => dismissToast(toast));
        toast.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                dismissToast(toast);
            }
        });

        // Add to container
        toastContainer.appendChild(toast);

        // Trigger animation
        requestAnimationFrame(() => {
            toast.classList.add('toast-visible');
        });

        // Auto-dismiss after duration (if set)
        if (duration > 0) {
            toast.dataset.timeout = setTimeout(() => {
                dismissToast(toast);
            }, duration);
        }

        // Announce to screen readers
        announceToast(message, type);

        return toast;
    };

    /**
     * Get action verb for job type
     * @param {string} type - Job type (install, uninstall, update)
     * @returns {Object} - {verb: string, noun: string}
     */
    function getJobActionLabels(type) {
        switch (type) {
            case 'install':
                return { verb: 'Installing', noun: 'Installed' };
            case 'uninstall':
                return { verb: 'Uninstalling', noun: 'Uninstalled' };
            case 'update':
                return { verb: 'Updating', noun: 'Updated' };
            default:
                return { verb: 'Processing', noun: 'Processed' };
        }
    }

    /**
     * Show a job started toast
     * @param {Object} job - The job object with type, appName, etc.
     */
    window.showJobStartedToast = function(job) {
        if (!job) return;

        const appName = job.appName || job.app_name || 'Application';
        const labels = getJobActionLabels(job.type);
        const icon = job.type === 'uninstall' ? '🗑️' : '⏳';

        // Show info toast that auto-dismisses when job completes
        const toast = showToast(`${icon} ${labels.verb} ${appName}...`, 'info', 0);

        // Store job ID so we can dismiss this toast when job completes
        if (job.id) {
            toast.dataset.jobId = job.id;
        }

        // Add "View Progress" button
        const contentDiv = toast.querySelector('.toast-content');
        if (contentDiv && job.id) {
            const progressBtn = document.createElement('button');
            progressBtn.className = 'toast-progress-btn';
            progressBtn.textContent = 'View Progress';
            progressBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                // Trigger apps list refresh when viewing job details
                if (window.jobManager && window.jobManager.refreshAppsList) {
                    window.jobManager.refreshAppsList().catch(() => {});
                }
                if (window.showJobOutput) {
                    window.showJobOutput(job.id);
                } else {
                    window.location.href = `/tasks?job=${job.id}`;
                }
            });
            contentDiv.appendChild(progressBtn);
        }

        // Make the whole toast clickable (except buttons)
        toast.style.cursor = 'pointer';
        toast.addEventListener('click', (e) => {
            // Don't trigger if clicking on buttons
            if (e.target.closest('button')) return;
            
            // Trigger apps list refresh when viewing job details
            if (window.jobManager && window.jobManager.refreshAppsList) {
                window.jobManager.refreshAppsList().catch(() => {});
            }
            
            if (job.id && window.showJobOutput) {
                window.showJobOutput(job.id);
            } else if (job.id) {
                window.location.href = `/tasks?job=${job.id}`;
            }
        });

        return toast;
    };

    /**
     * Show a job completion toast
     * @param {Object} job - The job object with status, appName, etc.
     */
    window.showJobToast = function(job) {
        if (!job) return;

        const appName = job.appName || job.app_name || 'Application';
        const labels = getJobActionLabels(job.type);

        // Dismiss any "started" toast for this job
        if (job.id) {
            const startedToast = document.querySelector(`.toast[data-job-id="${job.id}"]`);
            if (startedToast) {
                dismissToast(startedToast);
            }
        }

        if (job.status === 'complete' || job.status === 'completed' || job.success) {
            // Success toast
            const icon = job.type === 'uninstall' ? '✅' : '✅';
            const toast = showToast(`${icon} ${appName} ${labels.noun}`, 'success', 5000);

            // Add view details button for success (optional)
            addViewDetailsButton(toast, job.id || job.job_id, 'View Details');
        } else if (job.status === 'error') {
            // Error toast with view details button
            const toast = showToast(`❌ ${appName} ${labels.noun} Failed`, 'error', 0); // Don't auto-dismiss errors

            // Add view details button
            addViewDetailsButton(toast, job.id || job.job_id, 'View Details');
        }
    };

    /**
     * Add a view details button to a toast
     * @param {HTMLElement} toast - The toast element
     * @param {string} jobId - The job ID
     * @param {string} buttonText - Button text
     */
    function addViewDetailsButton(toast, jobId, buttonText) {
        if (!jobId) return;

        const contentDiv = toast.querySelector('.toast-content');
        if (!contentDiv) return;

        const detailsBtn = document.createElement('button');
        detailsBtn.className = 'toast-details-btn';
        detailsBtn.textContent = buttonText;
        detailsBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            dismissToast(toast);
            
            // Trigger apps list refresh when viewing completed job details
            // This ensures the list is up-to-date when user views the job
            if (window.jobManager && window.jobManager.refreshAppsList) {
                window.jobManager.refreshAppsList().catch(() => {
                    // Ignore errors - refresh is best effort
                });
            }
            
            // Call the global showJobOutput function if available
            if (window.showJobOutput) {
                window.showJobOutput(jobId);
            } else {
                // Fallback: navigate to tasks page
                window.location.href = `/tasks?job=${jobId}`;
            }
        });

        contentDiv.appendChild(detailsBtn);
    }

    /**
     * Dismiss a toast with animation
     * @param {HTMLElement} toast - The toast element to dismiss
     */
    function dismissToast(toast) {
        if (!toast || toast.classList.contains('toast-dismissing')) return;

        // Clear auto-dismiss timeout
        if (toast.dataset.timeout) {
            clearTimeout(parseInt(toast.dataset.timeout));
        }

        // Add dismissing class for animation
        toast.classList.add('toast-dismissing');
        toast.classList.remove('toast-visible');

        // Remove after animation
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }

    /**
     * Get the icon for a toast type
     * @param {string} type - Toast type
     * @returns {string} Icon HTML or emoji
     */
    function getToastIcon(type) {
        switch (type) {
            case 'success':
                return '<i class="bx bx-check-circle"></i>';
            case 'error':
                return '<i class="bx bx-x-circle"></i>';
            case 'warning':
                return '<i class="bx bx-error"></i>';
            case 'info':
            default:
                return '<i class="bx bx-info-circle"></i>';
        }
    }

    /**
     * Announce toast to screen readers
     * @param {string} message - The message
     * @param {string} type - Toast type
     */
    function announceToast(message, type) {
        const announcer = document.getElementById('alert-announcer');
        if (announcer) {
            const prefix = type === 'error' ? 'Error: ' : 
                          type === 'success' ? 'Success: ' : 
                          type === 'warning' ? 'Warning: ' : '';
            announcer.textContent = prefix + message;
        }
    }

    /**
     * Escape HTML to prevent XSS
     * @param {string} text - Text to escape
     * @returns {string} Escaped text
     */
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Convenience methods
    window.toast = {
        success: (message, duration) => window.showToast(message, 'success', duration),
        error: (message, duration) => window.showToast(message, 'error', duration),
        warning: (message, duration) => window.showToast(message, 'warning', duration),
        info: (message, duration) => window.showToast(message, 'info', duration),
        dismiss: dismissToast
    };

    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initToastContainer);
    } else {
        initToastContainer();
    }

})();
