<template>
    <v-form @submit.prevent>
        <v-text-field :label="l.email" v-model="form.email" type="email" required></v-text-field>
        <v-text-field :label="l.password" v-model="form.password" type="password" required></v-text-field>
        <template v-if="mode==='register'">
            <v-text-field :label="l.passwordRetype" v-model="form.passConfirm" type="password" required></v-text-field>
            <v-img :src="`/api/user/captcha?${captchaIter}`" class="my-2" height="100px"></v-img>
            <v-text-field :label="l.confirmCaptcha" v-model="form.captcha" required></v-text-field>
        </template>
        <v-btn @click="login" :color="mode=='login' ? 'green' : 'grey'" :type="mode=='login' ? 'submit' : 'button'">{{l.signin}}</v-btn>
        <v-btn @click="register" :color="mode=='register' ? 'green' : 'grey'" :type="mode=='register' ? 'submit' : 'button'" class="float-right">{{l.signup}}</v-btn>
    </v-form>
</template>

<script>
export default {
    data() {
        return {
            form:{
                email: '',
                password: '',
                passConfirm: ''
            },
            mode:'login', // or 'register'
            captchaIter: Math.random()
        }
    },
    methods: {
        async login() {
            // Implement login logic here
            if (this.mode == 'login') {
                // Perform login
                let response = await this.$api.user.signin(this.form);
                if(response.data?.status === 'OK') {
                    await this.loadUser();
                    this.$emit('login-success');
                } else {
                    this.toast(this.getErrorText(response.data), 'red');
                }
            } else {
                this.mode = 'login';
            }
        },
        async register() {
            if (this.mode == 'register') {
                // Implement registration logic here
                let response = await this.$api.user.signup(this.form);
                if(response.data?.status === 'OK') {
                    this.toast(this.l.signupSuccess, 'green');
                    await this.loadUser();
                } else {
                    this.toast(this.getErrorText(response.data), 'red');
                }
            } else {
                this.mode = 'register';
            }
        }
    }
}
</script>