<script setup lang="ts">
import useDialogue from '~/composables/useDialogue.ts';

const email = ref('');
const saving = ref(false);
const subscribed = ref(false);

const dialogue = useDialogue();
const subscribe = async () => {
    saving.value = true;
    try {
        await dialogue.postWithAlertOnError('/api/subscription/subscribe', {
            type: 'census',
            email: email.value,
        });
        subscribed.value = true;
    } finally {
        saving.value = false;
    }
};
</script>

<template>
    <div class="alert alert-light border">
        <p><T>census.subscribe.encouragement</T></p>

        <form @submit.prevent="subscribe">
            <div v-if="saving" class="text-center">
                <Spinner />
            </div>
            <div v-else-if="subscribed" class="text-success">
                <Icon v="badge-check" />
                <T>census.subscribe.success</T>
            </div>
            <div v-else class="input-group">
                <input v-model="email" type="email" class="form-control" placeholder="you@example.com">
                <button class="btn btn-outline-primary" type="submit">
                    <Icon v="mailbox" />
                    <T>census.subscribe.action</T>
                </button>
            </div>
        </form>
    </div>
</template>
