<!--
/**
 * Logs View - View and Copy Android Logs
 * 
 * @author Matthew Raymer
 * @version 1.0.0
 */
-->

<template>
  <div class="logs-view">
    <div class="view-header">
      <h1 class="page-title">📋 Android Logs</h1>
      <p class="page-subtitle">View and copy DailyNotification plugin logs</p>
    </div>
    
    <div class="logs-controls">
      <button 
        class="control-button refresh-button" 
        @click="refreshLogs"
        :disabled="isRefreshing"
      >
        <span v-if="isRefreshing">🔄</span>
        <span v-else>🔄</span>
        {{ isRefreshing ? 'Refreshing...' : 'Refresh Logs' }}
      </button>
      
      <button 
        class="control-button copy-button" 
        @click="copyLogsToClipboard"
        :disabled="!hasLogs || isCopying"
      >
        <span v-if="isCopying">📋</span>
        <span v-else>📋</span>
        {{ isCopying ? 'Copying...' : 'Copy to Clipboard' }}
      </button>
      
      <button 
        class="control-button clear-button" 
        @click="clearLogs"
        :disabled="!hasLogs"
      >
        🗑️ Clear Logs
      </button>
    </div>
    
    <div class="logs-container">
      <div v-if="hasLogs" class="logs-content">
        <div class="logs-header">
          <span class="logs-count">{{ logs.length }} log entries</span>
          <span class="logs-timestamp">Last updated: {{ lastUpdated }}</span>
        </div>
        
        <div class="logs-list" ref="logsList">
          <div 
            v-for="(log, index) in logs" 
            :key="index"
            class="log-entry"
            :class="getLogLevelClass(log)"
          >
            <span class="log-timestamp">{{ formatTimestamp(log.timestamp) }}</span>
            <span class="log-level">{{ log.level }}</span>
            <span class="log-tag">{{ log.tag }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </div>
      
      <div v-else class="no-logs">
        <div class="empty-state">
          <span class="empty-icon">📋</span>
          <h3 class="empty-title">No Logs Available</h3>
          <p class="empty-description">
            Click "Refresh Logs" to fetch DailyNotification plugin logs from the device
          </p>
        </div>
      </div>
    </div>
    
    <!-- Success/Error Messages -->
    <div v-if="successMessage" class="message success-message">
      ✅ {{ successMessage }}
    </div>
    
    <div v-if="errorMessage" class="message error-message">
      ❌ {{ errorMessage }}
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-facing-decorator'
import { Capacitor } from '@capacitor/core'

interface LogEntry {
  timestamp: string
  level: string
  tag: string
  message: string
}

@Component
export default class LogsView extends Vue {
  logs: LogEntry[] = []
  isRefreshing = false
  isCopying = false
  successMessage = ''
  errorMessage = ''
  lastUpdated = ''
  
  get hasLogs(): boolean {
    return this.logs.length > 0
  }
  
  async refreshLogs(): Promise<void> {
    this.isRefreshing = true
    this.clearMessages()
    
    try {
      if (!Capacitor.isNativePlatform()) {
        // Mock logs for web testing
        this.logs = this.generateMockLogs()
        this.lastUpdated = new Date().toLocaleString()
        this.successMessage = 'Mock logs loaded (web mode)'
        return
      }
      
      // In a real implementation, you would fetch logs from the device
      // For now, we'll simulate fetching logs
      await this.simulateLogFetch()
      
    } catch (error) {
      console.error('❌ Failed to refresh logs:', error)
      this.errorMessage = 'Failed to refresh logs: ' + (error as Error).message
    } finally {
      this.isRefreshing = false
    }
  }
  
  async copyLogsToClipboard(): Promise<void> {
    if (!this.hasLogs) {
      this.errorMessage = 'No logs to copy'
      return
    }
    
    this.isCopying = true
    this.clearMessages()
    
    try {
      const logsText = this.formatLogsForCopy()
      
      if (Capacitor.isNativePlatform()) {
        // Use Capacitor Clipboard plugin if available
        if (window.Capacitor && window.Capacitor.Plugins && window.Capacitor.Plugins.Clipboard) {
          await window.Capacitor.Plugins.Clipboard.write({
            string: logsText
          })
        } else {
          // Fallback to web clipboard API
          await navigator.clipboard.writeText(logsText)
        }
      } else {
        // Web clipboard API
        await navigator.clipboard.writeText(logsText)
      }
      
      this.successMessage = `Copied ${this.logs.length} log entries to clipboard`
      
      // Auto-hide success message
      setTimeout(() => {
        this.successMessage = ''
      }, 3000)
      
    } catch (error) {
      console.error('❌ Failed to copy logs:', error)
      this.errorMessage = 'Failed to copy logs: ' + (error as Error).message
    } finally {
      this.isCopying = false
    }
  }
  
  clearLogs(): void {
    this.logs = []
    this.lastUpdated = ''
    this.clearMessages()
    this.successMessage = 'Logs cleared'
    
    // Auto-hide success message
    setTimeout(() => {
      this.successMessage = ''
    }, 2000)
  }
  
  private clearMessages(): void {
    this.successMessage = ''
    this.errorMessage = ''
  }
  
  private async simulateLogFetch(): Promise<void> {
    // Simulate network delay
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // Generate sample logs based on the terminal output you showed
    this.logs = this.generateSampleLogs()
    this.lastUpdated = new Date().toLocaleString()
    this.successMessage = `Loaded ${this.logs.length} log entries`
    
    // Auto-hide success message
    setTimeout(() => {
      this.successMessage = ''
    }, 3000)
  }
  
  private generateSampleLogs(): LogEntry[] {
    const now = new Date()
    return [
      {
        timestamp: new Date(now.getTime() - 1000).toISOString(),
        level: 'D',
        tag: 'DailyNotificationReceiver',
        message: 'DN|RECEIVE_START action=com.timesafari.daily.NOTIFICATION'
      },
      {
        timestamp: new Date(now.getTime() - 900).toISOString(),
        level: 'D',
        tag: 'DailyNotificationReceiver',
        message: 'DN|WORK_ENQUEUE display=3bc1b920-9407-4ccf-94c0-26f99ba4c39d'
      },
      {
        timestamp: new Date(now.getTime() - 800).toISOString(),
        level: 'D',
        tag: 'DailyNotificationWorker',
        message: 'DN|WORK_START id=3bc1b920-9407-4ccf-94c0-26f99ba4c39d action=display'
      },
      {
        timestamp: new Date(now.getTime() - 700).toISOString(),
        level: 'D',
        tag: 'DailyNotificationWorker',
        message: 'DN|DISPLAY_START id=3bc1b920-9407-4ccf-94c0-26f99ba4c39d'
      },
      {
        timestamp: new Date(now.getTime() - 600).toISOString(),
        level: 'D',
        tag: 'DailyNotificationStorage',
        message: 'Loading notifications from storage: [53 notifications]'
      },
      {
        timestamp: new Date(now.getTime() - 500).toISOString(),
        level: 'D',
        tag: 'DailyNotificationWorker',
        message: 'DN|JIT_FRESH skip=true ageMin=0 id=3bc1b920-9407-4ccf-94c0-26f99ba4c39d'
      },
      {
        timestamp: new Date(now.getTime() - 400).toISOString(),
        level: 'D',
        tag: 'DailyNotificationWorker',
        message: 'DN|CLICK_INTENT app_only'
      },
      {
        timestamp: new Date(now.getTime() - 300).toISOString(),
        level: 'D',
        tag: 'DailyNotificationWorker',
        message: 'DN|ACTION_BUTTONS dismiss_only'
      },
      {
        timestamp: new Date(now.getTime() - 200).toISOString(),
        level: 'I',
        tag: 'DailyNotificationWorker',
        message: 'DN|DISPLAY_NOTIF_OK id=3bc1b920-9407-4ccf-94c0-26f99ba4c39d'
      },
      {
        timestamp: new Date(now.getTime() - 100).toISOString(),
        level: 'D',
        tag: 'DailyNotificationWorker',
        message: 'DN|RESCHEDULE_START id=3bc1b920-9407-4ccf-94c0-26f99ba4c39d'
      }
    ]
  }
  
  private generateMockLogs(): LogEntry[] {
    const now = new Date()
    return [
      {
        timestamp: new Date(now.getTime() - 2000).toISOString(),
        level: 'I',
        tag: 'VueApp',
        message: 'App initialized successfully'
      },
      {
        timestamp: new Date(now.getTime() - 1500).toISOString(),
        level: 'D',
        tag: 'Capacitor',
        message: 'Running in web mode - DailyNotification plugin not available'
      },
      {
        timestamp: new Date(now.getTime() - 1000).toISOString(),
        level: 'W',
        tag: 'NotificationsStore',
        message: 'DailyNotification plugin not loaded'
      }
    ]
  }
  
  private formatLogsForCopy(): string {
    const header = `DailyNotification Plugin Logs\nGenerated: ${new Date().toLocaleString()}\nTotal Entries: ${this.logs.length}\n\n`
    
    const logLines = this.logs.map(log => 
      `${log.timestamp} ${log.level}/${log.tag}: ${log.message}`
    ).join('\n')
    
    return header + logLines
  }
  
  private formatTimestamp(timestamp: string): string {
    const date = new Date(timestamp)
    return date.toLocaleTimeString()
  }
  
  private getLogLevelClass(log: LogEntry): string {
    switch (log.level) {
      case 'E': return 'log-error'
      case 'W': return 'log-warning'
      case 'I': return 'log-info'
      case 'D': return 'log-debug'
      case 'V': return 'log-verbose'
      default: return 'log-default'
    }
  }
  
  async mounted(): Promise<void> {
    // Auto-refresh logs on mount
    await this.refreshLogs()
  }
}
</script>

<style scoped>
.logs-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.view-header {
  text-align: center;
  margin-bottom: 32px;
}

.page-title {
  font-size: 2rem;
  font-weight: 700;
  color: white;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.page-subtitle {
  font-size: 1.1rem;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  font-weight: 300;
}

.logs-controls {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.control-button {
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  gap: 8px;
}

.control-button:hover:not(:disabled) {
  background: linear-gradient(135deg, #1976d2, #1565c0);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(33, 150, 243, 0.3);
}

.control-button:disabled {
  background: rgba(255, 255, 255, 0.2);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.refresh-button {
  background: linear-gradient(135deg, #4caf50, #45a049);
}

.refresh-button:hover:not(:disabled) {
  background: linear-gradient(135deg, #45a049, #3d8b40);
  box-shadow: 0 8px 25px rgba(76, 175, 80, 0.3);
}

.copy-button {
  background: linear-gradient(135deg, #ff9800, #f57c00);
}

.copy-button:hover:not(:disabled) {
  background: linear-gradient(135deg, #f57c00, #ef6c00);
  box-shadow: 0 8px 25px rgba(255, 152, 0, 0.3);
}

.clear-button {
  background: linear-gradient(135deg, #f44336, #d32f2f);
}

.clear-button:hover:not(:disabled) {
  background: linear-gradient(135deg, #d32f2f, #c62828);
  box-shadow: 0 8px 25px rgba(244, 67, 54, 0.3);
}

.logs-container {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
}

.logs-content {
  padding: 20px;
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.logs-count {
  font-weight: 600;
  color: white;
  font-size: 0.9rem;
}

.logs-timestamp {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.8rem;
}

.logs-list {
  max-height: 500px;
  overflow-y: auto;
  font-family: 'Courier New', monospace;
  font-size: 0.85rem;
  line-height: 1.4;
}

.log-entry {
  display: grid;
  grid-template-columns: 80px 20px 200px 1fr;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  align-items: start;
}

.log-entry:last-child {
  border-bottom: none;
}

.log-timestamp {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.75rem;
}

.log-level {
  font-weight: bold;
  text-align: center;
  font-size: 0.8rem;
}

.log-tag {
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.log-message {
  color: rgba(255, 255, 255, 0.9);
  word-break: break-word;
}

/* Log level colors */
.log-error .log-level {
  color: #f44336;
}

.log-warning .log-level {
  color: #ff9800;
}

.log-info .log-level {
  color: #4caf50;
}

.log-debug .log-level {
  color: #2196f3;
}

.log-verbose .log-level {
  color: #9c27b0;
}

.log-default .log-level {
  color: rgba(255, 255, 255, 0.7);
}

.no-logs {
  padding: 40px 20px;
  text-align: center;
}

.empty-state {
  padding: 40px 20px;
}

.empty-icon {
  font-size: 4rem;
  display: block;
  margin-bottom: 16px;
}

.empty-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: white;
  margin: 0 0 8px 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.empty-description {
  font-size: 1rem;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  line-height: 1.5;
}

.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 8px;
  font-weight: 600;
  z-index: 1000;
  animation: slideIn 0.3s ease;
}

.success-message {
  background: linear-gradient(135deg, #4caf50, #45a049);
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.error-message {
  background: linear-gradient(135deg, #f44336, #d32f2f);
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* Responsive design */
@media (max-width: 768px) {
  .logs-view {
    padding: 16px;
  }
  
  .logs-controls {
    flex-direction: column;
  }
  
  .control-button {
    justify-content: center;
  }
  
  .log-entry {
    grid-template-columns: 1fr;
    gap: 4px;
  }
  
  .log-timestamp,
  .log-level,
  .log-tag {
    font-size: 0.75rem;
  }
  
  .logs-list {
    font-size: 0.8rem;
  }
  
  .message {
    position: relative;
    top: auto;
    right: auto;
    margin: 16px 0;
  }
}
</style>
