<template>
  <div class="shopfloor-dashboard">
    <header class="dashboard-header">
      <div class="logo-container">
        <img :src="siteLogo" alt="Site logo" class="logo" />
      </div>

      <div class="header-center">
        <div class="location-title">{{ facilityName }}</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">
      <!-- Banner - single prominent full-width message -->
      <section v-if="banners.length" class="banner-section">
        <div
          v-for="n in banners"
          :key="n.notificationid"
          class="banner-strip"
          :style="{ backgroundColor: getTypeColor(n.typecolor) }"
        >
          {{ n.notification }}
        </div>
      </section>

      <!-- 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="rec.employeepicture"
                :alt="rec.employeename"
                class="recognition-photo"
                @error="handlePhotoError"
              />
              <img
                v-else
                :src="siteLogo"
                alt="Site logo"
                class="recognition-photo ge-logo-fallback"
              />
            </div>
            <div class="recognition-content">
              <div class="recognition-header">
                <div class="recognition-name">{{ rec.employeename }}</div>
              </div>
              <div class="recognition-message">{{ rec.notification }}</div>
            </div>
          </div>
        </div>
      </section>

      <!-- Recertification grid - everyone due shown at once, so nobody has to
           wait for a carousel to rotate to their name -->
      <section v-if="recertifications.length" class="recert-section">
        <div class="section-title recert-title">
          <span>Recertification Required ({{ recertifications.length }})</span>
          <span v-if="recertRangeLabel" class="recert-range">{{ recertRangeLabel }}</span>
        </div>
        <div
          v-for="msg in recertDescriptions"
          :key="msg"
          class="recert-description"
        >
          {{ msg }}
        </div>
        <div class="recert-row">
          <div
            v-for="rec in recertPage"
            :key="`recert-${rec.notificationid}-${rec.employeesso}`"
            class="recert-tile"
          >
            <img
              v-if="rec.employeepicture"
              :src="rec.employeepicture"
              :alt="rec.employeename"
              class="recert-photo"
              @error="handlePhotoError"
            />
            <img
              v-else
              :src="siteLogo"
              alt="Site logo"
              class="recert-photo ge-logo-fallback"
            />
            <div class="recert-name">{{ rec.employeename || rec.employeesso }}</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>
            <template v-if="n.ticketnumber">
              <a v-if="getTicketUrl(n.ticketnumber)" :href="getTicketUrl(n.ticketnumber)" target="_blank" class="event-ticket">
                {{ n.ticketnumber }}
              </a>
              <span v-else class="event-ticket">{{ n.ticketnumber }}</span>
            </template>
          </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>
            <template v-if="n.ticketnumber">
              <a v-if="getTicketUrl(n.ticketnumber)" :href="getTicketUrl(n.ticketnumber)" target="_blank" class="event-ticket">
                {{ n.ticketnumber }}
              </a>
              <span v-else class="event-ticket">{{ n.ticketnumber }}</span>
            </template>
          </div>
        </div>
      </section>

      <!-- No notifications -->
      <div v-if="!loading && !currentNotifications.length && !upcomingNotifications.length && !recognitions.length && !recertifications.length && !banners.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, dashboardDefaultsApi } from '@/api'
import { getFacilityName, getSiteLogo, getServicenowUrls } from '@/utils/siteSettings'

const loading = ref(true)
const facilityName = ref('ShopDB')
const siteLogo = ref('/ge-aerospace-logo.svg')
// ServiceNow ticket-link config; loaded on mount. Empty/disabled = plain text.
const servicenowConfig = ref({ enabled: true, incidentUrl: '', changeUrl: '' })
const businessUnit = ref('')
const businessUnits = ref([])
const notifications = ref({ current: [], upcoming: [] })
const currentRecognition = ref(0)
// Layout-config fingerprint from the feed; when it changes the kiosk reloads.
const loadedConfigVersion = ref(null)

let refreshInterval = null
let recognitionInterval = null
let recertPageInterval = null

// The board groups cards by each type's configured display style, so any custom
// type set to carousel/grid/banner renders that way - not just the built-ins.
const SPECIAL_STYLES = ['carousel', 'grid', 'banner']

const recognitions = computed(() =>
  notifications.value.current.filter(n => n.displaystyle === 'carousel')
)

const recertifications = computed(() =>
  notifications.value.current.filter(n => n.displaystyle === 'grid')
)

const banners = computed(() =>
  notifications.value.current.filter(n => n.displaystyle === 'banner')
)

// Distinct training descriptions shown once above the grid (the per-person
// tiles only carry photo + name).
const recertDescriptions = computed(() => {
  const seen = new Set()
  const out = []
  for (const r of recertifications.value) {
    const msg = (r.notification || '').trim()
    if (msg && !seen.has(msg)) { seen.add(msg); out.push(msg) }
  }
  return out
})

// Recertification shows as a single rotating row: one page of tiles at a time
// so it stays compact on any screen, cycling through everyone due.
const RECERT_PAGE_SIZE = 8
const currentRecertPage = ref(0)
const recertPageCount = computed(() =>
  Math.max(1, Math.ceil(recertifications.value.length / RECERT_PAGE_SIZE))
)
const recertPage = computed(() => {
  const page = currentRecertPage.value % recertPageCount.value
  const start = page * RECERT_PAGE_SIZE
  return recertifications.value.slice(start, start + RECERT_PAGE_SIZE)
})
const recertRangeLabel = computed(() => {
  if (recertPageCount.value <= 1) return ''
  const page = currentRecertPage.value % recertPageCount.value
  const start = page * RECERT_PAGE_SIZE
  const end = Math.min(start + RECERT_PAGE_SIZE, recertifications.value.length)
  return `${start + 1}-${end} of ${recertifications.value.length}`
})

const currentNotifications = computed(() =>
  notifications.value.current.filter(n => !SPECIAL_STYLES.includes(n.displaystyle))
)

const upcomingNotifications = computed(() =>
  notifications.value.upcoming.filter(n => !SPECIAL_STYLES.includes(n.displaystyle))
)

// 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)

  getFacilityName().then(name => { facilityName.value = name })
  getSiteLogo().then(logo => { siteLogo.value = logo })
  getServicenowUrls().then(config => { servicenowConfig.value = config })

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

  // Auto-select this kiosk's business unit from its IP (visitor location),
  // unless one was already chosen. Falls back to "all" when the IP is unmapped.
  if (!businessUnit.value) {
    try {
      const response = await dashboardDefaultsApi.visitorLocation()
      if (response.data.data?.businessunitid) {
        businessUnit.value = response.data.data.businessunitid
      }
    } catch (err) {
      console.error('Error resolving visitor location:', 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)

  // Cycle the recertification row through pages of employees every 7 seconds.
  recertPageInterval = setInterval(() => {
    if (recertPageCount.value > 1) {
      currentRecertPage.value = (currentRecertPage.value + 1) % recertPageCount.value
    }
  }, 7000)
})

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

async function loadData() {
  try {
    const params = {}
    if (businessUnit.value) {
      params.businessunit = businessUnit.value
    }
    const response = await notificationsApi.getShopfloor(params)
    const data = response.data.data || { current: [], upcoming: [] }

    // Reload the kiosk when the board's layout config changes, so type/style
    // edits (and deploys, via SHOPFLOOR_BUILD) reach already-open pages without
    // anyone touching the machine.
    const version = data.configversion
    if (version) {
      if (loadedConfigVersion.value && loadedConfigVersion.value !== version) {
        window.location.reload()
        return
      }
      loadedConfigVersion.value = version
    }

    notifications.value = { current: data.current || [], upcoming: data.upcoming || [] }
  } catch (err) {
    console.error('Error loading shopfloor data:', err)
  } finally {
    loading.value = false
  }
}

function getTypeColor(typecolor) {
  // Types store a hex color, used directly. Only legacy Bootstrap color names
  // still need aliasing; anything else (a hex) passes straight through.
  const aliases = {
    success: '#04b962',
    warning: '#ff8800',
    danger: '#f5365c',
    info: '#14abef',
    primary: '#7934f3',
    secondary: '#94614f'
  }
  return aliases[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) {
  // Return a URL only when ServiceNow is enabled and a matching template is set.
  // Null means "render the ticket number as plain text, no link".
  if (!ticketnumber) return null
  const config = servicenowConfig.value
  if (!config.enabled) return null
  if (ticketnumber.startsWith('GEINC') && config.incidentUrl) {
    return config.incidentUrl.replace('{ticket}', ticketnumber)
  }
  if (ticketnumber.startsWith('GECHG') && config.changeUrl) {
    return config.changeUrl.replace('{ticket}', ticketnumber)
  }
  return null
}

function handlePhotoError(e) {
  e.target.src = siteLogo.value
  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: #ffc107;
  color: #3a2e00;
}

/* Recertification grid - blue, compact tiles so 20-30 people are all visible
   at once (no carousel to wait through) */
.recert-section {
  margin-bottom: 25px;
}
.section-title.recert-title {
  background: #0d6efd;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.recert-range {
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 1px;
  opacity: 0.85;
}
.recert-description {
  font-size: 22px;
  font-weight: 600;
  color: #cbd5e1;
  margin: -4px 0 14px;
  line-height: 1.35;
}
/* Single row that cycles through pages of employees */
.recert-row {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 14px;
}
.recert-tile {
  background: linear-gradient(135deg, #1e3a5f 0%, #0d2137 100%);
  border: 2px solid #0d6efd;
  border-radius: 10px;
  padding: 14px 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  text-align: center;
}
.recert-photo {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #0d6efd;
  background: #1a1a2e;
}
.recert-photo.ge-logo-fallback {
  object-fit: contain;
  padding: 12px;
  background: #fff;
}
.recert-name {
  font-size: 20px;
  font-weight: 700;
  line-height: 1.15;
}

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

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

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

.banner-strip {
  padding: 22px 30px;
  border-radius: 10px;
  margin-bottom: 12px;
  color: #fff;
  font-size: 2rem;
  font-weight: 700;
  text-align: center;
  text-wrap: balance;
  box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35);
}

.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, #4a3a0a 0%, #2a2200 100%);
  border: 3px solid #ffc107;
  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 #ffc107;
  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>
