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

const auth = useAuthStore()
const sessions = useSessionStore()
const showSettings = ref(false)

// Redirect to login if not authenticated
if (!auth.isAuthenticated) {
  navigateTo('/login')
}

// Settings state
const settings = ref<Record<string, string>>({})
const settingsLoading = ref(false)
const settingsSaved = ref(false)

onMounted(async () => {
  if (!auth.isAuthenticated) return
  try {
    settings.value = await $fetch('/api/settings') as Record<string, string>
    // Sync 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)
  } catch {
    // defaults
  }
  document.documentElement.classList.add('dark')
})

async function saveSettings() {
  settingsLoading.value = true
  await $fetch('/api/settings', {
    method: 'PUT',
    body: settings.value,
  })
  settingsLoading.value = false
  settingsSaved.value = true
  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(() => (settingsSaved.value = false), 2000)
}

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="h-screen flex flex-col bg-gray-950 text-gray-100">
    <!-- Top bar -->
    <header class="h-12 flex items-center justify-between px-4 bg-gray-900 border-b border-gray-800 shrink-0">
      <div class="flex items-center gap-2">
        <img src="/wraith-logo.png" alt="Wraith" class="h-8" />
      </div>
      <div class="flex items-center gap-3">
        <NuxtLink to="/" class="text-sm text-gray-400 hover:text-white" @click="sessions.goHome()">Home</NuxtLink>
        <NuxtLink to="/vault" class="text-sm text-gray-400 hover:text-white" @click="sessions.goHome()">Vault</NuxtLink>
        <NuxtLink v-if="auth.isAdmin" to="/admin/users" class="text-sm text-gray-400 hover:text-white" @click="sessions.goHome()">Users</NuxtLink>
        <NuxtLink to="/profile" class="text-sm text-gray-400 hover:text-white" @click="sessions.goHome()">Profile</NuxtLink>
        <button @click="showSettings = !showSettings" class="text-sm text-gray-400 hover:text-white" :class="showSettings ? 'text-white' : ''">Settings</button>
        <button @click="auth.logout()" class="text-sm text-gray-500 hover:text-red-400">Logout</button>
      </div>
    </header>

    <!-- Session tab bar — visible when sessions exist -->
    <TerminalTabs v-if="sessions.hasSessions" />

    <!-- Main content area -->
    <div class="flex-1 flex overflow-hidden relative">
      <!-- Page content — visible when no sessions or Home tab is active -->
      <div v-show="!sessions.hasSessions || sessions.showHome" class="absolute inset-0 flex flex-col overflow-hidden">
        <slot />
      </div>

      <!-- Session panels overlay — visible when sessions exist and Home is not active -->
      <SessionPanels v-if="sessions.hasSessions" v-show="!sessions.showHome" />

      <!-- Settings sidebar overlay -->
      <aside
        v-if="showSettings"
        class="absolute right-0 top-0 h-full w-96 bg-gray-900 border-l border-gray-800 shadow-2xl z-50 flex flex-col overflow-y-auto"
      >
        <!-- Header -->
        <div class="p-4 border-b border-gray-800 flex items-center justify-between shrink-0">
          <h3 class="text-sm font-semibold text-white">Settings</h3>
          <button @click="showSettings = false" class="text-gray-500 hover:text-gray-300 text-lg leading-none">&times;</button>
        </div>

        <div class="p-4 space-y-6 flex-1 overflow-y-auto">
          <!-- Terminal Theme Picker -->
          <section>
            <h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Terminal Theme</h4>
            <div class="grid grid-cols-2 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'"
              >
                <div
                  class="h-14 rounded-md mb-1 flex items-end p-1.5 overflow-hidden"
                  :style="{ backgroundColor: (t.theme.background as string) }"
                >
                  <div class="w-full text-[8px] 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</span>
                    <br>
                    <span :style="{ color: (t.theme.cyan as string) }">drwxr-xr-x</span>
                    <span :style="{ color: (t.theme.yellow as string) }"> README</span>
                    <br>
                    <span :style="{ color: (t.theme.red as string) }">error:</span>
                    <span :style="{ color: (t.theme.foreground as string) }"> fail</span>
                  </div>
                </div>
                <div class="flex gap-0.5 mb-0.5">
                  <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-2.5 h-1.5 rounded-sm" :style="{ backgroundColor: (c as string) }" />
                </div>
                <p class="text-[11px] text-gray-300">{{ t.name }}</p>
                <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-[10px] text-gray-600 mt-2">Applies to new terminal sessions.</p>
          </section>

          <!-- Font Size & Scrollback -->
          <section>
            <h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Terminal Options</h4>
            <div class="space-y-3">
              <div>
                <label class="block text-xs 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-1.5 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-xs 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-1.5 rounded border border-gray-700 w-28 text-sm" />
              </div>
            </div>
          </section>
        </div>

        <!-- Save button -->
        <div class="p-4 border-t border-gray-800 shrink-0">
          <button @click="saveSettings" :disabled="settingsLoading"
            class="w-full py-2 bg-wraith-600 hover:bg-wraith-700 text-white rounded text-sm font-medium disabled:opacity-50">
            {{ settingsSaved ? 'Saved!' : settingsLoading ? 'Saving...' : 'Save Settings' }}
          </button>
        </div>
      </aside>
    </div>
  </div>
</template>
