<script setup lang="ts">
import {computed, ref} from "vue";
import {usePage} from "@inertiajs/vue3";
import type {SharedProps, User} from "@/Types/types";

type FollowStatus = 'following' | 'requested' | 'none'

const props = defineProps<{
    user: User
    followStatus: FollowStatus
}>()

const snackbar = ref(false)
const snackbarMessage = ref('')

const status = ref<FollowStatus>(props.followStatus)
const processing = ref(false)

const auth = usePage<SharedProps>().props.auth
const isOwnProfile = computed(() => auth.user?.id == props.user.id)
const isLoggedIn = computed(() => !!auth.user)

const buttonLabel = computed(() => {
    switch (status.value) {
        case 'following': return 'Following'
        case 'requested': return 'Request sent'
        default: return '+ Follow'
    }
})

const follow = async () => {
    processing.value = true
    const response = await fetch(route('profile.follow', { user: props.user.name }), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
        },
    })
    const data = await response.json()
    status.value = data.status

    snackbarMessage.value = data.status === 'following'
        ? `You are now following ${props.user.name}`
        : data.status === 'requested'
            ? `Follow request sent to ${props.user.name}`
            : `You unfollowed ${props.user.name}`
    snackbar.value = true
    processing.value = false
}
</script>

<template>
    <button
        v-if="isLoggedIn && !isOwnProfile"
        class="follow-btn"
        :disabled="processing"
        @click="follow"
    >
        {{ buttonLabel }}
    </button>
    <v-snackbar v-model="snackbar" :timeout="5000" color="#ffc107" location="bottom center">
        {{ snackbarMessage }}
        <template #actions>
            <v-btn variant="text" @click="snackbar = false">Close</v-btn>
        </template>
    </v-snackbar>
</template>

<style scoped>
.follow-btn {
    font-family: 'Share Tech Mono', monospace;
    font-size: 0.75rem;
    letter-spacing: 0.12em;
    color: #ffc107;
    background: none;
    border: 1px solid rgba(255, 193, 7, 0.35);
    border-radius: 4px;
    padding: 0.3em 0.85em;
    cursor: pointer;
    transition: background 0.15s ease;
    white-space: nowrap;
    align-self: center;
}

.follow-btn:hover:not(:disabled) {
    background: rgba(255, 193, 7, 0.1);
}

.follow-btn:disabled {
    opacity: 0.5;
    cursor: default;
}

</style>
