<script setup lang="ts">
const auth = useAuthStore()
const settings = ref<Record<string, string>>({})
const loading = ref(false)
const saved = ref(false)

onMounted(async () => {
  settings.value = await $fetch('/api/settings', {
    headers: { Authorization: `Bearer ${auth.token}` },
  }) as Record<string, string>
  // Apply theme on load
  applyTheme(settings.value.theme || 'dark')
})

async function save() {
  loading.value = true
  await $fetch('/api/settings', {
    method: 'PUT',
    body: settings.value,
    headers: { Authorization: `Bearer ${auth.token}` },
  })
  loading.value = false
  saved.value = true
  applyTheme(settings.value.theme || 'dark')
  setTimeout(() => (saved.value = false), 2000)
}

function applyTheme(t: string) {
  if (t === 'light') {
    document.documentElement.classList.remove('dark')
    document.documentElement.classList.add('light')
  } else {
    document.documentElement.classList.remove('light')
    document.documentElement.classList.add('dark')
  }
}

const theme = computed({
  get: () => settings.value.theme || 'dark',
  set: (v: string) => {
    settings.value.theme = v
  },
})

const scrollback = computed({
  get: () => settings.value.scrollbackLines || '10000',
  set: (v: string) => {
    settings.value.scrollbackLines = v
  },
})

const fontSize = computed({
  get: () => settings.value.fontSize || '14',
  set: (v: string) => {
    settings.value.fontSize = v
  },
})
</script>

<template>
  <div class="max-w-2xl mx-auto p-6">
    <h2 class="text-xl font-bold text-white dark:text-white mb-6">Settings</h2>

    <div class="space-y-6">
      <div>
        <label class="block text-sm text-gray-400 mb-1">Theme</label>
        <select v-model="theme" class="bg-gray-800 text-white px-3 py-2 rounded border border-gray-700">
          <option value="dark">Dark</option>
          <option value="light">Light</option>
        </select>
      </div>

      <div>
        <label class="block text-sm text-gray-400 mb-1">Terminal Font Size</label>
        <input v-model="fontSize" type="number" min="8" max="32"
          class="bg-gray-800 text-white px-3 py-2 rounded border border-gray-700 w-24" />
        <span class="text-xs text-gray-500 ml-2">px</span>
      </div>

      <div>
        <label class="block text-sm text-gray-400 mb-1">Scrollback Lines</label>
        <input v-model="scrollback" type="number" min="1000" max="100000" step="1000"
          class="bg-gray-800 text-white px-3 py-2 rounded border border-gray-700 w-32" />
      </div>

      <button @click="save" :disabled="loading"
        class="px-4 py-2 bg-wraith-600 hover:bg-wraith-700 text-white rounded disabled:opacity-50">
        {{ saved ? 'Saved!' : loading ? 'Saving...' : 'Save Settings' }}
      </button>
    </div>
  </div>
</template>
