const clientId = '597305194052-777qp4m2mk8i614mn591ll33qalbotrl.apps.googleusercontent.com'

function useGoogleAuth() {
	if (!clientId) {
		throw new Error('Please provide your Google Client ID!');
	}

	const isGoogleLoaded = Vue.ref(false);

	function loadGoogleSDK() {
		return new Promise((resolve, reject) => {
			if (window.google) {
				isGoogleLoaded.value = true;
				return resolve();
			}

			const script = document.createElement('script');
			script.src = 'https://accounts.google.com/gsi/client';
			script.async = true;
			script.defer = true;
			script.onload = () => {
				isGoogleLoaded.value = true;
				resolve();
			};
			script.onerror = reject;

			document.head.appendChild(script);
		});
	}

	async function initGoogleAuth(callback) {
		await loadGoogleSDK();
		if (!window.google) {
			throw new Error('Google SDK not loaded');
		}

		return await window.google.accounts.id.initialize({
			client_id: clientId,
			context: 'signin',
			cancel_on_tap_outside: true,
			callback: (authResult) => {
				let profileData = null;
				if (authResult.credential) {
					const data = window.jwtDecode(authResult.credential);
					profileData = {
						id: data.sub,
						firstName: data.given_name,
						lastName: data.family_name,
						email: data.email,
					};
				}

				callback(profileData);
			},
		});
	}

	return {initGoogleAuth, isGoogleLoaded};
}

window.useGoogleAuth = useGoogleAuth;
