jQuery(document).ready(function($) {
    let pollingInterval;
    const POLLING_INTERVAL = 4000; // 4 seconds

    function checkSyncStatus() {
        console.log('FinalPOS: Checking sync status...');
        $.ajax({
            url: finalposPolling.ajaxurl,
            type: 'POST',
            data: {
                action: 'finalpos_check_sync_status',
                nonce: finalposPolling.nonce,
                company_id: finalposPolling.companyId
            },
            success: function(response) {
                console.log('FinalPOS: Received response:', response);
                if (response.success && response.data.sync_status) {
                    const syncStatus = response.data.sync_status;
                    let allComplete = true;

                    // Update status for each category
                    ['products', 'orders', 'customers'].forEach(function(category) {
                        const status = syncStatus[category];
                        const statusElement = $('.sync-item:contains("' + category.charAt(0).toUpperCase() + category.slice(1) + '")');
                        
                        console.log('FinalPOS: Updating status for', category, 'to', status);
                        
                        if (status === 'done') {
                            statusElement.removeClass('sync-progress sync-unknown').addClass('sync-done');
                            statusElement.find('.sync-status').text('Done');
                        } else if (status === 'in-progress') {
                            statusElement.removeClass('sync-done sync-unknown').addClass('sync-progress');
                            statusElement.find('.sync-status').text('Syncing');
                            allComplete = false;
                        } else {
                            statusElement.removeClass('sync-done sync-progress').addClass('sync-unknown');
                            statusElement.find('.sync-status').text('Unknown');
                            allComplete = false;
                        }
                    });

                    // Stop polling if everything is complete
                    if (allComplete) {
                        console.log('FinalPOS: All sync complete, stopping polling');
                        clearInterval(pollingInterval);
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('FinalPOS: AJAX error:', status, error);
            }
        });
    }

    console.log('FinalPOS: Starting polling with interval:', POLLING_INTERVAL);
    // Start polling
    pollingInterval = setInterval(checkSyncStatus, POLLING_INTERVAL);
}); 