<template>
  <section class="bg-white border border-gray-200 rounded-xl p-6">
    <h3 class="text-xl font-semibold text-gray-800 mb-2">Document Preferences</h3>
    <p class="text-sm text-gray-600 mb-4">Choose how PDF documents open when you click on them.</p>

    <div class="space-y-3">
      <label class="flex items-center gap-3 cursor-pointer">
        <input
          type="radio"
          name="pdf_open_mode"
          value="in_app"
          v-model="pdfOpenMode"
          class="text-indigo-600 focus:ring-indigo-500"
        />
        <span class="text-sm text-gray-700">Open documents in-app</span>
      </label>
      <label class="flex items-center gap-3 cursor-pointer">
        <input
          type="radio"
          name="pdf_open_mode"
          value="new_tab"
          v-model="pdfOpenMode"
          class="text-indigo-600 focus:ring-indigo-500"
        />
        <span class="text-sm text-gray-700">Open documents in new tab</span>
      </label>
    </div>

    <!-- Save feedback -->
    <p v-if="saveFeedback" class="text-xs text-green-600 mt-3">{{ saveFeedback }}</p>
    <p v-if="saveError" class="text-xs text-red-600 mt-3">{{ saveError }}</p>
  </section>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import * as api from '../../api/client.js'

const pdfOpenMode = ref('new_tab')
const saveFeedback = ref('')
const saveError = ref('')
let feedbackTimer = null

onMounted(async () => {
  try {
    const prefs = await api.getMyPreferences()
    pdfOpenMode.value = prefs.pdf_open_mode || 'new_tab'
  } catch {
    // Default to new_tab if preferences can't be loaded
  }
})

watch(pdfOpenMode, async (newValue) => {
  saveFeedback.value = ''
  saveError.value = ''
  clearTimeout(feedbackTimer)
  try {
    await api.updateMyPreferences({ pdf_open_mode: newValue })
    saveFeedback.value = 'Preferences saved.'
    feedbackTimer = setTimeout(() => { saveFeedback.value = '' }, 3000)
  } catch (e) {
    saveError.value = e.message || 'Failed to save preferences.'
  }
})
</script>
