<template>
    <div class="d-flex align-items-center">
        <authenticated-image v-if="profilePictureUrl"
                             :src="profilePictureUrl"
                             :owner="displayUsername"
                             :alt="displayUsername"
                             :title="displayUsername"
                             img-class="rounded-circle mr-2"
                             :width="width"
                             :height="height"
                             fit="cover"/>
        <span>{{ displayUsername }}</span>
    </div>
</template>

<script>
import AuthenticatedImage from "@/components/AuthenticatedImage.vue";
import {mapGetters, mapActions} from 'vuex';

export default {
    name: 'UserNameTag',
    components: {
        AuthenticatedImage
    },
    props: {
        user: {
            type: Object,
            required: true
        },
        width: {
            type: Number,
            default: 32
        },
        height: {
            type: Number,
            default: 32
        }
    },
    computed: {
        ...mapGetters(['allUserProfiles']),
        displayUsername() {
            return this.user.username || this.user.owner || '';
        },
        profilePictureUrl() {
            // Check for explicitly set profile picture from allUserProfiles getter
            const storedProfile = this.allUserProfiles[this.displayUsername];
            if (storedProfile?.profile_picture?.name) {
                return storedProfile.profile_picture.name;
            }
            return null;
        }
    },
    methods: {
        ...mapActions(['fetchFriendProfile']),
        fetchProfileIfNeeded() {
            // Fetch profile if not already in store
            if (!this.allUserProfiles[this.displayUsername] && this.displayUsername) {
                this.fetchFriendProfile({username: this.displayUsername});
            }
        }
    },
    mounted() {
        this.fetchProfileIfNeeded();
    },
    watch: {
        displayUsername() {
            this.fetchProfileIfNeeded();
        }
    }
}
</script>

<style scoped>
</style>



