<script setup lang="ts">
import { ref } from 'vue';

const email = ref<string>("");
const pass = ref<string>("");
const text = ref<string>("");

const emit = defineEmits(['nextPage']);

async function login(e: SubmitEvent) {
    text.value = "";
    e.preventDefault();
    const res = await fetch("http://localhost:3000/login", {
        method: "POST",
        body: JSON.stringify({ email: email.value, pass: pass.value }),
        headers: new Headers({'content-type': 'application/json'})
    });
    if (res.ok) {
        cookieStore.set("loggedIn", "true");
        let uid = await res.json();
        cookieStore.set("userId", uid.uid.Id);
        emit('nextPage');
    } else {
        text.value = await res.text();
    }
}

async function signup(e: Event) {
    text.value = "";
    e.preventDefault();
    const res = await fetch("http://localhost:3000/createUser", {
        method: "POST",
        body: JSON.stringify({ email: email.value, pass: pass.value, name: email.value.split("@")[0] }),
        headers: new Headers({'content-type': 'application/json'})
    });
    if (res.ok) {
        cookieStore.set("loggedIn", "true");
        let uid = await res.json();
        cookieStore.set("userId", uid.uid.Id);
        emit('nextPage');
    } else {
        text.value = await res.text();
    }
} 

</script>

<template>
    <h1>Login</h1>
    <form @submit="login">
        <label for="email">Email</label> <br>
        <input type="email" id="email" v-model="email"/> <br>
        <label for="pass">Password</label> <br>
        <input type="password" id="pass" v-model="pass"/> <br>
        <button type="submit">Sign in</button> <br>
        <button type="button" @click="signup">Sign up</button>
        <p>{{ text }}</p>
    </form>
</template>