<template>
	<ButtonComponent
		class="bg-white border-charcoal"
		@click="handleGoogleLogin"
		:loading="loading"
	>
		<img
			:src="GoogleLogo"
			width="16px"
			height="16px"
			alt="google icon"
		/>

		<!--		<span class="text-charcoal">{{ text }}</span>-->
	</ButtonComponent>
</template>

<script setup>
const ButtonComponent = Vue.defineAsyncComponent(
	async () =>
		await loadModule(`${SAS_URL}/src/components/login/social-medias/Button.vue`, options)
);

const {ref, onMounted} = Vue;
const emit = defineEmits(['login'])
const GoogleLogo = `${SAS_URL}/src/assets/images/icons//google_g.svg`

const {initGoogleAuth} = useGoogleAuth()

const loading = ref(false)
// const text = computed(() => {
// 	return loading.value ? 'Loading' : 'Continue with Google'
// })

const handleGoogleLogin = () => {
	if (!!useUserStore().getUser) return

	const googleLoginWrapper = document.createElement('div')
	googleLoginWrapper.style.display = 'none'
	googleLoginWrapper.classList.add('custom-google-button')

	// Add the wrapper to body
	document.body.appendChild(googleLoginWrapper)

	// this button will not appear
	window.google.accounts.id.renderButton(googleLoginWrapper, {
		theme: 'outline',
		size: 'large',
	})

	setTimeout(() => {
		googleLoginWrapper.querySelector('div[role=button]').click()
	})
}

onMounted(() => {
	initGoogleAuth(async (response) => {
		if (!response) {
			console.error('Google Auth Error')
			return false
		}

		loading.value = true
		const payload = {
			login: {
				email: response.email,
				first_name: response.firstName,
				last_name: response.lastName,
				id: response.id,
			},
		}

		const {data} = await useAuthSocialStore().loginGoogle(payload)
		if (data.success) {
			emit('login', data.data.result)
		} else {
			console.error(data.message)
			// await $googleAuth.signOut()
		}

		loading.value = false
	})
})
</script>

<style></style>
