/**
 * AB2BC SSO Admin JavaScript v2.3.4
 * Handles QR code generation and status polling for wallet connection
 */

(function($) {
    'use strict';
    
    let sessionId = null;
    let expiresAt = null;
    let pollInterval = null;
    let countdownInterval = null;
    
    /**
     * Initialize SSO admin
     */
    function init() {
        // Generate QR button
        $('#m2c-generate-qr').on('click', startSSOSession);
        
        // Disconnect button
        $('#m2c-disconnect').on('click', disconnectStore);
    }
    
    /**
     * Start SSO session and generate QR code
     */
    function startSSOSession() {
        const $button = $('#m2c-generate-qr');
        const $qrContainer = $('#m2c-qr-container');
        
        $button.prop('disabled', true).text(m2cSSO.i18n.connecting);
        hideMessage();
        
        $.ajax({
            url: m2cSSO.ajaxUrl,
            type: 'POST',
            data: {
                action: 'm2c_sso_init',
                nonce: m2cSSO.nonce
            },
            success: function(response) {
                if (response.success) {
                    sessionId = response.data.sessionId;
                    expiresAt = new Date(response.data.expiresAt);
                    
                    // Show QR code
                    var qrHtml = '<img src="' + response.data.qrCodeUrl + '" alt="SSO QR Code" style="max-width:250px;">';
                    $('#m2c-qr-code').html(qrHtml);
                    $button.hide();
                    $qrContainer.show();
                    
                    // Update status
                    updateStatus('pending');
                    
                    // Start polling for status
                    startPolling();
                    
                    // Start countdown timer
                    startCountdown();
                } else {
                    showMessage(response.data.message || 'Failed to generate QR code', 'error');
                    resetButton();
                }
            },
            error: function(xhr, status, error) {
                showMessage('Connection error: ' + error, 'error');
                resetButton();
            }
        });
    }
    
    /**
     * Reset the generate button
     */
    function resetButton() {
        $('#m2c-generate-qr')
            .prop('disabled', false)
            .html('<span class="dashicons dashicons-smartphone"></span> Generate QR Code to Connect')
            .show();
    }
    
    /**
     * Start polling for SSO status
     */
    function startPolling() {
        pollInterval = setInterval(checkStatus, 2000);
    }
    
    /**
     * Stop polling
     */
    function stopPolling() {
        if (pollInterval) {
            clearInterval(pollInterval);
            pollInterval = null;
        }
    }
    
    /**
     * Check SSO status
     */
    function checkStatus() {
        if (!sessionId) {
            stopPolling();
            return;
        }
        
        $.ajax({
            url: m2cSSO.ajaxUrl,
            type: 'POST',
            data: {
                action: 'm2c_sso_status',
                nonce: m2cSSO.nonce,
                session_id: sessionId
            },
            success: function(response) {
                if (response.success) {
                    handleStatusUpdate(response.data);
                }
            }
        });
    }
    
    /**
     * Handle status update
     */
    function handleStatusUpdate(data) {
        updateStatus(data.status);
        
        switch (data.status) {
            case 'pending':
                // Still waiting for scan
                break;
                
            case 'scanned':
                // Wallet scanned, waiting for confirmation
                updateStatus('scanned', 'Wallet scanned! Waiting for confirmation...');
                break;
                
            case 'completed':
                // Connection complete!
                stopPolling();
                stopCountdown();
                updateStatus('completed', m2cSSO.i18n.connected);
                showMessage('Connection successful! Reloading...', 'success');
                setTimeout(function() {
                    location.reload();
                }, 1500);
                break;
                
            case 'expired':
                stopPolling();
                stopCountdown();
                updateStatus('expired', m2cSSO.i18n.expired);
                showMessage(m2cSSO.i18n.expired, 'error');
                setTimeout(function() {
                    resetUI();
                }, 3000);
                break;
                
            case 'cancelled':
                stopPolling();
                stopCountdown();
                showMessage('Connection was cancelled', 'error');
                setTimeout(function() {
                    resetUI();
                }, 3000);
                break;
        }
    }
    
    /**
     * Update status display
     */
    function updateStatus(status, message) {
        var $statusDiv = $('#m2c-qr-status');
        var statusHtml = '';
        
        switch (status) {
            case 'pending':
                statusHtml = '<span class="status-pending"><span class="spinner is-active"></span> Waiting for scan...</span>';
                break;
            case 'scanned':
                statusHtml = '<span class="status-scanned" style="color:#f0ad4e;"><span class="dashicons dashicons-smartphone"></span> ' + (message || 'Scanned! Confirm in app...') + '</span>';
                break;
            case 'completed':
                statusHtml = '<span class="status-completed" style="color:#5cb85c;"><span class="dashicons dashicons-yes-alt"></span> ' + (message || 'Connected!') + '</span>';
                break;
            case 'expired':
                statusHtml = '<span class="status-expired" style="color:#d9534f;"><span class="dashicons dashicons-clock"></span> ' + (message || 'Expired') + '</span>';
                break;
            default:
                statusHtml = message || '';
        }
        
        $statusDiv.html(statusHtml);
    }
    
    /**
     * Start countdown timer
     */
    function startCountdown() {
        updateCountdown();
        countdownInterval = setInterval(updateCountdown, 1000);
    }
    
    /**
     * Stop countdown
     */
    function stopCountdown() {
        if (countdownInterval) {
            clearInterval(countdownInterval);
            countdownInterval = null;
        }
    }
    
    /**
     * Update countdown display
     */
    function updateCountdown() {
        if (!expiresAt) return;
        
        var now = new Date();
        var diff = Math.max(0, Math.floor((expiresAt - now) / 1000));
        
        if (diff <= 0) {
            stopCountdown();
            $('#m2c-qr-timer').text('Expired');
            return;
        }
        
        var minutes = Math.floor(diff / 60);
        var seconds = diff % 60;
        $('#m2c-qr-timer').text('Expires in: ' + minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
    }
    
    /**
     * Reset UI to initial state
     */
    function resetUI() {
        sessionId = null;
        expiresAt = null;
        stopPolling();
        stopCountdown();
        
        $('#m2c-qr-container').hide();
        $('#m2c-qr-code').empty();
        $('#m2c-qr-status').empty();
        $('#m2c-qr-timer').empty();
        resetButton();
    }
    
    /**
     * Disconnect store
     */
    function disconnectStore() {
        if (!confirm('Are you sure you want to disconnect this store?')) {
            return;
        }
        
        var $button = $('#m2c-disconnect');
        $button.prop('disabled', true).text('Disconnecting...');
        
        $.ajax({
            url: m2cSSO.ajaxUrl,
            type: 'POST',
            data: {
                action: 'm2c_sso_disconnect',
                nonce: m2cSSO.nonce
            },
            success: function(response) {
                if (response.success) {
                    showMessage('Disconnected. Reloading...', 'success');
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    showMessage(response.data.message || 'Disconnect failed', 'error');
                    $button.prop('disabled', false).html(
                        '<span class="dashicons dashicons-dismiss"></span> Disconnect'
                    );
                }
            },
            error: function(xhr, status, error) {
                showMessage('Error: ' + error, 'error');
                $button.prop('disabled', false).html(
                    '<span class="dashicons dashicons-dismiss"></span> Disconnect'
                );
            }
        });
    }
    
    /**
     * Show message
     */
    function showMessage(message, type) {
        var $msg = $('#m2c-sso-message');
        $msg.removeClass('success error info notice-success notice-error')
            .addClass(type === 'success' ? 'notice-success' : 'notice-error')
            .addClass(type)
            .html('<p>' + message + '</p>')
            .show();
    }
    
    /**
     * Hide message
     */
    function hideMessage() {
        $('#m2c-sso-message').hide().empty();
    }
    
    // Initialize when document is ready
    $(document).ready(init);
    
})(jQuery);
