<template>
  <main class="container">
    <h1>{{ t('nav.debug') }}</h1>
    <p>{{ t('debug.readonly') }}</p>

    <section class="card">
      <p v-if="message">{{ message }}</p>
      <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
        <input type="checkbox" v-model="autoRefresh" />
        {{ t('debug.autoRefresh') }}
      </label>
      <pre style="white-space: pre-wrap;">{{ logs }}</pre>
      <div style="margin-top: 12px;">
        <button class="card" type="button" @click="reload">{{ t('actions.reload') }}</button>
        <button class="card" type="button" @click="copyLogs">{{ t('actions.copy') }}</button>
      </div>
    </section>
  </main>
</template>

<script setup lang="ts">
const { apiBase, getErrorMessage } = useApi()
const { t } = useI18n()

const logs = ref('')
const message = ref('')
const autoRefresh = ref(false)
let intervalId: ReturnType<typeof setInterval> | null = null

const reload = async () => {
  message.value = ''
  try {
    const data = await $fetch<{ logs: string }>(`${apiBase}/debug/logs`)
    logs.value = data?.logs || ''
  } catch (err) {
    message.value = getErrorMessage(err, t('errors.load'))
  }
}

const copyLogs = async () => {
  message.value = ''
  try {
    await navigator.clipboard.writeText(logs.value || '')
    message.value = t('messages.copied')
  } catch (err) {
    message.value = getErrorMessage(err, t('errors.copy'))
  }
}

watch(autoRefresh, (enabled) => {
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
  if (enabled) {
    intervalId = setInterval(reload, 5000)
  }
})

onMounted(reload)
onBeforeUnmount(() => {
  if (intervalId) clearInterval(intervalId)
})
</script>
