/**
 * Google Identity Services Integration for Profile Builder Social Connect
 * Uses the modern Google Identity Services API
 */

// Load Google Identity Services library
(function() {
    var gisScript = document.createElement('script');
    gisScript.src = 'https://accounts.google.com/gsi/client';
    gisScript.async = true;
    gisScript.defer = true;
    gisScript.onload = wppbGISOnLoadCallback;
    gisScript.onerror = function() {
        console.error('Failed to load Google Identity Services');
    };
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gisScript, s);
})();

jQuery(document).ready(function() {
    jQuery('.wppb-sc-google-gis-login').on('click', wppbGISOnClick);

    jQuery(document).on('elementor/popup/show', () => {
        jQuery('.wppb-sc-google-gis-login').on("click.wppb_sc_gis_elementor", wppbGISOnClick);
    });
    jQuery(document).on('elementor/popup/hide', () => {
        jQuery('.wppb-sc-google-gis-login').off("click.wppb_sc_gis_elementor");
    });
});

var wppbGISTokenClient = null;

function wppbGISOnLoadCallback() {
    if (!wppb_sc_google_gis_data.client_id) {
        console.error("Google Identity Services: Missing Client ID");
        return;
    }

    try {
        wppbGISTokenClient = google.accounts.oauth2.initTokenClient({
            client_id: wppb_sc_google_gis_data.client_id,
            scope: 'profile email',
            callback: wppbGISTokenCallback,
            error_callback: wppbGISErrorCallback
        });
        
        //console.log('Google Identity Services initialized successfully');
    } catch (error) {
        console.error('Failed to initialize Google Identity Services:', error);
    }
}

function wppbGISOnClick(e) {
    e.preventDefault();

    if (!wppbGISTokenClient) {
        console.error('Google Identity Services not initialized');
        return;
    }

    jQuery(this).addClass('wppb-sc-clicked');

    var wppb_form_location = jQuery(this).closest('div.wppb-sc-buttons-container').siblings('input[name=wppb_form_location]').val();
    if (wppb_form_location == '' || typeof wppb_form_location == 'undefined') {
        wppb_form_location = jQuery(this).closest('div.wppb-sc-buttons-container').siblings('form').find('input[name=wppb_form_location]').val();
    }
    if (wppb_form_location != '' && typeof wppb_form_location != 'undefined') {
        localStorage.setItem('wppb_form_location', wppb_form_location);
    }

    var wppb_sc_form_ID_google_gis = jQuery(this).data('wppb_sc_form_id_google_gis');
    if (typeof wppb_sc_form_ID_google_gis != 'undefined') {
        localStorage.setItem('wppb_sc_form_ID_google_gis', wppb_sc_form_ID_google_gis);
    }

    // Show loading state
    jQuery(this).children()
        .removeClass()
        .addClass('wppb-sc-icon')
        .addClass('wppb-sc-icon-spinner');

    // Request access token
    try {
        wppbGISTokenClient.requestAccessToken();
    } catch (error) {
        console.error('Error requesting access token:', error);
        wppbGISErrorCallback({error: 'request_failed', error_description: error.message});
    }
}

function wppbGISTokenCallback(tokenResponse) {
    if (tokenResponse.error) {
        wppbGISErrorCallback(tokenResponse);
        return;
    }

    // Get user info using the access token
    wppbGISGetUserInfo(tokenResponse.access_token);
}

function wppbGISGetUserInfo(accessToken) {
    jQuery.ajax({
        url: 'https://www.googleapis.com/oauth2/v2/userinfo',
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + accessToken
        },
        success: function(userInfo) {
            wppbGISProcessUserInfo(userInfo, accessToken);
        },
        error: function(xhr, status, error) {
            console.error('Failed to get user info:', error);
            wppbGISErrorCallback({error: 'userinfo_failed', error_description: 'Failed to retrieve user information'});
        }
    });
}

function wppbGISProcessUserInfo(userInfo, accessToken) {
    // Save security token
    var data = {
        'action': 'wppb_sc_save_cookies',
        'wppb_sc_cookies_nonce': wppb_sc_google_gis_data.wppb_sc_cookies_nonce,
        'wppb_sc_security_token': accessToken,
        'wppb_sc_platform_name': 'google-gis'
    };

    jQuery.post(wppb_sc_google_gis_data.ajaxUrl, data, function() {
        // Set up the user data in the format expected by the backend
        var user_data = {};
        user_data.id = userInfo.id;
        user_data.first_name = userInfo.given_name || '';
        user_data.last_name = userInfo.family_name || '';
        user_data.email = userInfo.email || '';
        user_data.name = userInfo.name || '';
        user_data.picture = userInfo.picture || '';

        var wppb_sc_form_ID_google_gis = localStorage.getItem('wppb_sc_form_ID_google_gis');
        if (wppb_sc_form_ID_google_gis === null || wppb_sc_form_ID_google_gis === 'undefined') {
            wppb_sc_form_ID_google_gis = '';
        }

        var loginData = {
            'platform': 'google-gis',
            'action': 'wppb_sc_handle_login_click',
            'platform_response': user_data,
            'wppb_sc_security_token': accessToken,
            'wppb_sc_form_ID': wppb_sc_form_ID_google_gis,
            'wppb_sc_login_nonce': wppb_sc_google_gis_data.wppb_sc_login_nonce,
        };

        wppbSCLogin(loginData, wppb_sc_google_gis_data, 'google-gis');

        localStorage.removeItem('wppb_sc_form_ID_google_gis');
    }).fail(function() {
        console.error('Failed to save security token');
        wppbGISErrorCallback({error: 'token_save_failed', error_description: 'Failed to save security token'});
    });
}

function wppbGISErrorCallback(error) {
    console.error('Google Identity Services error:', error);
    
    // Reset button state
    jQuery('.wppb-sc-google-gis-login.wppb-sc-clicked').children()
        .removeClass('wppb-sc-icon-spinner')
        .addClass('wppb-sc-icon-google-plus');
    
    jQuery('.wppb-sc-clicked').removeClass('wppb-sc-clicked');
    
    // Show error message
    var errorMessage = wppb_sc_google_gis_data.error_message;
    if (error.error_description) {
        errorMessage = error.error_description;
    }
    
    jQuery('.wppb-sc-google-gis-login').closest('.wppb-sc-buttons-container')
        .append('<div class="wppb-error wppb-sc-message">' + errorMessage + '</div>');
}

// Handle logout
jQuery(function() {
    jQuery('.wppb-logout-url, #wp-admin-bar-logout a').on('click', function() {
        if ((wppbGetCookie('wppb_sc_security_token') != '') && (wppbGetCookie('wppb_sc_platform_name') == 'google-gis')) {
            document.cookie = 'wppb_sc_security_token' + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
            document.cookie = 'wppb_sc_platform_name' + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
            
            // Revoke Google access token if available
            if (typeof google !== 'undefined' && google.accounts && google.accounts.oauth2) {
                var token = wppbGetCookie('wppb_sc_security_token');
                if (token) {
                    google.accounts.oauth2.revoke(token, function() {
                        console.log('Google access token revoked');
                    });
                }
            }
        }
    });
}); 