<script setup lang="ts">
import { terminalThemes } from '~/composables/useTerminalThemes'

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>
  applyTheme(settings.value.theme || 'dark')
  // Sync terminal theme from server or fallback to localStorage
  if (settings.value.terminalTheme) {
    localStorage.setItem('wraith_terminal_theme', settings.value.terminalTheme)
  }
  if (settings.value.fontSize) {
    localStorage.setItem('wraith_font_size', settings.value.fontSize)
  }
  if (settings.value.scrollbackLines) {
    localStorage.setItem('wraith_scrollback', settings.value.scrollbackLines)
  }
})

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')
  // Persist terminal settings to localStorage for immediate use by useTerminal
  localStorage.setItem('wraith_terminal_theme', settings.value.terminalTheme || 'wraith')
  localStorage.setItem('wraith_font_size', settings.value.fontSize || '14')
  localStorage.setItem('wraith_scrollback', settings.value.scrollbackLines || '10000')
  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 terminalTheme = computed({
  get: () => settings.value.terminalTheme || 'wraith',
  set: (v: string) => { settings.value.terminalTheme = 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-3xl mx-auto p-6">
    <h2 class="text-xl font-bold text-white mb-6">Settings</h2>

    <div class="space-y-8">
      <!-- Appearance -->
      <section>
        <h3 class="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">Appearance</h3>
        <div class="space-y-4">
          <div>
            <label class="block text-sm text-gray-400 mb-1">App Theme</label>
            <select v-model="theme" class="bg-gray-800 text-white px-3 py-2 rounded border border-gray-700 text-sm">
              <option value="dark">Dark</option>
              <option value="light">Light</option>
            </select>
          </div>
        </div>
      </section>

      <!-- Terminal -->
      <section>
        <h3 class="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">Terminal</h3>
        <div class="space-y-4">
          <!-- Terminal Theme Picker -->
          <div>
            <label class="block text-sm text-gray-400 mb-2">Terminal Theme</label>
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2">
              <button
                v-for="t in terminalThemes"
                :key="t.id"
                @click="terminalTheme = t.id"
                class="relative rounded-lg border p-2 text-left transition-all cursor-pointer"
                :class="terminalTheme === t.id
                  ? 'border-wraith-500 ring-1 ring-wraith-500/30'
                  : 'border-gray-700 hover:border-gray-600'"
              >
                <!-- Color preview bar -->
                <div
                  class="h-16 rounded-md mb-1.5 flex items-end p-1.5 gap-px overflow-hidden"
                  :style="{ backgroundColor: (t.theme.background as string) }"
                >
                  <!-- Sample text -->
                  <div class="w-full text-[9px] font-mono leading-tight">
                    <span :style="{ color: (t.theme.green as string) }">user</span><span :style="{ color: (t.theme.foreground as string) }">@</span><span :style="{ color: (t.theme.blue as string) }">host</span><span :style="{ color: (t.theme.foreground as string) }">:~$ </span><span :style="{ color: (t.theme.foreground as string) }">ls -la</span>
                    <br>
                    <span :style="{ color: (t.theme.cyan as string) }">drwxr-xr-x</span>
                    <span :style="{ color: (t.theme.yellow as string) }"> README.md</span>
                    <br>
                    <span :style="{ color: (t.theme.red as string) }">error:</span>
                    <span :style="{ color: (t.theme.foreground as string) }"> not found</span>
                  </div>
                </div>
                <!-- Color swatches -->
                <div class="flex gap-0.5 mb-1">
                  <span v-for="c in [t.theme.red, t.theme.green, t.theme.yellow, t.theme.blue, t.theme.magenta, t.theme.cyan]"
                    :key="(c as string)" class="w-3 h-2 rounded-sm" :style="{ backgroundColor: (c as string) }" />
                </div>
                <p class="text-xs text-gray-300">{{ t.name }}</p>
                <!-- Selected indicator -->
                <div v-if="terminalTheme === t.id" class="absolute top-1 right-1 w-2 h-2 rounded-full bg-wraith-500" />
              </button>
            </div>
            <p class="text-xs text-gray-600 mt-2">Theme applies to new terminal sessions after saving.</p>
          </div>

          <div class="flex gap-6">
            <div>
              <label class="block text-sm text-gray-400 mb-1">Font Size</label>
              <div class="flex items-center gap-2">
                <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-20 text-sm" />
                <span class="text-xs text-gray-500">px</span>
              </div>
            </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-28 text-sm" />
            </div>
          </div>
        </div>
      </section>

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