<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { getInstance } from 'src/services/keycloak';
import useUtilsStore from 'stores/utils';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';

const $q = useQuasar();
const { locale } = useI18n();
const utilsStore = useUtilsStore();
const EDM_SERVICE = import.meta.env.VITE_EDM_MICRO_FRONTEND_URL;
const kc = getInstance();
const at = ref(kc.token);
const rt = ref(kc.refreshToken);
const iframe = ref<InstanceType<typeof HTMLIFrameElement>>();

function sendMessage() {
  iframe?.value?.contentWindow?.postMessage(
    {
      i18n: locale.value,
      darkMode: $q.dark.isActive,
    },
    '*',
  );
}

onMounted(() => {
  utilsStore.currentTitle.title = 'menu.dms';
  utilsStore.currentTitle.path = [
    {
      text: '',
      i18n: true,
      handler: () => {},
    },
  ];
  sendMessage();
});

watch(
  () => kc.token,
  () => {
    at.value = kc.token;
    rt.value = kc.refreshToken;
  },
);

watch([locale, $q.dark], () => {
  sendMessage();
});
</script>

<template>
  <iframe
    ref="iframe"
    :src="`${EDM_SERVICE}/?at=${at}&rt=${rt}`"
    frameborder="0"
    class="full-width full-height rounded"
    allowtransparency="true"
  ></iframe>
</template>

<style scoped></style>
