/**
 * Widget Context Sender
 * Sends WooCommerce context data to ReplyIt API
 *
 * @package ReplyIt_Chat_Widget
 */

(function() {
    'use strict';

    // Wait for widget to be ready
    function waitForWidget(callback) {
        if (typeof window.chatWidgetInstance !== 'undefined') {
            callback();
        } else {
            setTimeout(function() {
                waitForWidget(callback);
            }, 100);
        }
    }

    // Send context to API
    function sendContextToAPI() {
        if (typeof replyitConfig === 'undefined' || typeof replyitWooContext === 'undefined') {
            console.warn('[ReplyIt] Config or context not available');
            return;
        }

        const widgetInstance = window.chatWidgetInstance;
        if (!widgetInstance || !widgetInstance.sessionId) {
            console.warn('[ReplyIt] Widget instance or session ID not available');
            return;
        }

        const apiUrl = replyitConfig.apiUrl || 'https://replyit.ai';
        const widgetId = replyitConfig.widgetId;
        const apiSecret = replyitConfig.apiSecret;
        const sessionId = widgetInstance.sessionId;

        fetch(`${apiUrl}/api/widgets/${widgetId}/context`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Widget-Secret': apiSecret
            },
            body: JSON.stringify({
                session_id: sessionId,
                context: replyitWooContext
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success || data.result) {
                console.log('[ReplyIt] Context sent successfully');
            } else {
                console.warn('[ReplyIt] Context send failed:', data.message);
            }
        })
        .catch(error => {
            console.error('[ReplyIt] Context send error:', error);
        });
    }

    // Initialize
    waitForWidget(function() {
        // Send context immediately
        sendContextToAPI();

        // Re-send context when cart updates (WooCommerce event)
        if (typeof jQuery !== 'undefined') {
            jQuery(document.body).on('updated_cart_totals updated_checkout', function() {
                console.log('[ReplyIt] Cart updated, refreshing context...');
                setTimeout(sendContextToAPI, 1000);
            });
        }
    });

})();
