<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 props = defineProps<{
    type: 'terms_of_use' | 'privacy'
  }>()

  const settingsStore = useSettingsStore()
  const fileText = ref<string | null>('')
  const isLoading = ref(true)
  const DEFAULT_LANG = 'ru'

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

  const parseLocale = (locale: string) => locale.split(/[-_]/)[0] || DEFAULT_LANG

  const fetchDocument = async (language: string) => {
    try {
      const response = await fetch(`/admin/doc/${baseDocName}_${language}.txt`)
      if (!response.ok) throw new Error(`HTTP ${response.status}`)
      return await response.text()
    } catch (error) {
      console.error(`Failed to load ${language} version:`, error)
      return null
    }
  }

  onMounted(async () => {
    try {
      const lang = parseLocale(settingsStore.settings.locale)
      
      fileText.value = await fetchDocument(lang)
      
      if (!fileText.value && lang !== DEFAULT_LANG) {
        fileText.value = await fetchDocument(DEFAULT_LANG)
      }
      
      if (!fileText.value) throw new Error('All loading attempts failed')
      
    } catch (error) {
      console.error('Document loading failed:', error)
    } finally {
      isLoading.value = false
    }
  })
</script>

<style>
</style>
