/**
 * Toast Notification System
 * Professional toast notifications using Bootstrap Toast component
 * Replaces all alert() calls with elegant toast popups
 */

// Toast configuration
const ToastConfig = {
    duration: 5000, // Default duration in milliseconds
    position: 'top-end', // top-start, top-center, top-end, bottom-start, bottom-center, bottom-end
    stackLimit: 3, // Maximum number of toasts to show at once
    animation: true,
    autohide: true
};

// Toast types with icons and colors
const ToastTypes = {
    success: {
        icon: 'fas fa-check-circle',
        class: 'bg-success',
        title: 'Success'
    },
    error: {
        icon: 'fas fa-times-circle',
        class: 'bg-danger',
        title: 'Error'
    },
    warning: {
        icon: 'fas fa-exclamation-triangle',
        class: 'bg-warning',
        title: 'Warning'
    },
    info: {
        icon: 'fas fa-info-circle',
        class: 'bg-info',
        title: 'Information'
    }
};

/**
 * Initialize toast container
 */
function initToastContainer() {
    if (document.getElementById('toast-container')) {
        return; // Already initialized
    }

    const container = document.createElement('div');
    container.id = 'toast-container';
    container.className = `toast-container position-fixed p-3 ${ToastConfig.position}`;
    container.style.zIndex = '9999';
    document.body.appendChild(container);
}

/**
 * Create and show a toast notification
 * @param {string} message - The message to display
 * @param {string} type - Toast type: success, error, warning, info
 * @param {object} options - Additional options
 */
function showToast(message, type = 'info', options = {}) {
    initToastContainer();
    
    const toastType = ToastTypes[type] || ToastTypes.info;
    const duration = options.duration || ToastConfig.duration;
    const title = options.title || toastType.title;
    const autohide = options.autohide !== undefined ? options.autohide : ToastConfig.autohide;
    
    // Check stack limit
    const container = document.getElementById('toast-container');
    const existingToasts = container.querySelectorAll('.toast');
    if (existingToasts.length >= ToastConfig.stackLimit) {
        // Remove oldest toast
        existingToasts[0].remove();
    }
    
    // Create toast element
    const toastId = 'toast-' + Date.now();
    const toastEl = document.createElement('div');
    toastEl.id = toastId;
    toastEl.className = 'toast';
    toastEl.setAttribute('role', 'alert');
    toastEl.setAttribute('aria-live', 'assertive');
    toastEl.setAttribute('aria-atomic', 'true');
    
    toastEl.innerHTML = `
        <div class="toast-header ${toastType.class} text-white">
            <i class="${toastType.icon} me-2"></i>
            <strong class="me-auto">${title}</strong>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body">
            ${message}
        </div>
    `;
    
    container.appendChild(toastEl);
    
    // Initialize Bootstrap toast
    const toast = new bootstrap.Toast(toastEl, {
        animation: ToastConfig.animation,
        autohide: autohide,
        delay: duration
    });
    
    // Show toast
    toast.show();
    
    // Remove from DOM after hidden
    toastEl.addEventListener('hidden.bs.toast', function () {
        toastEl.remove();
    });
    
    return toast;
}

/**
 * Success toast (green)
 */
function showSuccess(message, options = {}) {
    return showToast(message, 'success', options);
}

/**
 * Error toast (red)
 */
function showError(message, options = {}) {
    return showToast(message, 'error', options);
}

/**
 * Warning toast (yellow/orange)
 */
function showWarning(message, options = {}) {
    return showToast(message, 'warning', options);
}

/**
 * Info toast (blue)
 */
function showInfo(message, options = {}) {
    return showToast(message, 'info', options);
}

/**
 * Confirmation toast with Yes/No buttons
 * @param {string} message - Confirmation message
 * @param {function} onConfirm - Callback when confirmed
 * @param {function} onCancel - Callback when cancelled
 */
function showConfirm(message, onConfirm, onCancel = null) {
    initToastContainer();
    
    const container = document.getElementById('toast-container');
    const toastId = 'toast-confirm-' + Date.now();
    const toastEl = document.createElement('div');
    toastEl.id = toastId;
    toastEl.className = 'toast';
    toastEl.setAttribute('role', 'alert');
    toastEl.setAttribute('aria-live', 'assertive');
    toastEl.setAttribute('aria-atomic', 'true');
    
    toastEl.innerHTML = `
        <div class="toast-header bg-warning text-dark">
            <i class="fas fa-question-circle me-2"></i>
            <strong class="me-auto">Confirm</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body">
            <p class="mb-3">${message}</p>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-primary confirm-yes flex-grow-1">
                    <i class="fas fa-check me-1"></i>Yes
                </button>
                <button type="button" class="btn btn-sm btn-secondary confirm-no flex-grow-1" data-bs-dismiss="toast">
                    <i class="fas fa-times me-1"></i>No
                </button>
            </div>
        </div>
    `;
    
    container.appendChild(toastEl);
    
    // Initialize Bootstrap toast (no autohide for confirmation)
    const toast = new bootstrap.Toast(toastEl, {
        animation: true,
        autohide: false
    });
    
    // Add event listeners
    const yesBtn = toastEl.querySelector('.confirm-yes');
    const noBtn = toastEl.querySelector('.confirm-no');
    
    yesBtn.addEventListener('click', function() {
        toast.hide();
        if (onConfirm) onConfirm();
    });
    
    if (onCancel) {
        noBtn.addEventListener('click', function() {
            onCancel();
        });
    }
    
    // Show toast
    toast.show();
    
    // Remove from DOM after hidden
    toastEl.addEventListener('hidden.bs.toast', function () {
        toastEl.remove();
    });
    
    return toast;
}

/**
 * Replace native alert() with toast
 * Call this function to globally override alert()
 */
function replaceAlert() {
    window.alert = function(message) {
        showWarning(message);
    };
}

// Export functions for use in modules or direct access
window.Toast = {
    show: showToast,
    success: showSuccess,
    error: showError,
    warning: showWarning,
    info: showInfo,
    confirm: showConfirm,
    replaceAlert: replaceAlert,
    config: ToastConfig
};

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