<template>
    <div v-if="!userLoaded" class="bg-neutral-100 dark:bg-neutral-900 text-primary h-screen flex flex-col">
        Loading
    </div>
    <div v-else>
        <div v-if="isAuthenticated" class="bg-neutral-100 dark:bg-neutral-900 text-primary h-screen flex flex-col">
            <LayoutTopbar />
            <div class="overflow-y-auto pt-3">
                <NuxtPage />
            </div>
            <LayoutNavbar class="mt-auto" />
        </div>
        <div v-else class="bg-neutral-100 dark:bg-neutral-900 text-primary h-screen flex flex-col">
            <Login />
        </div>
    </div>
</template>

<script setup>
import { doc, getFirestore, serverTimestamp, writeBatch, collection, getDoc } from "firebase/firestore";
import { getAuth, onAuthStateChanged, signInWithEmailAndPassword } from "firebase/auth";

const db = getFirestore()
const route = useRoute()

const isAuthenticated = ref(false)
const user = ref('frikandel')
const auth = ref(null)
const userLoaded = ref(false)
const userData = ref(null)
const userPersons = ref([])
const userAllPersons = ref([])

onMounted(() => {
    auth.value = getAuth()

    onAuthStateChanged(auth.value, async (usr) => {
        if (usr) {
            user.value = usr

            let docRef = doc(db, "users", user.value.uid);
            let docSnap = await getDoc(docRef);

            if (docSnap.exists()) {
                const data = docSnap.data()
                userData.value = data
                getPersons(userData.value.relatiecodes)
            }

            isAuthenticated.value = true

        } else {
            isAuthenticated.value = false
            user.value = null
            userData.value = null
            userPersons.value = []
        }

        userLoaded.value = true
    })
})

const getPersons = async (persons) => {
    userPersons.value = [];

    for (let i = 0; i < persons.length; i++) {
        const docRef = doc(db, "ledenlijst", persons[i]);
        const docSnap = await getDoc(docRef);

        if (docSnap.exists()) {
            userPersons.value.push(docSnap.data())
        }
    }
}

const ledenlijst = ref([])

provide('firebase', { db, ledenlijst, isAuthenticated, user, userData, userPersons, auth, userAllPersons, getPersons })
</script>