<template>
    <div v-if="enabled" :class="`alert alert-${colour}`">
        <Icon v="user-chart" />
        <T :params="{ item, percentage: `${percentage}%` }">census.stats.{{ type }}</T>
        <br>
        <small><T :params="{ edition, year: edition.slice(-4) }">census.stats.source</T></small>
    </div>
</template>

<script>
import { fetchJson } from '../src/fetchJson.js';

export default {
    props: {
        type: { required: true },
        item: { required: true },
        colour: { default: 'light' },
    },
    data() {
        if (!this.$config.census.enabled || !this.$config.census.latestResults) {
            return {
                enabled: false,
            };
        }

        try {
            return {
                enabled: true,
                edition: this.$config.census.latestResults,
                percentage: fetchJson(
                    `${this.$config.census.latestResults}/general/stats.json`,
                    `${this.type}.${this.item}`,
                ),
            };
        } catch (e) {
            console.error(e);
            return {
                enabled: false,
            };
        }
    },
};
</script>
