<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import api from '../api'

const route = useRoute()

// Data Interface
interface Log {
  id: number
  check_time: string
  snapshot_path: string
  alarm_name: string
  alarm_content: string
  area: string
}

// State
const allAlarms = ref<Log[]>([])
// Changed: latestAlarm to latestAlarms (array of 2)
const latestAlarms = computed(() => allAlarms.value.slice(0, 2))
const scrollingAlarms = ref<Log[]>([])

// Timers
let pollTimer: ReturnType<typeof setInterval> | null = null
let scrollTimer: ReturnType<typeof setInterval> | null = null

// Utils
const getImageUrl = (path: string) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  const host = import.meta.env.PROD ? window.location.origin : 'http://localhost:8000'
  return `${host}${path}`
}

// Fetch Data
const fetchAlarms = async () => {
  try {
    // Increased limit to ensure we have enough for 2 static + scrolling
    const res = await api.get('/logs', { params: { only_alarm: true, limit: 15 } })
    const newData = res.data as Log[]
    
    if (newData.length > 0) {
        allAlarms.value = newData
        
        // Initialize scrolling list if empty
        if (scrollingAlarms.value.length === 0) {
            // Take items after the first two for the scrolling list
            scrollingAlarms.value = newData.slice(2)
        } else {
            // Update strategy similar to before, but for index 2+
            const newHistory = newData.slice(2)
            const currentIds = new Set(scrollingAlarms.value.map(l => l.id))
            const newIds = newHistory.map(l => l.id)
            
            // Basic update logic
            if (newHistory.length !== scrollingAlarms.value.length || newIds.some(id => !currentIds.has(id))) {
                 scrollingAlarms.value = newHistory
            }
        }
    }
  } catch (e) {
    console.error(e)
  }
}

// Scroll Animation
const startScrolling = () => {
    // Stop existing timer
    if (scrollTimer) clearInterval(scrollTimer)
    
    scrollTimer = setInterval(() => {
        // Only scroll if we have more than 3 items (since we want to show 3)
        if (scrollingAlarms.value.length > 3) {
            const first = scrollingAlarms.value.shift()
            if (first) {
                scrollingAlarms.value.push(first)
            }
        }
    }, 3000)
}

// Fullscreen
const dashboardRef = ref<HTMLElement | null>(null)
const isFullscreen = ref(false)

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    dashboardRef.value?.requestFullscreen().catch(err => {
      console.error(`Error attempting to enable fullscreen: ${err.message}`)
    })
  } else {
    document.exitFullscreen()
  }
}

onMounted(() => {
  fetchAlarms()
  pollTimer = setInterval(fetchAlarms, 5000)
  startScrolling()
  
  // Try auto fullscreen if on big-screen route
  if (route.name === 'big-screen') {
    // Small delay to ensure rendering
    setTimeout(() => {
       if (dashboardRef.value && !document.fullscreenElement) {
           dashboardRef.value.requestFullscreen().catch(err => {
               // Expected failure in most browsers without user gesture
               console.log('Auto fullscreen blocked:', err.message)
           })
       }
    }, 500)
  }

  document.addEventListener('fullscreenchange', () => {
      isFullscreen.value = !!document.fullscreenElement
  })
})

onUnmounted(() => {
  if (pollTimer) clearInterval(pollTimer)
  if (scrollTimer) clearInterval(scrollTimer)
})
</script>

<template>
  <div class="dashboard-container" ref="dashboardRef">
    <div class="header">
        <h1>监控大屏 - 异常告警实时监控</h1>
        <button class="fs-btn" @click="toggleFullscreen">
            {{ isFullscreen ? '退出全屏' : '全屏模式' }}
        </button>
    </div>

    <div class="content-wrapper">
        <!-- Left Section: Latest 2 Alarms (3/5 width) -->
        <div class="left-panel">
            <div class="section-header">
                <span class="pulse-dot"></span> 最新告警 (实时)
            </div>
            
            <div class="latest-list" v-if="latestAlarms.length > 0">
                <div v-for="(alarm, index) in latestAlarms" :key="alarm.id" class="latest-card">
                    <div class="latest-img-wrapper">
                        <img :src="getImageUrl(alarm.snapshot_path)" alt="Latest" />
                        <div class="badge-new" v-if="index === 0">NEW</div>
                    </div>
                    <div class="latest-info">
                        <div class="info-row time">
                            <span class="label">时间:</span>
                            <span class="value">{{ new Date(alarm.check_time).toLocaleString() }}</span>
                        </div>
                        <div class="info-row area">
                            <span class="label">地点:</span>
                            <span class="value">{{ alarm.area }}</span>
                        </div>
                        <div class="info-row name">
                            <span class="label">告警名称:</span>
                            <span class="value highlight-name">{{ alarm.alarm_name }}</span>
                        </div>
                         <div class="info-row content">
                            <span class="label">告警内容:</span>
                            <span class="value highlight-content">{{ alarm.alarm_content }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else class="no-data">
                暂无异常告警
            </div>
        </div>

        <!-- Right Section: Recent Alarms Scrolling (2/5 width) -->
        <div class="right-panel">
            <div class="section-header">
                最近告警记录 ({{ scrollingAlarms.length }})
            </div>
            <div class="scroll-container">
                 <TransitionGroup name="list" tag="div" class="list-wrapper">
                    <div v-for="alarm in scrollingAlarms" :key="alarm.id" class="recent-card">
                        <div class="recent-img">
                             <img :src="getImageUrl(alarm.snapshot_path)" loading="lazy" />
                        </div>
                        <div class="recent-info">
                            <div class="r-top">
                                <span class="r-time">{{ new Date(alarm.check_time).toLocaleString() }}</span>
                            </div>
                            <div class="r-mid">
                                 <span class="r-area">{{ alarm.area }}</span>
                            </div>
                            <div class="r-bottom">
                                <span class="r-name">{{ alarm.alarm_name }}</span>
                                <span class="r-content">{{ alarm.alarm_content }}</span>
                            </div>
                        </div>
                    </div>
                 </TransitionGroup>
            </div>
        </div>
    </div>
  </div>
</template>

<style scoped>
/* Reset & Base */
.dashboard-container {
    background-color: #0f172a;
    color: #f8fafc;
    height: 100vh;
    width: 100vw;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
    flex: 0 0 70px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30px;
    background: #1e293b;
    border-bottom: 1px solid #334155;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    z-index: 10;
}

.header h1 {
    font-size: 2.2rem;
    margin: 0;
    color: #ef4444;
    text-transform: uppercase;
    letter-spacing: 2px;
    text-shadow: 0 0 10px rgba(239, 68, 68, 0.3);
}

.fs-btn {
    background: rgba(255, 255, 255, 0.1);
    color: white;
    border: 1px solid #475569;
    padding: 10px 25px;
    cursor: pointer;
    font-size: 1.1rem;
    border-radius: 6px;
    transition: all 0.3s;
}
.fs-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: row; /* Changed to row */
    padding: 20px;
    gap: 20px;
    height: calc(100vh - 70px);
    overflow: hidden;
}

/* Common Section Styles */
.section-header {
    font-size: 1.5rem;
    color: #cbd5e1;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 0 0 auto;
}

.pulse-dot {
    width: 12px;
    height: 12px;
    background-color: #ef4444;
    border-radius: 50%;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); }
    70% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); }
    100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
}

/* Left Panel (Latest) */
.left-panel {
    flex: 3; /* 3/5 width */
    display: flex;
    flex-direction: column;
    min-width: 0;
}

.latest-list {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
    min-height: 0;
}

.latest-card {
    flex: 1;
    background: #1e293b;
    border: 3px solid #ef4444;
    border-radius: 12px;
    display: flex;
    padding: 20px;
    gap: 30px;
    box-shadow: 0 0 20px rgba(239, 68, 68, 0.15);
    overflow: hidden;
    position: relative;
}

.latest-img-wrapper {
    flex: 0 0 40%;
    border-radius: 8px;
    overflow: hidden;
    position: relative;
    border: 1px solid #334155;
}

.latest-img-wrapper img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.badge-new {
    position: absolute;
    top: 10px;
    left: 10px;
    background: #ef4444;
    color: white;
    padding: 5px 10px;
    border-radius: 4px;
    font-weight: bold;
    box-shadow: 0 2px 5px rgba(0,0,0,0.3);
    animation: blink 2s infinite;
}

@keyframes blink {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.6; }
}

.latest-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 15px;
}

/* Adjusted font sizes for fitting two cards */
.info-row {
    font-size: 1.4rem;
    display: flex;
    align-items: flex-start;
    line-height: 1.3;
}

.info-row .label {
    color: #94a3b8;
    min-width: 140px;
    font-weight: 500;
}

.info-row .value {
    color: #f1f5f9;
    font-weight: 600;
}

.highlight-name {
    color: #fca5a5;
    font-size: 1.6rem;
}

.highlight-content {
    color: #ef4444;
    font-size: 1.8rem;
    font-weight: 800;
}

/* Right Panel (Recent) */
.right-panel {
    flex: 2; /* 2/5 width */
    display: flex;
    flex-direction: column;
    min-width: 0;
    border-left: 1px solid #334155;
    padding-left: 20px;
}

.scroll-container {
    flex: 1;
    overflow: hidden;
    position: relative;
    background: transparent;
    border-radius: 12px;
    /* Mask for fade out effect at bottom */
    mask-image: linear-gradient(to bottom, black 85%, transparent 100%);
    -webkit-mask-image: linear-gradient(to bottom, black 85%, transparent 100%);
}

.list-wrapper {
    display: grid;
    grid-template-columns: 1fr;
    gap: 15px;
    padding-bottom: 20px;
}

.recent-card {
    background: #1e293b;
    border-left: 5px solid #ef4444;
    border-radius: 8px;
    padding: 12px;
    display: flex;
    gap: 15px;
    /* Height calculation to fit 3 items:
       Total height available approx (100vh - 70px - 20px padding - 40px header) / 3 
       Let's use a percentage or flex basis but fixed pixel is safer for layout stability */
    height: 140px; 
    align-items: center;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.recent-img {
    flex: 0 0 160px;
    height: 100%;
    border-radius: 6px;
    overflow: hidden;
}

.recent-img img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.recent-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
    padding: 5px 0;
}

.r-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.r-time {
    font-size: 1.1rem;
    color: #94a3b8;
}

.r-mid {
    margin: 5px 0;
}

.r-area {
    font-size: 1.2rem;
    font-weight: bold;
    color: #e2e8f0;
    background: #334155;
    padding: 2px 8px;
    border-radius: 4px;
    display: inline-block;
}

.r-bottom {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.r-name {
    font-size: 1.2rem;
    color: #fca5a5;
    font-weight: 600;
}

.r-content {
    font-size: 1.3rem;
    color: white;
    font-weight: 700;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* Animations */
.list-move,
.list-enter-active,
.list-leave-active {
  transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.list-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

.list-leave-to {
  opacity: 0;
  transform: translateY(-30px);
}

.list-leave-active {
  position: absolute;
  width: 100%;
}

.no-data {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 2.5rem;
    color: #475569;
    background: #1e293b;
    border-radius: 12px;
}
</style>