<template>
  <Viewer3cr
    ref="viewer3cr"
    :payload="payload"
    :options="options"
  />
  <DemoInfoModal v-model:modal="m_demoInfo" />
  <DemoPurchaseCreditsModal v-model="m_demoPurchaseCredits" />
  <DemoUpgradeCloudStorageModal v-model="m_demoEnableCloudStorage" />
  <DemoUpgradePlanModal v-model="m_demoUpgradePlan" />
  <UpdateSnackbar />
  <UploadsDrawer
    v-model="showUploads"
    :uploads="uploads"
  />
</template>

<script setup lang="ts">
import Viewer3cr from '@/components/modal/Viewer3cr.vue';
import { useDemoStore } from '@/stores/demo.store';
import { useThemeStore } from '@/stores/theme.store';
import { useUploadStore } from '@/stores/upload.store';
import { ViewerOptions, ViewerPayload } from '@3cr/viewer-types-ts';
import LogRocket from 'logrocket';
import { storeToRefs } from 'pinia';
import { onMounted, ref, watch } from 'vue';
import { useLanguageStore } from './stores/language.store';

const {
  isDemo,
  m_demoInfo,
  m_demoEnableCloudStorage,
  m_demoPurchaseCredits,
  m_demoUpgradePlan,
} = storeToRefs(useDemoStore());
const languageStore = useLanguageStore();
const { theme } = storeToRefs(useThemeStore());
const { uploads, showUploads } = storeToRefs(useUploadStore());

const payload = ref<ViewerPayload>();
const options = ref<ViewerOptions>();
const viewer3cr = ref<InstanceType<typeof Viewer3cr>>();

onMounted(() => {
  theme.value = 'light'; // TODO: undo this once we have Dark Mode designs
  languageStore.setLanguage(languageStore.language);
  if (isDemo.value) {
    LogRocket.init('qfib9l/3crviewer-browser');
  }
});

watch(
  () => options.value?.locale,
  (value?: string) => {
    if (value) {
      languageStore.setLanguage(value);
    }
  },
  { immediate: true },
);

async function loadSession(url: string): Promise<void> {
  await viewer3cr.value?.loadSession(url);
}

async function loadViewer(
  viewerPayload: ViewerPayload,
  viewerOptions: ViewerOptions,
) {
  payload.value = viewerPayload;
  options.value = viewerOptions;
}

defineExpose({ loadViewer, loadSession });
</script>
