<template>
  <div class="statusEvent" v-if="predecessorRoom !== undefined">
    <i18n-t keypath="message.room_upgraded_view_old" tag="span">
      <template v-slot:link>
        <a v-on:click="goToPredecessor" class="clickable" href="about:blank">{{ $t("message.room_upgraded_link") }}</a>
      </template>
    </i18n-t>
  </div>
  <div class="statusEvent">
    {{ $t('message.user_created_room', {user: eventSenderDisplayName(event)}) }}
  </div>
</template>

<script setup lang="ts">
import { inject, ref, Ref, watch } from "vue";
import { MessageEmits, MessageProps, useMessage } from "./useMessage";
import utils from "@/plugins/utils";
import { Room } from "matrix-js-sdk";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const $matrix: any = inject("globalMatrix");
const $navigation: any = inject("globalNavigation");

const props = defineProps<MessageProps>();
const emits = defineEmits<MessageEmits>();

const predecessorRoom: Ref<Room | undefined> = ref(undefined);

const { event, eventSenderDisplayName } = useMessage(
  $matrix,
  t,
  props,
  undefined,
  undefined
);

watch(props.room, (room) => {
  const rooms = $matrix.matrixClient.getRoomUpgradeHistory(room.roomId, true, true);
  if (rooms && rooms.length > 1) {
    const idx = rooms.indexOf(props.room);
    if (idx > 0) {
      predecessorRoom.value = rooms[idx - 1];
      return;
    }
  }
  predecessorRoom.value = undefined;
}, { immediate: true });

const goToPredecessor = (e: Event) => {
  e.preventDefault();
  e.stopPropagation();
  if (predecessorRoom.value) {
    $navigation.push(
      {
        name: "Chat",
        params: {
          roomId: utils.sanitizeRoomId(predecessorRoom.value.roomId),
        },
      },
      -1
    );
  }
};

</script>

<style lang="scss">
@use "@/assets/css/chat.scss" as *;
</style>