/**
 * BlogiBot Toastr - Reusable Toast Notification Component
 * A lightweight, customizable toast notification system
 */

class BlogiToastr {
    constructor(options = {}) {
        this.options = {
            position: options.position || 'top-right',
            autoClose: options.autoClose !== false,
            timeout: options.timeout || 4000,
            maxToasts: options.maxToasts || 5,
            animation: options.animation || 'slide',
            ...options
        };
        
        this.toasts = [];
        this.container = null;
        this.init();
    }
    
    init() {
        this.createContainer();
        this.addStyles();
    }
    
    createContainer() {
        // Remove existing container if any
        const existingContainer = document.getElementById('blogibot-toastr-container');
        if (existingContainer) {
            existingContainer.remove();
        }
        
        this.container = document.createElement('div');
        this.container.id = 'blogibot-toastr-container';
        this.container.className = `blogibot-toastr-container ${this.options.position}`;
        document.body.appendChild(this.container);
    }
    
    addStyles() {
        // Check if styles already exist
        if (document.getElementById('blogibot-toastr-styles')) {
            return;
        }
        
        const style = document.createElement('style');
        style.id = 'blogibot-toastr-styles';
        style.textContent = `
            .blogibot-toastr-container {
                position: fixed;
                z-index: 999999;
                pointer-events: none;
                max-width: 400px;
            }
            
            .blogibot-toastr-container.top-right {
                top: 20px;
                right: 20px;
            }
            
            .blogibot-toastr-container.top-left {
                top: 20px;
                left: 20px;
            }
            
            .blogibot-toastr-container.bottom-right {
                bottom: 20px;
                right: 20px;
            }
            
            .blogibot-toastr-container.bottom-left {
                bottom: 20px;
                left: 20px;
            }
            
            .blogibot-toastr-container.top-center {
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
            }
            
            .blogibot-toastr-container.bottom-center {
                bottom: 20px;
                left: 50%;
                transform: translateX(-50%);
            }
            
            .blogibot-toast {
                background: #333;
                color: white;
                padding: 12px 16px;
                margin-bottom: 10px;
                border-radius: 6px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
                display: flex;
                align-items: center;
                min-width: 300px;
                max-width: 400px;
                pointer-events: auto;
                opacity: 0;
                transform: translateX(100%);
                transition: all 0.3s ease;
                position: relative;
                overflow: hidden;
            }
            
            .blogibot-toast.show {
                opacity: 1;
                transform: translateX(0);
            }
            
            .blogibot-toast.slide-out {
                opacity: 0;
                transform: translateX(100%);
            }
            
            .blogibot-toast.success {
                background: linear-gradient(135deg, #28a745, #20c997);
                border-left: 4px solid #1e7e34;
            }
            
            .blogibot-toast.error {
                background: linear-gradient(135deg, #dc3545, #e74c3c);
                border-left: 4px solid #bd2130;
            }
            
            .blogibot-toast.warning {
                background: linear-gradient(135deg, #ffc107, #f39c12);
                border-left: 4px solid #d39e00;
                color: #212529;
            }
            
            .blogibot-toast.info {
                background: linear-gradient(135deg, #17a2b8, #3498db);
                border-left: 4px solid #117a8b;
            }
            
            .blogibot-toast-icon {
                font-size: 18px;
                margin-right: 12px;
                flex-shrink: 0;
            }
            
            .blogibot-toast-content {
                flex: 1;
                word-wrap: break-word;
            }
            
            .blogibot-toast-title {
                font-weight: 600;
                margin-bottom: 4px;
                font-size: 14px;
            }
            
            .blogibot-toast-message {
                font-size: 13px;
                opacity: 0.9;
                line-height: 1.4;
            }
            
            .blogibot-toast-close {
                background: none;
                border: none;
                color: inherit;
                cursor: pointer;
                font-size: 16px;
                padding: 0;
                margin-left: 12px;
                opacity: 0.7;
                flex-shrink: 0;
                width: 20px;
                height: 20px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .blogibot-toast-close:hover {
                opacity: 1;
            }
            
            .blogibot-toast-progress {
                position: absolute;
                bottom: 0;
                left: 0;
                height: 3px;
                background: rgba(255, 255, 255, 0.3);
                transition: width linear;
            }
            
            .blogibot-toast.success .blogibot-toast-progress {
                background: rgba(255, 255, 255, 0.4);
            }
            
            .blogibot-toast.error .blogibot-toast-progress {
                background: rgba(255, 255, 255, 0.4);
            }
            
            .blogibot-toast.warning .blogibot-toast-progress {
                background: rgba(0, 0, 0, 0.2);
            }
            
            .blogibot-toast.info .blogibot-toast-progress {
                background: rgba(255, 255, 255, 0.4);
            }
            
            /* Animation for left positioned toasts */
            .blogibot-toastr-container.top-left .blogibot-toast,
            .blogibot-toastr-container.bottom-left .blogibot-toast {
                transform: translateX(-100%);
            }
            
            .blogibot-toastr-container.top-left .blogibot-toast.show,
            .blogibot-toastr-container.bottom-left .blogibot-toast.show {
                transform: translateX(0);
            }
            
            .blogibot-toastr-container.top-left .blogibot-toast.slide-out,
            .blogibot-toastr-container.bottom-left .blogibot-toast.slide-out {
                transform: translateX(-100%);
            }
            
            /* Responsive design */
            @media (max-width: 768px) {
                .blogibot-toastr-container {
                    left: 10px !important;
                    right: 10px !important;
                    max-width: none;
                    transform: none !important;
                }
                
                .blogibot-toast {
                    min-width: auto;
                    max-width: none;
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    show(message, type = 'info', options = {}) {
        const toastOptions = { ...this.options, ...options };
        const toastId = Date.now() + Math.random();
        
        // Limit number of toasts
        if (this.toasts.length >= this.options.maxToasts) {
            this.remove(this.toasts[0].id);
        }
        
        const toast = this.createToast(message, type, toastOptions, toastId);
        this.container.appendChild(toast);
        
        // Store toast reference
        this.toasts.push({ id: toastId, element: toast, options: toastOptions });
        
        // Trigger animation
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);
        
        // Auto close if enabled
        if (toastOptions.autoClose && toastOptions.timeout > 0) {
            this.startAutoClose(toastId, toastOptions.timeout);
        }
        
        return toastId;
    }
    
    createToast(message, type, options, id) {
        const toast = document.createElement('div');
        toast.className = `blogibot-toast ${type}`;
        toast.dataset.toastId = id;
        
        const icon = this.getIcon(type);
        const { title, text } = this.parseMessage(message);
        
        toast.innerHTML = `
            <div class="blogibot-toast-icon">${icon}</div>
            <div class="blogibot-toast-content">
                ${title ? `<div class="blogibot-toast-title">${title}</div>` : ''}
                <div class="blogibot-toast-message">${text}</div>
            </div>
            ${options.closable !== false ? '<button class="blogibot-toast-close">&times;</button>' : ''}
            ${options.autoClose && options.timeout ? '<div class="blogibot-toast-progress"></div>' : ''}
        `;
        
        // Add close functionality
        const closeBtn = toast.querySelector('.blogibot-toast-close');
        if (closeBtn) {
            closeBtn.addEventListener('click', () => this.remove(id));
        }
        
        // Add click to close functionality
        if (options.clickToClose !== false) {
            toast.addEventListener('click', (e) => {
                if (e.target !== closeBtn) {
                    this.remove(id);
                }
            });
        }
        
        return toast;
    }
    
    parseMessage(message) {
        if (typeof message === 'string') {
            return { title: null, text: message };
        } else if (typeof message === 'object') {
            return {
                title: message.title || null,
                text: message.message || message.text || ''
            };
        }
        return { title: null, text: String(message) };
    }
    
    getIcon(type) {
        const icons = {
            success: '✅',
            error: '❌',
            warning: '⚠️',
            info: 'ℹ️',
            default: '📢'
        };
        return icons[type] || icons.default;
    }
    
    startAutoClose(toastId, timeout) {
        const toast = this.getToastById(toastId);
        if (!toast) return;
        
        const progressBar = toast.element.querySelector('.blogibot-toast-progress');
        if (progressBar) {
            progressBar.style.width = '100%';
            progressBar.style.transition = `width ${timeout}ms linear`;
            
            setTimeout(() => {
                progressBar.style.width = '0%';
            }, 10);
        }
        
        setTimeout(() => {
            this.remove(toastId);
        }, timeout);
    }
    
    remove(toastId) {
        const toast = this.getToastById(toastId);
        if (!toast) return;
        
        toast.element.classList.add('slide-out');
        
        setTimeout(() => {
            if (toast.element.parentNode) {
                toast.element.parentNode.removeChild(toast.element);
            }
            this.toasts = this.toasts.filter(t => t.id !== toastId);
        }, 300);
    }
    
    getToastById(id) {
        return this.toasts.find(toast => toast.id === id);
    }
    
    clear() {
        this.toasts.forEach(toast => {
            if (toast.element.parentNode) {
                toast.element.parentNode.removeChild(toast.element);
            }
        });
        this.toasts = [];
    }
    
    // Convenience methods
    success(message, options = {}) {
        return this.show(message, 'success', options);
    }
    
    error(message, options = {}) {
        return this.show(message, 'error', options);
    }
    
    warning(message, options = {}) {
        return this.show(message, 'warning', options);
    }
    
    info(message, options = {}) {
        return this.show(message, 'info', options);
    }
}

// Create global instance
window.BlogiToastr = new BlogiToastr();

// Legacy compatibility - keep the old BlogToast interface
window.BlogToast = {
    show: (message, type = 'info', options = {}) => window.BlogiToastr.show(message, type, options),
    success: (message, options = {}) => window.BlogiToastr.success(message, options),
    error: (message, options = {}) => window.BlogiToastr.error(message, options),
    warning: (message, options = {}) => window.BlogiToastr.warning(message, options),
    info: (message, options = {}) => window.BlogiToastr.info(message, options),
    clear: () => window.BlogiToastr.clear()
};
