<script setup lang="ts">
import { ref, computed, nextTick, watch, onMounted } from 'vue'
import { useLogsStore } from '../stores/logs'
import { Trash2, Search } from 'lucide-vue-next'

const logsStore = useLogsStore()
const logsContainer = ref<HTMLElement | null>(null)
const filterLevel = ref<'all' | 'info' | 'error'>('all')
const searchQuery = ref('')

const filteredLogs = computed(() => {
  return logsStore.logs.filter(log => {
    if (filterLevel.value !== 'all' && log.level !== filterLevel.value) return false
    if (searchQuery.value && !log.message.toLowerCase().includes(searchQuery.value.toLowerCase()) && !log.taskId.includes(searchQuery.value)) return false
    return true
  })
})

// Restore scroll position on mount
onMounted(() => {
    if (logsContainer.value) {
        logsContainer.value.scrollTop = logsStore.scrollTop
        // If it was auto-scrolling, ensure it's at bottom in case new logs arrived while away
        if (logsStore.autoScroll) {
             logsContainer.value.scrollTop = logsContainer.value.scrollHeight
        }
    }
})

// Auto-scroll watcher
watch(() => logsStore.logs.length, () => {
  if (logsStore.autoScroll) {
    nextTick(() => {
      if (logsContainer.value) {
        logsContainer.value.scrollTop = logsContainer.value.scrollHeight
      }
    })
  }
})

function handleScroll(e: Event) {
    const target = e.target as HTMLElement;
    logsStore.scrollTop = target.scrollTop;
    
    // Check if user is near bottom (allow 20px threshold)
    const isAtBottom = target.scrollTop + target.clientHeight >= target.scrollHeight - 20;
    logsStore.autoScroll = isAtBottom;
}

function formatTime(ts: number) {
    const d = new Date(ts)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hours = String(d.getHours()).padStart(2, '0')
    const minutes = String(d.getMinutes()).padStart(2, '0')
    const seconds = String(d.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
</script>

<template>
  <div class="flex flex-col h-full p-6">
      <!-- Header -->
      <div class="flex justify-between items-center mb-6">
          <div>
            <h1 class="text-3xl font-bold text-zinc-900 dark:text-white">运行日志</h1>
            <!-- <p class="text-gray-500 dark:text-gray-400 mt-2">下载任务的实时输出。</p> -->
          </div>
          
          <div class="flex items-center gap-3">
             <!-- Search -->
             <div class="relative">
                 <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                 <input 
                    v-model="searchQuery"
                    type="text" 
                    placeholder="搜索日志..." 
                    class="pl-9 pr-4 py-2 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 text-zinc-900 dark:text-white w-48"
                 />
             </div>

             <!-- Level Filter -->
             <div class="flex bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-xl p-1">
                 <button 
                    @click="filterLevel = 'all'"
                    class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
                    :class="filterLevel === 'all' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
                 >全部</button>
                 <button 
                    @click="filterLevel = 'info'"
                    class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
                    :class="filterLevel === 'info' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
                 >信息</button>
                 <button 
                    @click="filterLevel = 'error'"
                    class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
                    :class="filterLevel === 'error' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
                 >错误</button>
             </div>

             <button 
                @click="logsStore.clearLogs"
                class="p-2 text-gray-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 rounded-xl transition-colors border border-gray-200 dark:border-zinc-800 bg-white dark:bg-zinc-900"
                title="清空日志"
             >
                <Trash2 class="w-4 h-4" />
             </button>
          </div>
      </div>

      <!-- Logs Console -->
      <div class="flex-1 overflow-hidden relative bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800 font-mono text-xs md:text-sm">
          <div 
            ref="logsContainer"
            class="absolute inset-0 overflow-auto p-4 space-y-1"
            @scroll="handleScroll"
          >
              <div v-if="filteredLogs.length === 0" class="h-full flex items-center justify-center text-gray-400 dark:text-gray-600">
                  暂无日志
              </div>
              <div v-for="log in filteredLogs" :key="log.id" class="flex gap-4 hover:bg-gray-50 dark:hover:bg-zinc-800/50 px-2 py-1 rounded transition-colors">
                  <span class="text-gray-400 dark:text-zinc-600 shrink-0 select-none w-36">{{ formatTime(log.timestamp) }}</span>
                  <span 
                    class="break-all whitespace-pre-wrap"
                    :class="log.level === 'error' ? 'text-red-500 dark:text-red-400' : 'text-zinc-700 dark:text-gray-300'"
                  >{{ log.message }}</span>
              </div>
          </div>
          
          <!-- Auto-scroll indicator -->
          <div v-if="!logsStore.autoScroll" class="absolute bottom-4 right-4">
              <button 
                @click="() => { if(logsContainer) { logsContainer.scrollTop = logsContainer.scrollHeight; logsStore.autoScroll = true; } }"
                class="bg-blue-600 hover:bg-blue-700 text-white text-xs px-3 py-1.5 rounded-full shadow-lg transition-colors"
              >
                  恢复自动滚动
              </button>
          </div>
      </div>
  </div>
</template>