<template>
    <div
        class="mag-connection-status"
        v-if="state !== 'connected' || showConnected"
        :class="state"
    >
        <span v-if="state === 'connected'">
            {{ i18n.t("connectionStatus.connected") }}
        </span>
        <span v-if="state === 'exponentialBackoff' || state === 'initial'">
            {{ i18n.t("connectionStatus.reconnecting") }}
            <MkEllipsis />
        </span>
        <span v-else-if="state === 'failed' || state === 'closed'">
            {{ i18n.t("connectionStatus.disconnected") }}
        </span>
    </div>
</template>
<script lang="ts" setup>
import { i18n } from "@/i18n";
import { magStream } from "@/stream";
import { MagChannelState } from "magnetar-common";
import { onMounted, onUnmounted, ref } from "vue";

defineProps<{
    showConnected?: boolean;
}>();

const state = ref<MagChannelState>(magStream.state);
let stateListener: (e: MagChannelState) => void = (e) => {
    if (
        state.value !== "initial" &&
        state.value !== "connected" &&
        e === "connected"
    ) {
        emit("reconnect");
    }

    state.value = e;
};

onMounted(() => {
    magStream.on("stateChange", stateListener);
});

onUnmounted(() => {
    magStream.off("stateChange", stateListener);
});

const emit = defineEmits<{
    (e: "reconnect"): void;
}>();
</script>
<style lang="scss" scoped>
.mag-connection-status {
    padding: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--infoBg);
    color: var(--infoFg);

    // Experimental
    position: sticky;
    z-index: 5;
    top: 0;

    &.closed,
    &.failed {
        background-color: var(--infoWarnBg);
        color: var(--error);
    }

    &.exponentialBackoff {
        background-color: var(--infoWarnBg);
        color: var(--infoWarnFg);
    }
}
</style>
