<template>
    <div class="statusbar">
        <template v-for="item in statusItems" :key="item.key">
            <div class="status-item" v-if="item.value !== null" :title="$t(`falukant.statusbar.${item.key}`)">
                <span class="status-icon">{{ item.icon }}: {{ item.value }}</span>
            </div>
        </template>
    </div>
</template>

<script>
import { mapState } from "vuex";
import apiClient from "@/utils/axios.js";

export default {
    name: "StatusBar",
    data() {
        return {
            statusItems: [
                { key: "age", icon: "👶", value: 0 },
                { key: "wealth", icon: "💰", value: 0 },
                { key: "health", icon: "❤️", value: "Good" },
                { key: "events", icon: "📰", value: null },
            ],
        };
    },
    computed: {
        ...mapState(["socket"]),
    },
    async mounted() {
        await this.fetchStatus();
        if (this.socket) {
            this.socket.on("falukantUpdateStatus", this.fetchStatus);
        }
    },
    beforeUnmount() {
        if (this.socket) {
            this.socket.off("falukantUpdateStatus", this.fetchStatus);
        }
    },
    methods: {
        async fetchStatus() {
            try {
                const response = await apiClient.get("/api/falukant/info");
                const { money, character, events } = response.data;
                const { age, health } = character;
                let healthStatus = '';
                if (health > 90) {
                    healthStatus = this.$t("falukant.health.amazing");
                } else if (health > 75) {
                    healthStatus = this.$t("falukant.health.good");
                } else if (health > 50) {
                    healthStatus = this.$t("falukant.health.normal");
                } else if (health > 25) {
                    healthStatus = this.$t("falukant.health.bad");
                } else {
                    healthStatus = this.$t("falukant.health.very_bad");
                }
                this.statusItems = [
                    { key: "age", icon: "👶", value: age },
                    { key: "wealth", icon: "💰", value: money },
                    { key: "health", icon: "❤️", value: healthStatus },
                    { key: "events", icon: "📰", value: events || null },
                ];
            } catch (error) {
                console.error("Error fetching status:", error);
            }
        },
    },
};
</script>

<style scoped>
.statusbar {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f4f4f4;
    border: 1px solid #ccc;
    border-radius: 4px;
    width: calc(100% + 40px);
    gap: 2em;
    margin: -21px -20px 1.5em -20px;
    position: fixed;
}

.status-item {
    text-align: center;
    cursor: pointer;
}

.status-icon {
    font-size: 14px;
}
</style>
