<!-- pages/Anjungan/AntreanMasuk/[id].vue -->
<template>
  <div class="antrian-display-container">
    <!-- Header -->
    <div class="display-header">
      <div class="header-left">
        <div class="logo-circle">
          <img 
            src="/RSSA logo 1.png" 
            alt="RSUD Logo" 
            class="header-logo"
            width="64"
            height="64"
            style="width: 64px; height: 64px; object-fit: contain;"
          />
        </div>
        <div class="header-text">
          <h1 class="hospital-name">RSUD dr. Saiful Anwar Provinsi Jawa Timur</h1>
          <!-- <p class="display-subtitle">RSUD dr. Saiful Anwar Provinsi Jawa Timur</p> -->
        </div>
      </div>
      <div class="header-right">
        <div class="datetime-display">
          <div class="time-large">{{ currentTime }}</div>
          <div class="date-small">{{ currentDate }}</div>
        </div>
      </div>
    </div>

    <!-- Main Grid - Display Loket Cards -->
    <div class="loket-grid-container">
      <!-- Loket Grid -->
      <div class="lokets-grid" :style="gridStyle">
        <div
          v-for="loketData in displayedLokets"
          :key="loketData.id"
          class="loket-card"
        >
          <!-- Loket Header -->
          <div class="loket-header-bar">
            <div class="loket-header-content">
              <span class="loket-name">{{ loketData.nama }}</span>
              <v-chip 
                size="default" 
                class="ml-2 loket-header-chip" 
                color="primary-700"
              >
                <v-icon start size="20" color="white">mdi-account-multiple</v-icon>
                {{ loketData.totalQueues }}
              </v-chip>
            </div>
          </div>

          <!-- Queue Display - CSS Animated Scroll -->
          <div 
            class="queue-display"
            :ref="el => setQueueDisplayRef(el, loketData.id)"
          >
            <!-- Ticket Cards List - CSS Animation -->
            <div v-if="loketData.queues.length > 0" class="ticket-cards-wrapper">
              <div 
                class="ticket-cards-scroll"
                :class="{ 'animate-scroll': loketScrollStatus[loketData.id] }"
                :ref="el => setQueueScrollRef(el, loketData.id)"
              >
                <!-- Original Content -->
                <div 
                  class="ticket-cards-grid"
                  :style="ticketGridStyle"
                >
                  <div
                    v-for="(queue, index) in loketData.queues"
                    :key="`${loketData.id}-${queue.no}-${queue.barcode || index}`"
                    class="ticket-card"
                    :class="{ 'ticket-card-fast-track': queue.fastTrack === 'YA' }"
                  >
                    <!-- Fast Track Badge - Pojok Kanan Atas -->
                    <div v-if="queue.fastTrack === 'YA'" class="ticket-fast-track">
                      <v-icon color="white" size="14">mdi-flash</v-icon>
                    </div>
                    <div class="ticket-number">{{ queue.noAntrian?.split(" |")[0] || queue.no || '' }}</div>
                  </div>
                </div>
                <!-- Duplicated Content for Seamless Loop -->
                <div 
                  v-if="loketScrollStatus[loketData.id]"
                  class="ticket-cards-grid"
                  :style="ticketGridStyle"
                  aria-hidden="true"
                >
                  <div
                    v-for="(queue, index) in loketData.queues"
                    :key="`${loketData.id}-dup-${queue.no}-${queue.barcode || index}`"
                    class="ticket-card"
                    :class="{ 'ticket-card-fast-track': queue.fastTrack === 'YA' }"
                  >
                    <!-- Fast Track Badge - Pojok Kanan Atas -->
                    <div v-if="queue.fastTrack === 'YA'" class="ticket-fast-track">
                      <v-icon color="white" size="14">mdi-flash</v-icon>
                    </div>
                    <div class="ticket-number">{{ queue.noAntrian?.split(" |")[0] || queue.no || '' }}</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Empty State -->
            <div
              v-else
              class="empty-queue"
            >
              <v-icon size="64" color="grey-lighten-2" class="empty-icon">mdi-ticket-outline</v-icon>
              <div class="empty-text">Tidak Ada Antrian</div>
              <div class="empty-subtext">Antrian akan muncul di sini</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Footer Stats -->
    <div class="footer-stats-bar">
      <div class="stat-item">
        <div class="stat-icon stat-icon-total">
          <v-icon size="32" color="primary-600">mdi-format-list-numbered</v-icon>
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ statistics?.total ?? 0 }}</div>
          <div class="stat-label">Total Antrian</div>
        </div>
      </div>

      <div class="stat-divider" />

      <div class="stat-item">
        <div class="stat-icon stat-icon-waiting">
          <v-icon size="32" color="primary-600">mdi-clock-alert-outline</v-icon>
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ statistics?.waiting ?? 0 }}</div>
          <div class="stat-label">Menunggu</div>
        </div>
      </div>

      <div class="stat-divider" />

      <div class="stat-item">
        <div class="stat-icon stat-icon-active">
          <v-icon size="32" color="primary-600">mdi-account-check</v-icon>
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ statistics?.active ?? 0 }}</div>
          <div class="stat-label">Dipanggil untuk Check-in</div>
        </div>
      </div>

      <div class="footer-message">
        <v-icon size="24" color="primary-600" class="mr-2">mdi-information</v-icon>
        <span>Harap perhatikan nomor tiket Anda yang dipanggil untuk check-in</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useQueueStore } from '@/stores/queueStore'
import { useMasterStore } from '@/stores/masterStore'
import { useAntreanMasukScreenStore } from '@/stores/antreanMasukScreenStore'
import { useRoute, useRuntimeConfig } from '#app'

definePageMeta({
  layout: false,
})

// Set viewport meta tag for proper responsive behavior
useHead({
  meta: [
    {
      name: 'viewport',
      content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover'
    }
  ]
})

const route = useRoute()
const queueStore = useQueueStore()
const masterStore = useMasterStore()
const antreanMasukScreenStore = useAntreanMasukScreenStore()

// Get screen ID from route (not loket ID)
const screenId = computed(() => {
  const id = route.params.id
  // Handle both string and array cases
  const idValue = Array.isArray(id) ? id[0] : id
  const parsed = parseInt(idValue)
  return isNaN(parsed) ? null : parsed
})

// Get screen configuration
const screenData = computed(() => {
  const id = screenId.value
  if (!id) return null
  
  const screen = antreanMasukScreenStore.antreanMasukScreenItems.find(s => s.id === id)
  return screen || null
})

// Get all loket IDs configured for this screen
const configuredLoketIds = computed(() => {
  if (screenData.value) {
    return screenData.value.loket || []
  }
  
  // FALLBACK: If screen not found, treat ID as a Loket ID
  // This allows displaying a specific single loket without screen config
  if (screenId.value) {
    return [screenId.value]
  }
  
  return []
})


const currentTime = ref('')
const currentDate = ref('')
let timeInterval = null

// Toggle untuk menyembunyikan/menampilkan loket tanpa antrian
// true = sembunyikan loket tanpa antrian (default)
// false = tampilkan semua loket termasuk yang tanpa antrian
const hideEmptyLokets = ref(false)

const windowWidth = ref(process.client ? window.innerWidth : 1920)
// Status scroll per loket: { loketId: boolean }
const loketScrollStatus = ref({})
const queueDisplayRefs = ref({})
const queueScrollRefs = ref({})

const setQueueDisplayRef = (el, loketId) => {
  if (el) queueDisplayRefs.value[loketId] = el
}

const setQueueScrollRef = (el, loketId) => {
  if (el) queueScrollRefs.value[loketId] = el
}

const checkOverflow = (loketId) => {
  const container = queueDisplayRefs.value[loketId]
  const content = queueScrollRefs.value[loketId]
  
  if (container && content) {
    // Check if content height is greater than container height
    // We use a small buffer (5px) to prevent flickering
    const hasOverflow = content.scrollHeight > container.clientHeight + 5
    loketScrollStatus.value[loketId] = hasOverflow
  }
}

const checkAllOverflows = () => {
  nextTick(() => {
    displayedLokets.value.forEach(loket => {
      checkOverflow(loket.id)
    })
  })
}

const updateWidth = () => {
  if (process.client) {
    windowWidth.value = window.innerWidth
    checkAllOverflows()
  }
}

// Get all patients with processStage 'loket'
// Force reactivity by accessing the computed result directly
const loketPatients = computed(() => {
  try {
    // Get the computed result from store
    const stageResult = queueStore.getPatientsByStage('loket')
    
    // Access .value to get the actual computed value
    // This ensures reactivity after store hydration
    if (stageResult && stageResult.value) {
      const patients = stageResult.value.all || []
      // Ensure it's an array and filter out any null/undefined
      return Array.isArray(patients) ? patients.filter(p => p != null) : []
    }
    return []
  } catch (error) {
    console.error('Error getting loket patients:', error)
    return []
  }
})

// Filter: Only show tickets from anjungan that are called for check-in
// These are tickets printed from anjungan that have been called by admin loket
// Status berubah dari 'menunggu' menjadi 'waiting' ketika dipanggil oleh admin loket
// Status 'waiting' = sudah dipanggil tapi belum check-in
// Filter berdasarkan loket yang dikonfigurasi di screen
const calledForCheckIn = computed(() => {
  const loketIds = configuredLoketIds.value
  
  // Jika tidak ada loket yang dikonfigurasi, return empty array
  if (!loketIds || loketIds.length === 0) {
    return []
  }
  
  // Normalize loketIds to strings for robust comparison
  const normalizedConfiguredIds = loketIds.map(id => String(id))
  
  return loketPatients.value
    .filter(p => {
      // Must be called (waiting status = sudah dipanggil dari status menunggu) 
      // and not yet checked in (processStage still 'loket')
      const isCalled = p.status === 'anjungan' && p.processStage === 'loket'
      
      // Filter berdasarkan loketId yang dikonfigurasi di screen
      // Handle potential undefined or number types
      const patientLoketId = String(p.loketId || 1)
      const isForConfiguredLoket = normalizedConfiguredIds.includes(patientLoketId)
      
      return isCalled && isForConfiguredLoket
    })
    // Tidak perlu sorting - tampilkan semua sesuai urutan dari store
})

// Removed displayedQueues - tidak diperlukan lagi karena menggunakan allCalledQueues

// Group queues by loketId and create loket cards
const displayedLokets = computed(() => {
  const loketIds = configuredLoketIds.value
  
  if (!loketIds || loketIds.length === 0) {
    return []
  }
  
  // Ensure calledForCheckIn is an array
  const queues = Array.isArray(calledForCheckIn.value) ? calledForCheckIn.value : []
  
  // Group queues by loketId
  const queuesByLoket = new Map()
  const normalizedQueues = Array.isArray(calledForCheckIn.value) ? calledForCheckIn.value : []
  
  loketIds.forEach(loketId => {
    const loket = masterStore.getLoketById(loketId)
    const loketQueues = normalizedQueues
      .filter(q => {
        // Robust string comparison
        return String(q.loketId || 1) === String(loketId)
      })
      .sort((a, b) => {
        // Sort numerically by ticket number (e.g., A1, A2, A10) 
        const noA = (a.noAntrian || '').split('|')[0].trim();
        const noB = (b.noAntrian || '').split('|')[0].trim();
        
        // Use localeCompare with numeric: true for natural sorting (e.g., A1 before A10)
        const numCompare = noA.localeCompare(noB, undefined, { numeric: true, sensitivity: 'base' });
        
        if (numCompare !== 0) return numCompare;
        
        // Fallback to createdAt for consistent ordering if ticket numbers are identical
        if (a.createdAt && b.createdAt) {
          return new Date(a.createdAt) - new Date(b.createdAt)
        }
        return (a.no || 0) - (b.no || 0)
      })
    
    queuesByLoket.set(loketId, {
      id: loketId,
      nama: loket ? loket.namaLoket : `Loket ${loketId}`,
      queues: loketQueues,
      totalQueues: loketQueues.length
    })
  })
  
  // Filter: hanya tampilkan loket yang memiliki antrian (jika hideEmptyLokets = true)
  const allLokets = Array.from(queuesByLoket.values())
  if (hideEmptyLokets.value) {
    return allLokets.filter(loket => loket.queues.length > 0)
  }
  return allLokets
})

// Calculate grid columns based on number of displayed lokets
// User wants all lokets in a single row (columns only)
const gridStyle = computed(() => {
  return {
    gridTemplateColumns: `repeat(${displayedLokets.value.length || 1}, 1fr)`
  }
})

const ticketGridStyle = computed(() => {
  return {
    gridTemplateColumns: `repeat(auto-fill, minmax(min(115px, 100%), 1fr))`
  }
})

const statistics = computed(() => {
  // Ensure we always return default values even if data is not ready
  try {
    const loketIds = configuredLoketIds.value
    
    // Jika tidak ada loket yang dikonfigurasi, return 0
    if (!loketIds || loketIds.length === 0) {
      return {
        total: 0,
        waiting: 0,
        active: 0
      }
    }
    
    // Ensure loketPatients is an array
    const patients = Array.isArray(loketPatients.value) ? loketPatients.value : []
    
    // Filter semua pasien untuk loket-loket yang dikonfigurasi di screen
    const allLoketTickets = patients.filter(p => {
      if (!p) return false
      
      // Filter berdasarkan loketId yang dikonfigurasi
      const patientLoketId = p.loketId || 1 // Default ke loket 1 jika tidak ada
      return loketIds.includes(patientLoketId)
    })
    
    // Menunggu = belum dipanggil (status 'menunggu')
    const menungguCount = allLoketTickets.filter(p => p && p.status === 'menunggu').length
    
    // Dipanggil untuk check-in = sudah dipanggil (status 'anjungan')
    const calledForCheckInArray = Array.isArray(calledForCheckIn.value) ? calledForCheckIn.value : []
    const activeCount = calledForCheckInArray.length
    
    return {
      total: allLoketTickets.length || 0,
      waiting: menungguCount || 0, // Jumlah yang masih menunggu untuk dipanggil
      active: activeCount || 0 // Jumlah yang sudah dipanggil dan ditampilkan di layar
    }
  } catch {
    // Return default values if there's any error
    return {
      total: 0,
      waiting: 0,
      active: 0
    }
  }
})

const updateTime = () => {
  const now = new Date()
  // Format jam dengan titik dua (HH:MM:SS)
  const timeString = now.toLocaleTimeString('id-ID', { 
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
  currentTime.value = timeString.replace(/\./g, ':')
  currentDate.value = now.toLocaleDateString('id-ID', {
    weekday: 'long',
    day: 'numeric',
    month: 'long',
    year: 'numeric'
  })
}

// ========== DATA FETCHING & WEBSOCKET ==========

// Proactive Fetching: Ensure this screen fetches data even if others didn't
const fetchAllData = async () => {
  if (!screenId.value) return;
  
  console.log('🔄 Anjungan refresh: Fetching data for configured lokets...');
  try {
    // 1. Fetch data for each configured loket
    const loketIds = configuredLoketIds.value;
    if (loketIds && loketIds.length > 0) {
      for (const id of loketIds) {
        await queueStore.fetchPatientsForLoket(id);
      }
    }
    
    // 2. Ensure initial data (seeds etc)
    queueStore.ensureInitialData();
    
    console.log('✅ Anjungan refresh: Success');
    checkAllOverflows();
  } catch (err) {
    console.error('❌ Anjungan refresh error:', err);
  }
};

// WebSocket configuration for Anjungan
const config = useRuntimeConfig()
const wsBaseUrl = config.public?.wsBaseUrl || 'ws://10.10.123.135:8084/api/v1/ws'

// Generate a unique session suffix (random ID) to fulfill "use different id" request
// This ensures that even if the same screen is opened in multiple tabs, they have distinct client IDs
const uniqueSessionSuffix = ref(process.client ? Math.random().toString(36).substring(2, 8) : '')

const anjunganClientId = computed(() => {
  if (!screenId.value) return ''
  return `anjungan-masuk-${screenId.value}`
})

// let wsInstance = null
// const isConnected = ref(false)

// WebSocket configuration (Centralized in queueStore)
// Old implementation preserved for rollback
/*
const initWebSocketLocal = () => {
  if (!screenId.value) return null
  
  console.log('🔌 WebSocket: Connecting to', wsBaseUrl)
  console.log('🆔 Client ID:', anjunganClientId.value)
  
  wsInstance = useWebSocket({
    url: wsBaseUrl,
    clientId: anjunganClientId.value,
    fallbackPostUrl: `${config.public.externalApiBaseUrl}/ws`,
    onMessage: (data) => {
      console.log('📨 WebSocket message received:', data)
      fetchAllData()
    },
    onOpen: () => {
      console.log('✅ WebSocket connected')
      isConnected.value = true
    },
    onClose: () => {
      isConnected.value = false
    },
    onError: () => {
      isConnected.value = false
    },
    reconnectInterval: 3000,
    maxReconnectAttempts: 10
  })
  
  return wsInstance
}
*/

const isConnected = computed(() => queueStore.isWsConnected);

// Watch loketPatients to ensure reactivity after refresh
watch(loketPatients, (newPatients) => {
  if (newPatients && newPatients.length > 0) {
    checkAllOverflows()
  }
}, { immediate: true, deep: true })

// Watch store's getPatientsByStage to ensure reactivity after refresh
watch(() => {
  try {
    const result = queueStore.getPatientsByStage('loket')
    return result?.value?.all || []
  } catch {
    return []
  }
}, (newPatients) => {
  // Force reactivity update
  if (newPatients && newPatients.length > 0) {
    console.log('Store loket patients updated:', newPatients.length)
  }
}, { immediate: true, deep: true })

onMounted(() => {
  updateWidth()
  if (process.client) {
    window.addEventListener('resize', updateWidth)
    
    // Check overflows initially
    checkAllOverflows()
    
    // Set up ResizeObserver to monitor container size changes
    const resizeObserver = new ResizeObserver(() => {
      checkAllOverflows()
    })
    
    // Observe the main container
    const container = document.querySelector('.antrian-display-container')
    if (container) resizeObserver.observe(container)
    
    onUnmounted(() => {
      window.removeEventListener('resize', updateWidth)
      resizeObserver.disconnect()
    })
  }
  
  // Wait for stores to be hydrated from persisted state
  // Use nextTick to ensure stores are ready
  nextTick(async () => {
    // Redirect to index if screen not found
    if (!screenData.value) {
      navigateTo('/anjungan/antreanmasuk')
      return
    }

    // Initial fetch
    await fetchAllData();

    // Initialize and connect WebSocket (Centralized)
    queueStore.initWebSocket(anjunganClientId.value);
    
    // Register specific interest for each configured loket to receive immediate WS updates
    if (configuredLoketIds.value && configuredLoketIds.value.length > 0) {
      configuredLoketIds.value.forEach(id => queueStore.registerInterest(id));
    }

    onUnmounted(() => {
      // Unregister specific interest when leaving the page
      if (configuredLoketIds.value && configuredLoketIds.value.length > 0) {
        configuredLoketIds.value.forEach(id => queueStore.unregisterInterest(id));
      }
    });
    
    updateTime();
    timeInterval = setInterval(updateTime, 1000);
  })
})

onUnmounted(() => {
  if (timeInterval) clearInterval(timeInterval)
  if (process.client) {
    window.removeEventListener('resize', updateWidth)
  }
})

</script>

<style scoped lang="scss">
.antrian-display-container {
  background: #FFFFFF;
  width: 100%;
  min-height: 100vh;
  min-height: 100dvh; /* Dynamic viewport height for better mobile support */
  max-width: 100vw;
  max-height: 100vh;
  max-height: 100dvh;
  padding: 16px;
  font-family: 'Roboto', sans-serif;
  overflow: auto;
  display: flex;
  flex-direction: column;
  margin: 0;
  box-sizing: border-box;
  position: relative;
}

/* Ensure body/html don't cause layout issues */
:deep(body),
:deep(html) {
  margin: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  position: fixed;
  overscroll-behavior: none;
}

:deep(#__nuxt) {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  position: fixed;
  overflow: hidden;
}

/* ========== HEADER ========== */
.display-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, var(--color-primary-600) 0%, var(--color-primary-700) 100%);
  border-radius: 12px;
  padding: clamp(12px, 1.2vw, 18px) clamp(16px, 2vw, 24px);
  margin-bottom: 12px;
  box-shadow: 0 8px 24px rgba(25, 118, 210, 0.3);
  flex-shrink: 0;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.logo-circle {
  background: rgba(255, 255, 255, 0.95);
  width: 70px;
  height: 70px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-logo {
  width: 56px;
  height: 56px;
  object-fit: contain;
  padding: 4px;
}

.header-text {
  flex: 1;
}

.hospital-name {
  font-size: clamp(20px, 1.8vw, 26px);
  font-weight: 800;
  color: var(--color-neutral-100);
  margin: 0;
  letter-spacing: 0.5px;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  line-height: 1.1;
}

.display-subtitle {
  font-size: 20px;
  font-weight: 600;
  color: var(--color-neutral-100);
  margin: 6px 0 0 0;
  opacity: 0.95;
}

.klinik-info {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-neutral-100);
  margin: 4px 0 0 0;
  opacity: 0.85;
}

.loket-info {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-neutral-100);
  margin: 4px 0 0 0;
  opacity: 0.85;
}

.header-right {
  display: flex;
  align-items: center;
}

.datetime-display {
  text-align: right;
}

.time-large {
  font-size: clamp(32px, 3vw, 48px);
  font-weight: 900;
  color: var(--color-neutral-100);
  letter-spacing: 1px;
  line-height: 1;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  font-variant-numeric: tabular-nums; /* Prevent digit shifting */
}

.date-small {
  font-size: 14px;
  color: var(--color-neutral-100);
  margin-top: 6px;
  font-weight: 500;
  opacity: 0.95;
}

/* ========== LOKET GRID CONTAINER ========== */
.loket-grid-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  box-sizing: border-box;
  overflow: hidden;
}

.lokets-grid {
  display: grid;
  gap: clamp(8px, 1vw, 16px);
  width: 100%;
  flex: 1;
  min-height: 0;
  box-sizing: border-box;
  overflow: hidden;
  /* grid-template-columns is set dynamically via :style binding */
}

.loket-card {
  background: #FFFFFF;
  border-radius: 8px;
  border: 1px solid #E0E0E0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 150px;
  min-width: 0;
  /* Tidak set max-height untuk allow card fleksibel */
}

/* Loket Header */
.loket-header-bar {
  background: linear-gradient(135deg, var(--color-primary-600) 0%, var(--color-primary-700) 100%);
  color: var(--color-neutral-100);
  padding: clamp(8px, 1vw, 14px) clamp(10px, 1.2vw, 18px);
  box-shadow: 0 2px 8px rgba(58, 97, 201, 0.2);
  border-radius: 8px 8px 0 0;
  flex-shrink: 0;
}

.loket-header-content {
  display: flex;
  align-items: center;
  font-weight: 700;
  font-size: 16px;
  gap: 8px;
  width: 100%;
}

.loket-name {
  flex: 1;
  color: var(--color-neutral-100);
  font-weight: 700;
  font-size: 24px;
  letter-spacing: 0.5px;
  text-transform: uppercase;
  line-height: 1.2;
}

.loket-header-chip {
  color: var(--color-neutral-100) !important;
  font-weight: 700;
  font-size: 16px;
  height: 32px !important;
  padding: 0 16px !important;
  min-width: auto !important;
}

.loket-header-chip .v-icon {
  margin-right: 6px;
}

/* Queue Display - CSS Animated Scroll */
.queue-display {
  flex: 1;
  padding: clamp(4px, 0.6vw, 10px);
  padding-bottom: 1vh;
  overflow: hidden;
  background: #FFFFFF;
  min-height: 0;
  box-sizing: border-box;
  position: relative;
}

.ticket-cards-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* Scroll Container with CSS Animation */
.ticket-cards-scroll {
  width: 100%;
  display: flex;
  flex-direction: column;
}

/* Animate scroll when there are many items */
.ticket-cards-scroll.animate-scroll {
  animation: scroll-up 30s linear infinite;
}

/* Keyframes for smooth vertical scrolling */
@keyframes scroll-up {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-50%);
  }
}

/* Pause animation on hover for better UX */
.ticket-cards-scroll:hover {
  animation-play-state: paused;
}

.ticket-cards-grid {
  display: grid;
  gap: clamp(4px, 0.4vw, 8px);
  width: 100%;
  padding: 4px;
}

.ticket-card {
  background: var(--color-neutral-400, #E1E5EA);
  border: 1px solid var(--color-neutral-500, #CDD4DC);
  border-radius: 8px;
  padding: clamp(6px, 0.8vh, 10px) 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  min-height: clamp(55px, 7vh, 80px);
  position: relative;
  cursor: default;
}

.ticket-card-fast-track {
  background: var(--color-secondary-50, rgba(255, 132, 65, 0.15)) !important;
  border-color: var(--color-secondary-300, rgba(255, 132, 65, 0.4)) !important;
  border-width: 2px;
}

.ticket-card:hover {
  box-shadow: 0 4px 12px rgba(58, 97, 201, 0.15);
  border-color: var(--color-primary-500, #567EE7);
  transform: translateY(-2px);
  background: var(--color-neutral-300, #F5F7FA);
}

.ticket-card-fast-track:hover {
  background: var(--color-secondary-100, rgba(255, 132, 65, 0.2)) !important;
  border-color: var(--color-secondary-500, #FF8441) !important;
}

.ticket-number {
  font-size: clamp(14px, 3.5vw, 32px);
  font-weight: 800;
  color: var(--color-primary-600, #3A61C9);
  letter-spacing: -0.5px;
  line-height: 1;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  text-align: center;
  white-space: nowrap;
  width: 100%;
  overflow: visible; /* Don't hide/ellipsis, let it fit via clamp font-size */
  font-variant-numeric: tabular-nums; /* Stable digits */
}

.ticket-klinik {
  font-size: 11px;
  font-weight: 500;
  color: #717171;
  text-align: center;
  margin-top: 4px;
}

.ticket-fast-track {
  position: absolute;
  top: 6px;
  right: 6px;
  background: var(--color-danger-600, #DE473B);
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 6px rgba(222, 71, 59, 0.4);
  z-index: 1;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(239, 83, 80, 0.15); /* Red background dengan opacity */
  border: 2px solid rgba(229, 57, 53, 0.4); /* Red border */
  transition: all 0.2s ease;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(229, 57, 53, 0.2);
}

.ticket-fast-track:hover {
  background: #E53935; /* Solid red on hover */
  border-color: #E53935;
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(229, 57, 53, 0.4);
}

.ticket-fast-track .v-icon {
  color: #E53935 !important;
  transition: all 0.2s ease;
  font-size: 16px !important;
}

.ticket-fast-track:hover .v-icon {
  color: white !important;
}

.empty-queue {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  min-height: 300px;
  color: var(--color-neutral-600, #89939E);
}

.empty-icon {
  margin-bottom: 20px;
  opacity: 0.6;
  transition: all 0.3s ease;
  font-size: 64px !important;
}

.empty-queue:hover .empty-icon {
  opacity: 0.8;
  transform: scale(1.05);
}

.empty-text {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-neutral-700, #717171);
  margin-bottom: 8px;
}

.empty-subtext {
  font-size: 13px;
  font-weight: 400;
  color: var(--color-neutral-600, #89939E);
  opacity: 0.8;
}

/* ========== FOOTER STATS ========== */
.footer-stats-bar {
  background: #FFFFFF;
  border: 2px solid var(--color-primary-200);
  border-radius: 14px;
  padding: 20px 40px;
  display: flex !important;
  align-items: center;
  justify-content: space-between;
  gap: 24px;
  box-shadow: 0 4px 16px rgba(25, 118, 210, 0.08);
  flex-shrink: 0;
  width: 100%;
  box-sizing: border-box;
  margin-top: 24px;
  min-height: 90px;
  height: auto;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-shrink: 0;
  min-width: fit-content;
  width: auto;
  height: 70px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  min-width: 60px;
  min-height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-icon-total,
.stat-icon-waiting {
  background: var(--color-primary-200);
}

.stat-icon-active {
  background: var(--color-primary-200);
}

.stat-info {
  text-align: left;
  flex-shrink: 0;
  min-width: fit-content;
  width: auto;
  height: 70px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-value {
  font-size: 52px;
  font-weight: 900;
  color: #212121;
  line-height: 1;
  white-space: nowrap;
  height: auto;
  display: flex;
  align-items: center;
  font-variant-numeric: tabular-nums; /* Stable digits */
}

.stat-label {
  font-size: 14px;
  color: #717171;
  font-weight: 600;
  margin-top: 6px;
  height: auto;
  line-height: 1.2;
}

.stat-divider {
  width: 2px;
  height: 70px;
  min-width: 2px;
  min-height: 70px;
  background: var(--color-primary-200);
  flex-shrink: 0;
}

.footer-message {
  flex: 1;
  text-align: right;
  font-size: 20px;
  font-weight: 600;
  color: #4D4D4D;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  min-width: 0;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 70px;
  padding-left: 24px;
}

/* ========== RESPONSIVE ========== */
/* Fullscreen layout - no fixed dimensions to prevent breaking on refresh */

@media (max-width: 1366px) {
  .antrian-display-container {
    padding: 16px;
  }

  .display-header {
    padding: 16px 24px;
  }

  .logo-circle {
    width: 64px;
    height: 64px;
  }

  .logo-circle .v-icon {
    font-size: 40px !important;
  }

  .hospital-name {
    font-size: 36px;
  }

  .display-subtitle {
    font-size: 16px;
  }

  .time-large {
    font-size: 48px;
  }

  .date-small {
    font-size: 14px;
  }

  .hero-call-section {
    padding: 24px;
  }

  .call-label {
    font-size: 24px;
  }

  .call-number {
    font-size: 100px;
  }

  .call-loket {
    font-size: 28px;
  }

  .lokets-grid {
    gap: 12px;
    /* grid-template-columns is set dynamically via :style binding */
  }

  .loket-name {
    font-size: 20px;
  }

  .ticket-number {
    font-size: 28px;
  }

  .footer-stats-bar {
    padding: 16px 32px;
  }

  .stat-icon {
    width: 56px;
    height: 56px;
  }

  .stat-icon .v-icon {
    font-size: 28px !important;
  }

  .stat-value {
    font-size: 36px;
  }

  .stat-label {
    font-size: 13px;
  }

  .stat-divider {
    height: 50px;
  }

  .footer-message {
    font-size: 18px;
  }
}

@media (max-width: 1024px) {
  .display-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-left {
    flex-direction: column;
    gap: 12px;
  }

  .datetime-display {
    text-align: center;
  }

  .footer-stats-bar {
    flex-direction: column;
    gap: 16px;
  }

  .stat-divider {
    display: none;
  }

  .footer-message {
    text-align: center;
    justify-content: center;
  }
}

@media (max-width: 960px) {
  .lokets-grid {
    gap: 12px;
  }
  
  .ticket-card {
    min-height: 70px;
    padding: 10px;
  }
}

@media (min-width: 961px) {
  .lokets-grid {
    gap: clamp(12px, 1vw, 20px);
  }
}


@media (max-width: 768px) {
  .hospital-name {
    font-size: 28px;
  }

  .time-large {
    font-size: 36px;
  }

  .loket-name {
    font-size: 18px;
  }

  .ticket-number {
    font-size: 20px;
    color: #3556AE;
  }
}

/* Prevent text selection */
* {
  user-select: none;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
</style>

