/**
 * WooCommerce Proactive Messages
 *
 * @package ReplyIt_Chat_Widget
 */

(function() {
    'use strict';

    // Check if settings are available
    if (typeof replyitWooSettings === 'undefined') {
        return;
    }

    const settings = replyitWooSettings;

    // Track cart abandonment
    function trackCartAbandonment() {
        if (!settings.cart_abandon_enabled || !settings.cart_has_items) {
            return;
        }

        const abandonTime = parseInt(settings.cart_abandon_time) * 60 * 1000; // Convert minutes to ms
        const lastActivity = localStorage.getItem('replyit_last_cart_activity');
        const now = Date.now();

        // Update last activity timestamp
        localStorage.setItem('replyit_last_cart_activity', now);

        // Check if cart has been abandoned
        if (lastActivity) {
            const timeSinceActivity = now - parseInt(lastActivity);

            if (timeSinceActivity >= abandonTime) {
                showProactiveMessage(
                    'cart_abandon',
                    'I noticed you have items in your cart. Need any help completing your order?'
                );
            }
        }

        // Set up timer to check for abandonment
        setTimeout(function() {
            const currentActivity = parseInt(localStorage.getItem('replyit_last_cart_activity'));
            const elapsed = Date.now() - currentActivity;

            if (elapsed >= abandonTime) {
                showProactiveMessage(
                    'cart_abandon',
                    'I noticed you have items in your cart. Need any help completing your order?'
                );
            }
        }, abandonTime);
    }

    // Track product page viewing
    function trackProductPageDelay() {
        if (!settings.product_page_enabled || !settings.is_product_page) {
            return;
        }

        const delayTime = parseInt(settings.product_page_delay) * 1000; // Convert seconds to ms

        setTimeout(function() {
            // Check if user is still on the page
            if (document.hasFocus()) {
                showProactiveMessage(
                    'product_help',
                    'Looking at this product? I can help answer any questions you might have!'
                );
            }
        }, delayTime);
    }

    // Track checkout page help
    function trackCheckoutHelp() {
        if (!settings.checkout_help_enabled || !settings.is_checkout_page) {
            return;
        }

        setTimeout(function() {
            // Check if user is still on checkout page
            if (document.hasFocus()) {
                showProactiveMessage(
                    'checkout_help',
                    'Need any help with checkout? I\'m here to assist you!'
                );
            }
        }, 30000); // 30 seconds
    }

    // Show proactive message
    function showProactiveMessage(type, message) {
        // Check if message was already shown in this session
        const shownKey = 'replyit_shown_' + type;
        if (sessionStorage.getItem(shownKey)) {
            return;
        }

        // Mark as shown
        sessionStorage.setItem(shownKey, 'true');

        // Check if ChatWidget is available
        if (typeof window.cw !== 'function') {
            console.warn('ReplyIt ChatWidget not loaded');
            return;
        }

        // Open chat with message
        window.cw('open');

        // Wait a bit for widget to open, then send message
        setTimeout(function() {
            window.cw('message', message);
        }, 500);
    }

    // Initialize on page load
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            trackCartAbandonment();
            trackProductPageDelay();
            trackCheckoutHelp();
        });
    } else {
        trackCartAbandonment();
        trackProductPageDelay();
        trackCheckoutHelp();
    }

    // Track user activity to reset cart abandonment timer
    let activityTimeout;
    function resetCartActivity() {
        if (settings.cart_has_items) {
            clearTimeout(activityTimeout);
            activityTimeout = setTimeout(function() {
                localStorage.setItem('replyit_last_cart_activity', Date.now());
            }, 1000); // Debounce for 1 second
        }
    }

    // Listen for user activity
    ['mousedown', 'keydown', 'scroll', 'touchstart'].forEach(function(event) {
        document.addEventListener(event, resetCartActivity, { passive: true });
    });

})();
