<template>
  <pn-page-card>
    <template #title>
      {{ $t(type + '__title') }}
    </template>
    <pn-scroll-list>
      <div class="q-px-md">
        <div
          v-if="fileText"
          style="white-space: pre-wrap;"
          >
          {{ fileText }}
        </div>
        <div
          v-else
          align="center"
          class="text-negative"
          >
          {{ $t(type + '__not_ready') }}
        </div>
      </div>
    </pn-scroll-list>
    <div
      class="flex column justify-center items-center w100"
      style="position: absolute; bottom: 0;"
      v-if="isLoading"
      >
      <q-linear-progress indeterminate />
    </div>
  </pn-page-card>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useSettingsStore } from 'stores/settings'

  const fileText = ref<string>('')
  const isLoading = ref<boolean>(true)
  const error = ref<boolean>(false)
  const settingsStore = useSettingsStore()
  const lang = ref<string>('EN')

  const props = defineProps<{
    type: 'terms_of_use' | 'privacy'
  }>()

  function parseLocale(locale: string): string {
    return locale.split(/[-_]/)[0] ?? ''
  }

  const baseDocName = 
    props.type ==='terms_of_use' ? 'Terms_of_use' : 'Privacy'

  onMounted(async () => {
    const locale = settingsStore.settings.locale
    lang.value = parseLocale(locale)
    try {
      const response = await fetch('/admin/doc/' + baseDocName + '_' + lang.value +'.txt')
      
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }
      
      fileText.value = await response.text()
    } catch (err) {
      console.error('File load error:', err)
      error.value = true
    } finally {
      isLoading.value = false
    }
  })
</script>

<style>
</style>
