<template>
	<ButtonComponent
		class="bg-black border-charcoal"
		@click="handleAppleLogin"
		:loading="loading"
	>
		<img
			:src="AppleLogo"
			width="16px"
			height="16px"
			alt="apple icon"
		/>

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

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

const emit = defineEmits(['login'])
const AppleLogo = `${SAS_URL}/src/assets/images/icons/apple_light.svg`

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

const authSocial = useAuthSocialStore()

const firebaseConfig = {
	apiKey: "AIzaSyCULJvOuI-k-MAL4TrdWSdV5Sifk9C1TLA",
	authDomain: "breakz-783ea.firebaseapp.com",
	projectId: "breakz-783ea",
	storageBucket: "breakz-783ea.firebasestorage.app",
	messagingSenderId: "175432425925",
	appId: "1:175432425925:web:792683bdc643fd86932bac",
	measurementId: "G-48Y70K9XZF"
};
Vue.onMounted(() => {
	firebase.initializeApp(firebaseConfig)
})

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

	let payload;

	const provider = new window.firebase.auth.OAuthProvider('apple.com');

	provider.addScope('email');
	provider.addScope('name');

	const auth = window.firebase.auth();
	const result = await auth.signInWithPopup(provider);

	loading.value = true;
	try {
		payload = {
			login: {
				email: result.user?.email ?? result.user.providerData[0].email,
				first_name: result.user.displayName.split(' ')[0],
				last_name: result.user.displayName.split(' ').pop(),
				id: result.user.providerData[0].uid,
			},
		}
	} catch (e) {
		console.error(e);
		loading.value = false;
		return;
	}

	const {data} = await authSocial.loginApple(payload);
	if (data.success) {
		emit('login', data.data.result)
	} else {
		console.error(data.message);
	}

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

<style></style>
