import { toast, createToaster } from './sonner-vanilla.js';

// Expose globally
window.xSonnerToasters = {};
window.xCreateToasterFunc = createToaster;
window.xToastLib = toast;

function xToast() {
    // Builder check
    if (document.querySelector('body > .brx-body.iframe')) {
        return;
    }

    // Initialize instances storage - group by container ID
    if (!window.xtoast) {
        window.xtoast = {
            Instances: {}, // Store toasters by container ID
            ContainerConfigs: {}, // Store container configs
            toastIdMap: {} // Map unique IDs to toast IDs for close button handling
        };
    }

    // Global debounce tracker for toasts
    const recentlyShownToasts = new Set();

    function showToast(notificationElement, containerElement) {
        const elementId = notificationElement.getAttribute('data-x-id');
        const containerId = containerElement.getAttribute('data-x-id');
        
        // Check if this toast was recently shown (debounce)
        if (recentlyShownToasts.has(elementId)) {
            return;
        }
        
        // Check if element is in a loop and needs product ID matching
        const interactionLoopId = notificationElement.getAttribute('data-interaction-loop-id');
        if (interactionLoopId) {
            // Extract product ID from loop ID (format: "btnezi:0:post:15343")
            const loopProductId = interactionLoopId.split(':').pop();
            
            // Get the product ID that was just added to cart from WooCommerce event
            const addedProductId = window.bricksExtrasLastAddedProduct;
            
            // If this toast is in a loop but doesn't match the added product, skip it
            if (addedProductId && loopProductId !== addedProductId) {
                return;
            }
        }
        
        // Add to debounce set
        recentlyShownToasts.add(elementId);
        
        // Remove from set after 100ms
        setTimeout(() => {
            recentlyShownToasts.delete(elementId);
        }, 100);
        
        // Show toast using sonner-vanilla with the cloned element
        if (window.xToastLib && window.xToastLib.custom && window.xCreateToasterFunc) {
            
            // Clone the notification element to get a fresh copy
            const notificationClone = notificationElement.cloneNode(true);
            notificationClone.style.display = 'block';
            
            // Attach close button handler before passing to Sonner
            // We'll use a data attribute to store a unique ID that we can use to dismiss
            const uniqueId = `toast_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            notificationClone.setAttribute('data-toast-unique-id', uniqueId);
            
            const closeBtn = notificationClone.querySelector('[data-x-toast-close]');
            if (closeBtn) {
                closeBtn.setAttribute('data-toast-unique-id', uniqueId);
                closeBtn.onclick = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    const toastId = window.xtoast.toastIdMap?.[uniqueId];
                    if (toastId) {
                        window.xToastLib.dismiss(toastId);
                    }
                };
            }
            
            // Get container config
            const containerConfigAttr = containerElement.getAttribute('data-x-toast-container');
            const containerConfig = containerConfigAttr ? JSON.parse(containerConfigAttr) : {};
            
            // Get notification config
            const notificationConfigAttr = notificationElement.getAttribute('data-x-notification');
            const notificationConfig = notificationConfigAttr ? JSON.parse(notificationConfigAttr) : {};
            
            // Get settings from container config
            const position = containerConfig.position || 'bottom-right';
            const visibleToasts = containerConfig.visibleToasts || 3;
            
            // Get gap and offset from config (regular number fields)
            const gap = containerConfig.gap || 14;
            const offset = containerConfig.offset || 24;
            
            // Get settings from notification config
            const duration = notificationConfig.duration === 'Infinity' ? Infinity : (notificationConfig.duration || 5000);
            const dismissible = notificationConfig.dismissible !== undefined ? notificationConfig.dismissible : true;
            const closeButton = notificationConfig.closeButton !== undefined ? notificationConfig.closeButton : false;
            const ariaLive = notificationConfig.ariaLive || 'polite';
            
            // Container and notification configured
            
            // Determine toaster key: use position for looped containers, containerId for unique ones
            // Check if container is in a Bricks query loop using isLooping attribute
            const isLooping = containerConfig.isLooping || null;
            const isLoopingComponent = containerConfig.isLoopingComponent || null;
            const isLooped = !!(isLooping);
            
            // Determine the loop ID to use for the class
            let loopingID = isLooping;
            if (isLooping && !document.querySelector('.brxe-' + isLooping)) {
                if (isLoopingComponent) {
                    loopingID = isLoopingComponent;
                }
            }
            
            // Use position as key so all containers with the same position share the same toaster
            // This allows toasts to stack properly when triggered repeatedly
            const toasterKey = `position_${position}`;
            
            // Create or get toaster instance for this key
            if (!window.xtoast.Instances[toasterKey]) {
                // Creating new toaster instance
                const toaster = window.xCreateToasterFunc({
                    position: position,
                    theme: 'light',
                    duration: 5000,
                    visibleToasts: visibleToasts,
                    richColors: false,
                    gap: gap,
                    offset: offset,
                    mobileOffset: offset,
                });
                
                // Mount the toaster
                toaster.mount(document.body);
                
                // Save the toaster instance and config
                window.xtoast.Instances[toasterKey] = toaster;
                window.xtoast.ContainerConfigs[toasterKey] = { position, toasterKey };
            }
            
            // Add looping element class to Sonner container if inside a loop
            // This ensures Bricks loop-specific styles are applied
            // Do this outside the "if new toaster" block so it applies to existing toasters too
            if (isLooped && loopingID) {
                // Use setTimeout to give Sonner time to create the DOM element
                setTimeout(() => {
                    // Find the specific Sonner container for this position
                    // Parse position to get x and y positions (e.g., "bottom-right" -> y: bottom, x: right)
                    const [yPos, xPos] = position.split('-');
                    const sonnerContainer = document.querySelector(`[data-sonner-toaster][data-y-position="${yPos}"][data-x-position="${xPos}"]`);
                    
                    if (sonnerContainer) {
                        const className = 'brxe-' + loopingID;
                        sonnerContainer.classList.add(className);
                    }
                }, 100);
            }
        
        // Get the toaster for this key
        const toaster = window.xtoast.Instances[toasterKey];
        const currentPosition = window.xtoast.ContainerConfigs[toasterKey].position;
        
        // Track if we need to switch toasters (if last used toaster key is different)
        const needsToasterSwitch = window.xtoast.lastActiveToaster && window.xtoast.lastActiveToaster !== toasterKey;
        
        // Only dismiss other toasters and remount if we're switching toasters
        if (needsToasterSwitch) {
            // Dismiss toasts from other toasters
            Object.keys(window.xtoast.Instances).forEach(key => {
                if (key !== toasterKey) {
                    const otherToaster = window.xtoast.Instances[key];
                    
                    // Dismiss all toasts in this toaster
                    if (otherToaster.toastInstances && otherToaster.toastInstances.size > 0) {
                        // Get all toast IDs from the map
                        const toastIds = Array.from(otherToaster.toastInstances.keys());
                        
                        // Dismiss each toast (this triggers the animation)
                        toastIds.forEach(toastId => {
                            window.xToastLib.dismiss(toastId);
                        });
                    }
                }
            });
            
            // Unmount and remount the current toaster to make it the "active" one
            toaster.unmount();
            toaster.mount(document.body);
        }
        
        // Always track the current toaster as active (for next time)
        window.xtoast.lastActiveToaster = toasterKey;
        
        // Now use the global toast API which will use the mounted toaster
        const toastId = window.xToastLib.custom(notificationClone, {
            duration: duration,
            dismissible: dismissible,
            closeButton: closeButton
        });
        
        // Store the mapping between uniqueId and toastId for close button handling
        window.xtoast.toastIdMap[uniqueId] = toastId;
        
        // Apply the Bricks element ID to the toast
            requestAnimationFrame(() => {
                // Find the specific toast that was just created using its toast ID
                const toastElement = document.querySelector(`[data-sonner-toast][data-toast-id="${toastId}"]`);
                
                if (!toastElement) {
                    return;
                }
                
                // Apply the Bricks ID
                toastElement.id = elementId;
                toastElement.classList.add('x-toast-active');
                
                // Set aria-live attribute for screen reader announcements
                if (ariaLive === 'off') {
                    toastElement.setAttribute('aria-live', 'off');ok
                    toastElement.setAttribute('role', 'status');
                } else {
                    toastElement.setAttribute('aria-live', ariaLive);
                    toastElement.setAttribute('role', ariaLive === 'assertive' ? 'alert' : 'status');
                }
                
                // Update favorite counts inside this toast if they exist
                toastElement.querySelectorAll('[data-x-favorite-count]').forEach(count => {
                    const countTypes = count.getAttribute('data-x-favorite-count').split(':');
                    
                    // Get current favorite data from cookies
                    const favoriteIds = {};
                    document.cookie.split("; ").forEach(cookie => {
                        const [name, value] = cookie.split("=");
                        if (name.startsWith("x_favorite_ids__")) {
                            const key = name.replace("x_favorite_ids__", "");
                            try {
                                favoriteIds[key] = JSON.parse(decodeURIComponent(value) || "[]");
                            } catch(e) {
                                favoriteIds[key] = [];
                            }
                        }
                    });
                    
                    // Calculate total count for this element's post types
                    let totalCount = 0;
                    countTypes.forEach(type => {
                        if (favoriteIds[type] && favoriteIds[type].length > 0) {
                            totalCount += favoriteIds[type].length;
                        }
                    });
                    
                    count.innerHTML = totalCount.toString();
                });

                // Dispatch show event (other code can listen to this to update content)
                notificationElement.dispatchEvent(new Event('x_toast:show'));
            });
        }
    }

    // Global function for easy access
    window.xShowToast = function(notificationId, args = {}) {
        // Find notification by data-x-id attribute
        const notification = document.querySelector(`[data-x-id="${notificationId}"]`);
        if (!notification) {
            return;
        }
        
        // Find parent container
        const container = notification.closest('.x-toast-container');
        if (!container) {
            console.warn('Toast container not found for notification:', notificationId);
            return;
        }
        
        // Clone the notification to avoid modifying the original
        const notificationClone = notification.cloneNode(true);
        
        // Override message content if provided
        if (args.message) {
            const inner = notificationClone.querySelector('.x-toast-notification-inner');
            if (inner) {
                inner.innerHTML = args.message;
                
                // Update favorite counts in the new content immediately
                notificationClone.querySelectorAll('[data-x-favorite-count]').forEach(count => {
                    const countTypes = count.getAttribute('data-x-favorite-count').split(':');
                    
                    // Get current favorite data from cookies
                    const favoriteIds = {};
                    document.cookie.split("; ").forEach(cookie => {
                        const [name, value] = cookie.split("=");
                        if (name.startsWith("x_favorite_ids__")) {
                            const key = name.replace("x_favorite_ids__", "");
                            try {
                                favoriteIds[key] = JSON.parse(decodeURIComponent(value) || "[]");
                            } catch(e) {
                                favoriteIds[key] = [];
                            }
                        }
                    });
                    
                    // Calculate total count for this element's post types
                    let totalCount = 0;
                    countTypes.forEach(type => {
                        if (favoriteIds[type] && favoriteIds[type].length > 0) {
                            totalCount += favoriteIds[type].length;
                        }
                    });
                    
                    count.innerHTML = totalCount.toString();
                });
            }
        }
        
        // Override notification config with args if provided
        const currentConfig = notification.getAttribute('data-x-notification');
        const config = currentConfig ? JSON.parse(currentConfig) : {};
        const mergedConfig = { 
            ...config, 
            duration: args.duration !== undefined ? args.duration : config.duration,
            dismissible: args.dismissible !== undefined ? args.dismissible : config.dismissible,
            closeButton: args.closeButton !== undefined ? args.closeButton : config.closeButton,
            contextIcon: args.contextIcon !== undefined ? args.contextIcon : config.contextIcon,
            ariaLive: args.ariaLive !== undefined ? args.ariaLive : config.ariaLive
        };
        notificationClone.setAttribute('data-x-notification', JSON.stringify(mergedConfig));
        
        // Handle context icon visibility
        if (args.contextIcon !== undefined) {
            const contextIconElement = notificationClone.querySelector('.x-toast-context-icon');
            if (contextIconElement) {
                contextIconElement.style.display = args.contextIcon ? '' : 'none';
            }
        }
        
        showToast(notificationClone, container);
    };

    // Setup bricksextras API for toast notifications
    if (typeof bricksextras !== 'undefined') {
        bricksextras.toast = {
            show: (brxParam, message = '', announce, duration, contextIcon, dismissible, closeButton) => {
                // Handle Bricks interaction parameter format
                if (brxParam?.target) {
                    let target = brxParam.target;
                    // Check if target is a notification element
                    if (target.classList.contains('brxe-xtoastnotification')) {
                        // Get the notification ID from the target
                        const notificationId = target.getAttribute('data-x-id');
                        
                        // Build args object from individual parameters
                        const toastArgs = {};
                        if (message) toastArgs.message = message;
                        if (announce !== undefined) toastArgs.ariaLive = announce;
                        if (duration !== undefined) toastArgs.duration = duration;
                        if (contextIcon !== undefined) toastArgs.contextIcon = contextIcon;
                        if (dismissible !== undefined) toastArgs.dismissible = dismissible;
                        if (closeButton !== undefined) toastArgs.closeButton = closeButton;
                        
                        // Use xShowToast with the notification ID and args
                        window.xShowToast(notificationId, toastArgs);
                    }
                } else if (typeof brxParam === 'string') {
                    // Build args object from individual parameters
                    const toastArgs = {};
                    if (message) toastArgs.message = message;
                    if (announce !== undefined) toastArgs.ariaLive = announce;
                    if (duration !== undefined) toastArgs.duration = duration;
                    if (contextIcon !== undefined) toastArgs.contextIcon = contextIcon;
                    if (dismissible !== undefined) toastArgs.dismissible = dismissible;
                    if (closeButton !== undefined) toastArgs.closeButton = closeButton;
                    
                    // If just a string ID is passed, use xShowToast with optional args
                    window.xShowToast(brxParam, toastArgs);
                }
            },
            
            // Alias for backward compatibility and Bricks interactions
            showByNotificationId: (notificationId, args = {}) => {
                window.xShowToast(notificationId, args);
            },
            
            // Show custom HTML toast
            showCustom: (containerId, html, config = {}) => {
                // Find container by data-x-id attribute
                const container = document.querySelector(`[data-x-id="${containerId}"]`);
                if (!container) {
                    console.warn('Toast container not found:', containerId);
                    return;
                }
                
                // Create a temporary notification element
                const tempNotification = document.createElement('div');
                tempNotification.className = 'x-toast-notification';
                tempNotification.setAttribute('data-x-id', 'temp-' + Date.now());
                
                // Create inner container
                const inner = document.createElement('div');
                inner.className = 'x-toast-notification-inner';
                inner.innerHTML = html;
                tempNotification.appendChild(inner);
                
                // Set config
                const defaultConfig = {
                    duration: 5000,
                    dismissible: true,
                    closeButton: false,
                    ariaLive: 'polite'
                };
                const mergedConfig = { ...defaultConfig, ...config };
                tempNotification.setAttribute('data-x-notification', JSON.stringify(mergedConfig));
                
                // Add close button if requested
                if (mergedConfig.closeButton) {
                    const closeBtn = document.createElement('button');
                    closeBtn.className = 'x-toast-close';
                    closeBtn.setAttribute('data-x-toast-close', '');
                    closeBtn.setAttribute('aria-label', 'Close notification');
                    closeBtn.innerHTML = '<span class="x-toast-close-icon"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></span>';
                    tempNotification.appendChild(closeBtn);
                }
                
                showToast(tempNotification, container);
            }
        }
    } else {
        console.warn('bricksextras object not found!');
    }

}



// Listen for WooCommerce add to cart events to track which product was added
document.addEventListener("DOMContentLoaded", function() {
    // Capture product ID BEFORE WooCommerce processes it (on button click)
    document.addEventListener('click', function(e) {
        const button = e.target.closest('.add_to_cart_button');
        if (button) {
            const productId = button.getAttribute('data-product_id');
            if (productId) {
                window.bricksExtrasLastAddedProduct = productId;
                
                // Keep it available for longer since interactions might fire after a delay
                setTimeout(() => {
                    window.bricksExtrasLastAddedProduct = null;
                }, 2000);
            }
        }
    }, true); // Use capture phase to fire early
    
    // Also listen to WooCommerce event as backup
    if (typeof jQuery !== 'undefined') {
        jQuery(document.body).on('added_to_cart', function(event, fragments, cart_hash, button) {
            if (button && button.data('product_id')) {
                const productId = button.data('product_id').toString();
                if (!window.bricksExtrasLastAddedProduct) {
                    window.bricksExtrasLastAddedProduct = productId;
                }
            }
        });
    }
});

// Process PHP-queued toasts
function processQueuedToasts() {
    // Check for queued toasts from PHP
    const queueScript = document.getElementById('bricksextras-toast-queue');
    if (!queueScript) {
        return;
    }
    
    try {
        const queue = JSON.parse(queueScript.textContent);
        
        if (!queue || queue.length === 0) {
            return;
        }
        
        // Wait for toast system to be ready
        function waitForToastSystem(callback) {
            if (window.xToastLib && window.xCreateToasterFunc && typeof bricksextras !== 'undefined' && bricksextras.toast) {
                callback();
            } else {
                setTimeout(function() {
                    waitForToastSystem(callback);
                }, 100);
            }
        }
        
        waitForToastSystem(function() {
            queue.forEach(function(item, index) {
                // Small delay between toasts
                setTimeout(function() {
                    if (bricksextras.toast.showByNotificationId) {
                        bricksextras.toast.showByNotificationId(item.notification_id, {
                            message: item.message || '',
                            duration: item.duration || 5000,
                            dismissible: item.dismissible !== undefined ? item.dismissible : true,
                            closeButton: item.close_button !== undefined ? item.close_button : false,
                            contextIcon: item.context_icon !== undefined ? item.context_icon : true,
                            ariaLive: item.announce || 'polite'
                        });
                    }
                }, 100 * (index + 1));
            });
        });
    } catch (e) {
        console.error('BricksExtras Toast: Error processing queue', e);
    }
}

// Process toast triggers
function processToastTriggers() {
    // Find all toast notifications with triggers
    document.querySelectorAll('.x-toast-notification[data-x-notification]').forEach(notification => {
        const notificationId = notification.getAttribute('data-x-id');
        const configAttr = notification.getAttribute('data-x-notification');
        
        if (!configAttr) return;
        
        try {
            const config = JSON.parse(configAttr);
            
            // Check if triggers exist
            if (!config.triggers || !Array.isArray(config.triggers)) return;
            
            // Determine loop container for scoped selector queries
            // Find the toast container element to get its config
            const toastContainer = notification.closest('[data-x-toast-container]');
            let loopContainer = document;
            
            if (toastContainer) {
                const containerConfigAttr = toastContainer.getAttribute('data-x-toast-container');
                if (containerConfigAttr) {
                    const containerConfig = JSON.parse(containerConfigAttr);
                    
                    // Check if inside a loop
                    if (containerConfig.isLooping) {
                        loopContainer = notification.closest('.brxe-' + containerConfig.isLooping);
                        
                        if (!loopContainer && containerConfig.isLoopingComponent) {
                            loopContainer = notification.closest('.brxe-' + containerConfig.isLoopingComponent);
                        }
                        
                        // Fallback to document if loop container not found
                        if (!loopContainer) {
                            loopContainer = document;
                        }
                    }
                }
            }
            
            // Check show_once and show_again settings
            let currentTime = new Date().getTime();
            let lastShownTime = localStorage && localStorage['x-toast-' + notificationId + '-last-shown-time'] 
                ? JSON.parse(localStorage['x-toast-' + notificationId + '-last-shown-time']) 
                : false;
            let sessionAlreadyShown = sessionStorage && sessionStorage['x-toast-' + notificationId + '-last-shown-time'] 
                ? JSON.parse(sessionStorage['x-toast-' + notificationId + '-last-shown-time']) 
                : false;
            
            let toastShown = false;
            
            // Check if already shown in session
            if (sessionAlreadyShown && config.show_once_session) {
                toastShown = true;
            }
            
            // Function to check if toast should be shown based on show_again settings
            function shouldShowToast() {
                // Update current time for each check
                let now = new Date().getTime();
                
                switch(config.show_again?.type) {
                    case 'never':
                        // If shown at least once, don't show again
                        if (lastShownTime !== false) return false;
                        break;
                    case 'after':
                        let settingDays = parseInt(config.show_again.options.days) || 0;
                        let settingHours = parseInt(config.show_again.options.hours) || 0;
                        let settingDelay = settingDays + (settingHours / 24);
                        
                        if (lastShownTime !== false && (now - lastShownTime) / 86400000 < settingDelay) {
                            return false;
                        }
                        break;
                }
                
                return true;
            }
            
            // Wrapper function to show toast and update storage
            function showToastAndTrack() {
                
                if (!shouldShowToast()) {
                    return;
                }
                
                window.xShowToast(notificationId);
                toastShown = true;
                
                // Update timestamps for next check
                currentTime = new Date().getTime();
                lastShownTime = currentTime;
                
                // Save current time as last shown time
                if (localStorage) localStorage['x-toast-' + notificationId + '-last-shown-time'] = JSON.stringify(currentTime);
                if (config.show_once_session && sessionStorage) {
                    sessionStorage['x-toast-' + notificationId + '-last-shown-time'] = JSON.stringify(currentTime);
                }
            }
            
            config.triggers.forEach(trigger => {
                const triggerType = trigger.type;
                const triggerSelector = trigger.selector;
                
                // Page Load
                if (triggerType === 'pageLoad') {
                    const delay = parseInt(trigger.delay) || 0;
                    setTimeout(() => {
                        if (!toastShown && (config.show_once === false && config.show_once_session === false || shouldShowToast())) {
                            showToastAndTrack();
                        }
                    }, delay);
                }
                
                // Page Load with URL Parameter
                if (triggerType === 'pageLoadURLParameter') {
                    const queryString = window.location.search;
                    const urlParam = trigger.urlParameter;
                    const delay = parseInt(trigger.delay) || 0;
                    if (urlParam && queryString.includes(urlParam)) {
                        setTimeout(() => {
                            if (!toastShown && (config.show_once === false && config.show_once_session === false || shouldShowToast())) {
                                showToastAndTrack();
                            }
                        }, delay);
                    }
                }
                
                // Scroll Distance
                if (triggerType === 'scroll') {
                    let scrollAmount = trigger.scrollDistance;
                    if (!scrollAmount) return;
                    let isPercentage = scrollAmount.includes('%');
                    let scrollValue = parseInt(scrollAmount);
                    
                    let waiting = false;
                    const scrollHandler = function() {
                        if (waiting || toastShown) return;
                        waiting = true;
                        
                        setTimeout(() => {
                            const scrollTop = window.pageYOffset;
                            const scrollTarget = isPercentage 
                                ? (document.documentElement.scrollHeight - window.innerHeight) * (scrollValue / 100)
                                : scrollValue;
                            
                            if (scrollTop >= scrollTarget && !toastShown && (config.show_once === false && config.show_once_session === false || shouldShowToast())) {
                                showToastAndTrack();
                                document.removeEventListener('scroll', scrollHandler);
                            }
                            waiting = false;
                        }, 100);
                    };
                    
                    document.addEventListener('scroll', scrollHandler);
                }
                
                // Scroll to Element
                if (triggerType === 'scrolledToElement' && triggerSelector) {
                    const targetElement = loopContainer.querySelector(triggerSelector);
                    if (targetElement) {
                        const observer = new IntersectionObserver((entries) => {
                            entries.forEach(entry => {
                                if (entry.intersectionRatio > 0 && !toastShown && (config.show_once === false && config.show_once_session === false || shouldShowToast())) {
                                    showToastAndTrack();
                                    observer.unobserve(entry.target);
                                }
                            });
                        });
                        observer.observe(targetElement);
                    }
                }
                
                // Exit Intent
                if (triggerType === 'exitIntent') {
                    let firstTime = true;
                    document.documentElement.addEventListener('mouseleave', (e) => {
                        if (!e.toElement && !e.relatedTarget && firstTime && !toastShown && (config.show_once === false && config.show_once_session === false || shouldShowToast())) {
                            showToastAndTrack();
                            firstTime = false;
                        }
                    });
                }
                
                // Page Views
                if (triggerType === 'pageViews') {
                    const targetViews = parseInt(trigger.pageViews);
                    if (!targetViews) return;
                    
                    let pageViews = localStorage && localStorage['x-toast-' + notificationId + '-page-views'] 
                        ? parseInt(localStorage['x-toast-' + notificationId + '-page-views']) 
                        : 0;
                    pageViews++;
                    
                    if (localStorage) localStorage['x-toast-' + notificationId + '-page-views'] = pageViews;
                    
                    if (pageViews === targetViews && !toastShown && (config.show_once === false && config.show_once_session === false || shouldShowToast())) {
                        if (localStorage) localStorage['x-toast-' + notificationId + '-page-views'] = 0;
                        showToastAndTrack();
                    }
                }
                
                // Element Click
                if (triggerType === 'elementClick' && triggerSelector) {
                    const clickElements = loopContainer.querySelectorAll(triggerSelector);
                    clickElements.forEach(element => {
                        element.addEventListener('click', (e) => {
                            
                            // Check show_once first - if enabled and already shown, block
                            if (config.show_once && toastShown) {
                                return;
                            }
                            
                            // Check show_once_session - already handled by initial toastShown flag
                            if (config.show_once_session && toastShown) {
                                return;
                            }
                            
                            // Check show_again settings
                            if (shouldShowToast()) {
                                showToastAndTrack();
                            }
                        });
                    });
                }
                
                // Element Hover
                if (triggerType === 'elementHover' && triggerSelector) {
                    const hoverElements = loopContainer.querySelectorAll(triggerSelector);
                    hoverElements.forEach(element => {
                        element.addEventListener('mouseenter', () => {
                            // Check show_once first - if enabled and already shown, block
                            if (config.show_once && toastShown) {
                                return;
                            }
                            
                            // Check show_once_session - already handled by initial toastShown flag
                            if (config.show_once_session && toastShown) {
                                return;
                            }
                            
                            // Check show_again settings
                            if (shouldShowToast()) {
                                showToastAndTrack();
                            }
                        });
                    });
                }
                
                // Intervals (loop notifications)
                if (triggerType === 'intervals') {
                    const intervalSeconds = parseInt(trigger.intervalSeconds) || 20;
                    const shouldLoop = trigger.intervalLoop === true; // Default to false if not set
                    
                    if (intervalSeconds > 0) {
                        // Get all direct children of the inner div
                        const innerDiv = notification.querySelector('.x-toast-notification-inner');
                        if (!innerDiv) return;
                        
                        const children = Array.from(innerDiv.children);
                        if (children.length === 0) return;
                        
                        // Storage keys for persistence
                        const storageKeyIndex = 'x-toast-interval-' + notificationId + '-index';
                        const storageKeyTime = 'x-toast-interval-' + notificationId + '-time';
                        const storageKeyComplete = 'x-toast-interval-' + notificationId + '-complete';
                        
                        // Check if sequence is already complete (for non-looping)
                        if (!shouldLoop && sessionStorage && sessionStorage[storageKeyComplete]) {
                            return; // Don't start if already completed
                        }
                        
                        // Get stored state or initialize
                        let currentIndex = sessionStorage && sessionStorage[storageKeyIndex] 
                            ? parseInt(sessionStorage[storageKeyIndex]) 
                            : 0;
                        let lastShownTime = sessionStorage && sessionStorage[storageKeyTime]
                            ? parseInt(sessionStorage[storageKeyTime])
                            : 0;
                        
                        const now = Date.now();
                        const timeSinceLastShow = now - lastShownTime;
                        const intervalMs = intervalSeconds * 1000;
                        
                        // Calculate when the next show should happen
                        let timeUntilNextShow = intervalMs;
                        
                        if (lastShownTime > 0 && timeSinceLastShow < intervalMs) {
                            // User returned before interval completed, wait for remaining time
                            timeUntilNextShow = intervalMs - timeSinceLastShow;
                        }
                        
                        // Hide all children initially
                        children.forEach((child) => {
                            child.style.display = 'none';
                        });
                        
                        // Track timers for cleanup
                        let intervalId = null;
                        let timeoutId = null;
                        
                        // Function to show current notification
                        const showCurrentNotification = () => {
                            // Don't show if page is hidden
                            if (document.hidden) {
                                return true; // Continue but don't show
                            }
                            
                            // Check if we've reached the end and shouldn't loop
                            if (!shouldLoop && currentIndex >= children.length) {
                                // Mark as complete
                                if (sessionStorage) {
                                    sessionStorage[storageKeyComplete] = 'true';
                                }
                                return false; // Signal to stop
                            }
                            
                            // Show current child
                            children.forEach((child, index) => {
                                child.style.display = index === currentIndex ? '' : 'none';
                            });
                            
                            // Show the toast
                            window.xShowToast(notificationId);
                            
                            // Update storage
                            if (sessionStorage) {
                                sessionStorage[storageKeyTime] = Date.now();
                            }
                            
                            // Move to next index
                            if (shouldLoop) {
                                currentIndex = (currentIndex + 1) % children.length;
                            } else {
                                currentIndex = currentIndex + 1;
                            }
                            
                            // Save new index
                            if (sessionStorage) {
                                sessionStorage[storageKeyIndex] = currentIndex;
                            }
                            
                            return true; // Continue
                        };
                        
                        // Function to start the interval
                        const startInterval = () => {
                            if (intervalId) return; // Already running
                            
                            intervalId = setInterval(() => {
                                if (showCurrentNotification() === false) {
                                    clearInterval(intervalId);
                                    intervalId = null;
                                }
                            }, intervalMs);
                        };
                        
                        // Function to stop the interval
                        const stopInterval = () => {
                            if (intervalId) {
                                clearInterval(intervalId);
                                intervalId = null;
                            }
                            if (timeoutId) {
                                clearTimeout(timeoutId);
                                timeoutId = null;
                            }
                        };
                        
                        // Handle page visibility changes
                        const handleVisibilityChange = () => {
                            if (document.hidden) {
                                // Page is hidden, stop the interval
                                stopInterval();
                            } else {
                                // Page is visible again, resume
                                // Check if we should show immediately or wait
                                if (sessionStorage && sessionStorage[storageKeyTime]) {
                                    const lastTime = parseInt(sessionStorage[storageKeyTime]);
                                    const elapsed = Date.now() - lastTime;
                                    
                                    if (elapsed >= intervalMs) {
                                        // Enough time has passed, show now
                                        if (showCurrentNotification() !== false) {
                                            startInterval();
                                        }
                                    } else {
                                        // Wait for remaining time
                                        timeoutId = setTimeout(() => {
                                            if (showCurrentNotification() !== false) {
                                                startInterval();
                                            }
                                        }, intervalMs - elapsed);
                                    }
                                } else {
                                    // No previous time, start interval
                                    startInterval();
                                }
                            }
                        };
                        
                        // Listen for visibility changes
                        document.addEventListener('visibilitychange', handleVisibilityChange);
                        
                        // Show first notification after calculated delay
                        timeoutId = setTimeout(() => {
                            if (showCurrentNotification() === false) return;
                            
                            // Set up interval for subsequent shows
                            startInterval();
                        }, timeUntilNextShow);
                    }
                }
            });
            
        } catch (e) {
            console.error('Error processing toast triggers:', e);
        }
    });
}

// Initialize on DOMContentLoaded
document.addEventListener("DOMContentLoaded", function() {
    // Initialize toast system
    xToast();
    
    // Process any queued toasts from PHP
    processQueuedToasts();
    
    // Process toast triggers
    processToastTriggers();
});
