<template>
  <ResizablePanel
    position="bottom"
    :default-size="200"
    :min-size="100"
    :max-size="500"
    :left-panel-size="leftPanelSize"
    :right-panel-size="rightPanelSize"
    :left-panel-collapsed="leftPanelCollapsed"
    :right-panel-collapsed="rightPanelCollapsed"
    v-model:collapsed="isCollapsed"
  >
    <div class="bottom-panel">
      <div class="bottom-header">
        <h3 class="text-lg font-semibold">
          <i class="fas fa-terminal mr-2"></i>
          Console / Logs
        </h3>
        <div class="bottom-actions">
          <button 
            @click="clearLogs" 
            class="action-btn" 
            title="Clear logs"
            aria-label="Clear all logs"
            type="button"
          >
            <span class="sr-only">Clear all logs</span>
            <i class="fas fa-trash" aria-hidden="true"></i>
          </button>
          <button 
            @click="toggleAutoScroll" 
            class="action-btn" 
            :title="autoScroll ? 'Disable auto-scroll' : 'Enable auto-scroll'"
            :aria-label="autoScroll ? 'Disable auto-scroll' : 'Enable auto-scroll'"
            type="button"
          >
            <span class="sr-only">{{ autoScroll ? 'Disable auto-scroll' : 'Enable auto-scroll' }}</span>
            <i class="fas" :class="autoScroll ? 'fa-pause' : 'fa-play'" aria-hidden="true"></i>
          </button>
          <button 
            @click="exportLogs" 
            class="action-btn" 
            title="Export logs"
            aria-label="Export logs to file"
            type="button"
          >
            <span class="sr-only">Export logs to file</span>
            <i class="fas fa-download" aria-hidden="true"></i>
          </button>
        </div>
      </div>
      
      <div 
        ref="logsContainer" 
        class="bottom-content"
        role="log"
        aria-live="polite"
        aria-label="Console logs"
      >
        <div
          v-for="(log, index) in logs"
          :key="`log-${index}-${log.timestamp.getTime()}`"
          :class="['log-entry', `log-${log.level}`]"
        >
          <span class="log-time">{{ formatTime(log.timestamp) }}</span>
          <span class="log-level" :aria-label="`Log level: ${log.level}`">{{ log.level.toUpperCase() }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
        <div v-if="logs.length === 0" class="log-empty">
          No logs available
        </div>
      </div>
    </div>
  </ResizablePanel>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onUnmounted, inject, computed } from 'vue';
import ResizablePanel from './ResizablePanel.vue';

const panelSizes = inject<{
  left: { value: number };
  right: { value: number };
  leftCollapsed: { value: boolean };
  rightCollapsed: { value: boolean };
}>('panelSizes', {
  left: { value: 250 },
  right: { value: 300 },
  leftCollapsed: { value: false },
  rightCollapsed: { value: false },
});

const leftPanelSize = computed(() => panelSizes.left.value);
const rightPanelSize = computed(() => panelSizes.right.value);
const leftPanelCollapsed = computed(() => panelSizes.leftCollapsed.value);
const rightPanelCollapsed = computed(() => panelSizes.rightCollapsed.value);

const isCollapsed = ref(false);
const autoScroll = ref(true);
const logsContainer = ref<HTMLElement | null>(null);
const logs = ref<Array<{ level: string; message: string; timestamp: Date }>>([
  { level: 'info', message: 'System initialized', timestamp: new Date() },
  { level: 'info', message: 'Monitoring services started', timestamp: new Date() },
]);

let logInterval: ReturnType<typeof setInterval> | null = null;
const MAX_LOGS = 1000; // Limit logs to prevent memory issues

const addLog = (level: string, message: string) => {
  logs.value.push({ level, message, timestamp: new Date() });
  
  // Limit log size
  if (logs.value.length > MAX_LOGS) {
    logs.value.shift();
  }
  
  if (autoScroll.value) {
    nextTick(() => {
      scrollToBottom();
    });
  }
};

const scrollToBottom = () => {
  if (logsContainer.value) {
    logsContainer.value.scrollTop = logsContainer.value.scrollHeight;
  }
};

const clearLogs = () => {
  logs.value = [];
};

const toggleAutoScroll = () => {
  autoScroll.value = !autoScroll.value;
  if (autoScroll.value) {
    scrollToBottom();
  }
};

const exportLogs = () => {
  const logText = logs.value
    .map(log => `[${formatTime(log.timestamp)}] ${log.level.toUpperCase()}: ${log.message}`)
    .join('\n');
  
  const blob = new Blob([logText], { type: 'text/plain' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `logs-${new Date().toISOString().split('T')[0]}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const formatTime = (date: Date): string => {
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
};

// Simulate log generation
onMounted(() => {
  logInterval = setInterval(() => {
    const levels = ['info', 'warning', 'error'];
    const messages = [
      'Deployment status updated',
      'Health check completed',
      'Metrics collected',
      'Service health changed',
    ];
    const level = levels[Math.floor(Math.random() * levels.length)];
    const message = messages[Math.floor(Math.random() * messages.length)];
    addLog(level, message);
  }, 5000);
});

onUnmounted(() => {
  if (logInterval) {
    clearInterval(logInterval);
    logInterval = null;
  }
});

defineExpose({ addLog });
</script>

<style scoped>
/* Bottom panel styles moved to panels.css for consistency */
</style>
