<template>
  <div class="shopfloor-dashboard">
    <header class="dashboard-header">
      <div class="logo-container">
        <img src="/ge-aerospace-logo.svg" alt="GE Aerospace" class="logo" />
      </div>

      <div class="header-center">
        <div class="location-title">West Jefferson</div>
        <h1>Shopfloor Dashboard</h1>
      </div>

      <div class="header-right">
        <div class="clock">{{ currentTime }}</div>
        <select v-model="businessUnit" class="filter-select" @change="loadData">
          <option value="">All Business Units</option>
          <option v-for="bu in businessUnits" :key="bu.businessunitid" :value="bu.businessunitid">
            {{ bu.businessunit }}
          </option>
        </select>
      </div>
    </header>

    <main class="dashboard-content">
      <!-- Recognition Carousel -->
      <section v-if="recognitions.length" class="recognition-section">
        <div class="section-title recognition">Employee Recognition</div>
        <div class="recognition-carousel">
          <div
            v-for="(rec, idx) in recognitions"
            :key="`${rec.notificationid}-${rec.employeesso}`"
            class="recognition-card"
            :class="{ active: idx === currentRecognition }"
          >
            <div class="recognition-photo-container">
              <img
                v-if="rec.employeepicture"
                :src="`/static/employees/${rec.employeepicture}`"
                :alt="rec.employeename"
                class="recognition-photo"
                @error="handlePhotoError"
              />
              <img
                v-else
                src="/ge-aerospace-logo.svg"
                alt="GE Aerospace"
                class="recognition-photo ge-logo-fallback"
              />
            </div>
            <div class="recognition-content">
              <div class="recognition-header">
                <span class="recognition-star">&#9733;</span>
                <div class="recognition-name">{{ rec.employeename }}</div>
              </div>
              <div class="recognition-message">{{ rec.notification }}</div>
            </div>
          </div>
        </div>
      </section>

      <!-- Current Notifications -->
      <section v-if="currentNotifications.length" class="notifications-section">
        <div class="section-title" :class="getSectionClass(currentNotifications)">
          Current Notifications
        </div>
        <div class="events-list">
          <div
            v-for="n in currentNotifications"
            :key="n.notificationid"
            class="event-card"
            :class="{ resolved: n.resolved }"
          >
            <div class="event-indicator" :style="{ backgroundColor: getTypeColor(n.typecolor) }"></div>
            <div class="event-content">
              <div class="event-title">{{ n.notification }}</div>
              <div class="event-time">
                <template v-if="n.resolved">
                  <strong>RESOLVED</strong>
                </template>
                <template v-else>
                  <strong>{{ formatTime(n.starttime) }}</strong>
                  <span v-if="n.endtime"> - {{ formatTime(n.endtime) }}</span>
                </template>
              </div>
            </div>
            <a v-if="n.ticketnumber" :href="getTicketUrl(n.ticketnumber)" target="_blank" class="event-ticket">
              {{ n.ticketnumber }}
            </a>
          </div>
        </div>
      </section>

      <!-- Upcoming Notifications -->
      <section v-if="upcomingNotifications.length" class="notifications-section">
        <div class="section-title upcoming">Upcoming</div>
        <div class="events-list">
          <div
            v-for="n in upcomingNotifications"
            :key="n.notificationid"
            class="event-card"
          >
            <div class="event-indicator" :style="{ backgroundColor: getTypeColor(n.typecolor) }"></div>
            <div class="event-content">
              <div class="event-title">{{ n.notification }}</div>
              <div class="event-time">
                <strong>{{ formatDateTime(n.starttime) }}</strong>
              </div>
            </div>
            <a v-if="n.ticketnumber" :href="getTicketUrl(n.ticketnumber)" target="_blank" class="event-ticket">
              {{ n.ticketnumber }}
            </a>
          </div>
        </div>
      </section>

      <!-- No notifications -->
      <div v-if="!loading && !currentNotifications.length && !upcomingNotifications.length && !recognitions.length" class="no-events">
        No active notifications
      </div>

      <div v-if="loading" class="loading">Loading...</div>
    </main>

    <footer class="dashboard-footer">
      Auto-refreshes every 30 seconds
    </footer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { notificationsApi, businessUnitsApi } from '@/api'

const loading = ref(true)
const businessUnit = ref('')
const businessUnits = ref([])
const notifications = ref({ current: [], upcoming: [] })
const currentRecognition = ref(0)

let refreshInterval = null
let recognitionInterval = null

// Separate recognition notifications from others
const recognitions = computed(() =>
  notifications.value.current.filter(n => n.typecolor === 'recognition')
)

const currentNotifications = computed(() =>
  notifications.value.current.filter(n => n.typecolor !== 'recognition')
)

const upcomingNotifications = computed(() =>
  notifications.value.upcoming.filter(n => n.typecolor !== 'recognition')
)

// Clock
const currentTime = ref('')
function updateClock() {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('en-US', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

onMounted(async () => {
  updateClock()
  setInterval(updateClock, 1000)

  // Load business units
  try {
    const response = await businessUnitsApi.list()
    businessUnits.value = response.data.data || []
  } catch (err) {
    console.error('Error loading business units:', err)
  }

  await loadData()

  // Auto-refresh every 30 seconds
  refreshInterval = setInterval(loadData, 30000)

  // Rotate recognition carousel every 8 seconds
  recognitionInterval = setInterval(() => {
    if (recognitions.value.length > 1) {
      currentRecognition.value = (currentRecognition.value + 1) % recognitions.value.length
    }
  }, 8000)
})

onUnmounted(() => {
  if (refreshInterval) clearInterval(refreshInterval)
  if (recognitionInterval) clearInterval(recognitionInterval)
})

async function loadData() {
  try {
    const params = {}
    if (businessUnit.value) {
      params.businessunit = businessUnit.value
    }
    const response = await notificationsApi.getShopfloor(params)
    notifications.value = response.data.data || { current: [], upcoming: [] }
  } catch (err) {
    console.error('Error loading shopfloor data:', err)
  } finally {
    loading.value = false
  }
}

function getTypeColor(typecolor) {
  const colors = {
    success: '#04b962',
    warning: '#ff8800',
    danger: '#f5365c',
    info: '#14abef',
    primary: '#7934f3',
    recognition: '#0d6efd'
  }
  return colors[typecolor] || typecolor || '#14abef'
}

function getSectionClass(notifications) {
  // Use danger color if any active incidents
  const hasIncident = notifications.some(n => n.typecolor === 'danger' && !n.resolved)
  return hasIncident ? 'danger' : ''
}

function formatTime(dateStr) {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleTimeString('en-US', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

function formatDateTime(dateStr) {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('en-US', {
    weekday: 'short',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

function getTicketUrl(ticketnumber) {
  if (!ticketnumber) return '#'
  // ServiceNow ticket URLs
  if (ticketnumber.startsWith('GEINC')) {
    return `https://ge.service-now.com/nav_to.do?uri=incident.do?sysparm_query=number=${ticketnumber}`
  }
  if (ticketnumber.startsWith('GECHG')) {
    return `https://ge.service-now.com/nav_to.do?uri=change_request.do?sysparm_query=number=${ticketnumber}`
  }
  return '#'
}

function handlePhotoError(e) {
  e.target.src = '/ge-aerospace-logo.svg'
  e.target.classList.add('ge-logo-fallback')
}
</script>

<style scoped>
.shopfloor-dashboard {
  min-height: 100vh;
  background: #00003d;
  color: #fff;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  overflow: hidden;
}

.dashboard-header {
  display: grid;
  grid-template-columns: auto 1fr auto;
  align-items: center;
  gap: 30px;
  padding: 20px 40px;
  border-bottom: 3px solid #4181ff;
}

.logo {
  height: 90px;
  width: auto;
}

.header-center {
  text-align: center;
}

.location-title {
  font-size: 18px;
  font-weight: 600;
  color: #888;
  text-transform: uppercase;
  letter-spacing: 2px;
}

.header-center h1 {
  font-size: 28px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 2px;
  margin: 0;
}

.header-right {
  text-align: right;
}

.clock {
  font-size: 28px;
  font-weight: 600;
  color: #4181ff;
  font-variant-numeric: tabular-nums;
  margin-bottom: 10px;
}

.filter-select {
  padding: 10px 16px;
  font-size: 16px;
  font-weight: 600;
  background: #1a1a5e;
  color: #fff;
  border: 2px solid #4181ff;
  border-radius: 6px;
  cursor: pointer;
  min-width: 200px;
}

.dashboard-content {
  padding: 20px 40px;
  max-height: calc(100vh - 180px);
  overflow-y: auto;
}

.section-title {
  font-size: 22px;
  font-weight: 700;
  padding: 12px 20px;
  border-radius: 8px;
  text-transform: uppercase;
  letter-spacing: 2px;
  margin-bottom: 15px;
  background: #4181ff;
}

.section-title.recognition {
  background: #0d6efd;
}

.section-title.danger {
  background: #f5365c;
}

.section-title.upcoming {
  background: #6c757d;
}

/* Recognition carousel */
.recognition-section {
  margin-bottom: 25px;
}

.recognition-carousel {
  position: relative;
  min-height: 170px;
}

.recognition-card {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  background: linear-gradient(135deg, #1e3a5f 0%, #0d2137 100%);
  border: 3px solid #0d6efd;
  border-radius: 12px;
  padding: 20px 25px;
  display: flex;
  align-items: center;
  gap: 25px;
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 0.8s ease, transform 0.8s ease;
}

.recognition-card.active {
  opacity: 1;
  transform: translateY(0);
  position: relative;
}

.recognition-photo {
  width: 140px;
  height: 140px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #0d6efd;
  background: #1a1a2e;
}

.recognition-photo.ge-logo-fallback {
  object-fit: contain;
  padding: 20px;
  background: #fff;
}

.recognition-content {
  flex: 1;
}

.recognition-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.recognition-star {
  font-size: 48px;
  color: #ffc107;
  margin-right: 20px;
  animation: starPulse 2s ease-in-out infinite;
}

@keyframes starPulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.recognition-name {
  font-size: 36px;
  font-weight: 700;
}

.recognition-message {
  font-size: 24px;
  color: #ccc;
  line-height: 1.4;
}

/* Event cards */
.notifications-section {
  margin-bottom: 25px;
}

.events-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.event-card {
  display: flex;
  align-items: center;
  background: #fff;
  color: #00003d;
  border-radius: 8px;
  padding: 15px 20px;
  gap: 15px;
}

.event-card.resolved {
  opacity: 0.6;
  background: #e9ecef;
}

.event-indicator {
  width: 8px;
  height: 60px;
  border-radius: 4px;
  flex-shrink: 0;
}

.event-content {
  flex: 1;
}

.event-title {
  font-size: 24px;
  font-weight: 700;
  line-height: 1.3;
}

.event-time {
  font-size: 18px;
  color: #666;
  margin-top: 5px;
}

.event-time strong {
  color: #00003d;
}

.event-ticket {
  font-size: 18px;
  font-weight: 700;
  background: #00003d;
  color: #fff;
  padding: 8px 16px;
  border-radius: 6px;
  text-decoration: none;
  text-transform: uppercase;
}

.event-ticket:hover {
  background: #4181ff;
}

.no-events, .loading {
  text-align: center;
  font-size: 28px;
  font-weight: 600;
  padding: 40px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.dashboard-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.8);
  text-align: center;
  padding: 12px;
  font-size: 16px;
}
</style>
