<template>
  <div class="h-full flex flex-col bg-slate-900 rounded-lg shadow-lg overflow-hidden border border-slate-700">
    <!-- Header with Tabs -->
    <div class="flex border-b border-slate-700 bg-slate-800">
      <button 
        @click="activeTab = 'sys'"
        :class="['px-4 py-2 text-sm font-medium transition-colors', activeTab === 'sys' ? 'bg-indigo-600 text-white' : 'text-slate-400 hover:text-slate-200 hover:bg-slate-700']"
      >
        System Log
      </button>
      <button 
        @click="activeTab = 'io'"
        :class="['px-4 py-2 text-sm font-medium transition-colors', activeTab === 'io' ? 'bg-indigo-600 text-white' : 'text-slate-400 hover:text-slate-200 hover:bg-slate-700']"
      >
        Data I/O
      </button>
      
      <!-- Dynamic Profile Monitors -->
      <button 
        v-for="(monitor, idx) in (profileConfig?.monitors || [])" 
        :key="idx"
        @click="activeTab = monitor.title"
        :class="['px-4 py-2 text-sm font-medium transition-colors', activeTab === monitor.title ? 'bg-indigo-600 text-white' : 'text-slate-400 hover:text-slate-200 hover:bg-slate-700']"
      >
        {{ monitor.title }}
      </button>
      
      <div class="flex-1 flex justify-end items-center pr-4">
        <button @click="clearLogs" class="text-xs text-slate-500 hover:text-slate-300">
          Clear
        </button>
      </div>
    </div>
    
    <!-- Content Area -->
    <div ref="logContainer" class="flex-1 overflow-y-auto custom-scrollbar relative">
      
      <!-- System Logs -->
      <div v-show="activeTab === 'sys'" class="space-y-1 p-3 font-mono text-xs">
        <div v-for="(log, idx) in sysLogs" :key="idx" class="flex break-words">
          <span class="text-slate-500 mr-2 shrink-0">{{ log.time }}</span>
          <span :class="{
            'text-red-400': log.level === 'error',
            'text-yellow-400': log.level === 'warn',
            'text-slate-300': log.level === 'info',
            'text-slate-500': log.level === 'debug'
          }">
            {{ log.message }}
          </span>
        </div>
      </div>
      
      <!-- Data I/O Logs -->
      <div v-show="activeTab === 'io'" class="space-y-1 p-3 font-mono text-xs">
        <div v-for="(io, idx) in ioLogs" :key="idx" class="flex break-words">
          <span class="text-slate-500 mr-2 shrink-0">{{ io.time }}</span>
          <span :class="io.dir === 'RX' ? 'text-green-400' : 'text-blue-400'">
            <span class="font-bold mr-1">[{{ io.dir }}]</span> {{ io.data }}
          </span>
        </div>
      </div>
      
      <!-- Dynamic Monitor Tables -->
      <template v-for="(monitor, idx) in (profileConfig?.monitors || [])" :key="idx">
         <div v-show="activeTab === monitor.title" class="h-full w-full">
            <EventTable v-if="monitor.type === 'table'" :config="monitor" />
         </div>
      </template>
      
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, inject } from 'vue';
import { subscribeToLogs, subscribeToIO, profileConfig } from '../services/backend';
import EventTable from './EventTable.vue';

const activeTab = ref('sys');
const logContainer = ref(null);

const sysLogs = ref([]);
const ioLogs = ref([]);

const clearTrigger = inject('clearTrigger');
if (clearTrigger) {
    watch(clearTrigger, () => {
        sysLogs.value = [];
        ioLogs.value = [];
    });
}

const MAX_LINES = 1000;

function formatTime() {
    const d = new Date();
    return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}.${d.getMilliseconds().toString().padStart(3, '0')}`;
}

subscribeToLogs((payload) => {
    sysLogs.value.push({
        time: formatTime(),
        level: payload.level || 'info', // Adjust based on Python LogLevel enum
        message: payload.msg
    });
    
    if (sysLogs.value.length > MAX_LINES) sysLogs.value.shift();
    scrollToBottom();
});

subscribeToIO((payload) => {
    ioLogs.value.push({
        time: formatTime(),
        dir: payload.dir, // "RX" or "TX"
        data: payload.data
    });
    
    if (ioLogs.value.length > MAX_LINES) ioLogs.value.shift();
    scrollToBottom();
});

function clearLogs() {
    if (activeTab.value === 'sys') sysLogs.value = [];
    else ioLogs.value = [];
}

let scrollTimeout = null;
function scrollToBottom() {
    // Debounce autoscroll to save performance
    if (scrollTimeout) return;
    
    scrollTimeout = setTimeout(() => {
        if (logContainer.value) {
            logContainer.value.scrollTop = logContainer.value.scrollHeight;
        }
        scrollTimeout = null;
    }, 100);
}
</script>

<style scoped>
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: #475569;
  border-radius: 10px;
}
</style>
