<template>
  <div class="antrian-display-container">
    <!-- Header -->
    <div class="display-header">
      <div class="header-left">
        <div class="logo-circle">
          <img 
            src="/Rumah_Sakit_Umum_Daerah_Dr._Saiful_Anwar.webp" 
            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">ANTRIAN KLINIK RUANG</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>

    <!-- Hero Call Section -->
    <Transition name="hero-fade">
      <div v-if="currentCalledQueue" class="hero-call-section" :class="{ 'is-compact': isCompact }">
        <div class="call-label">
          <v-icon :size="isCompact ? 24 : 32" color="white" class="mr-2">mdi-bullhorn</v-icon>
          NOMOR ANTRIAN YANG DIPANGGIL
        </div>
        <div class="call-number">{{ currentCalledQueue.noAntrian.split(' |')[0] }}</div>
        <div class="call-clinic">
          {{ currentCalledQueue.klinik === currentCalledQueue.ruang ? currentCalledQueue.ruang : `${currentCalledQueue.klinik} - ${currentCalledQueue.ruang}` }}
        </div>
      </div>
    </Transition>

    <!-- Main Grid - Display Ruang -->
    <div class="clinics-grid" :style="gridStyle" :class="{ 'is-compact': isCompact }">
      <div
        v-for="ruang in displayedRuang"
        :key="`${ruang.kodeKlinik}-${ruang.nomorRuang}`"
        class="clinic-box"
        :class="{ 'is-single-view': displayedRuang.length === 1, 'is-compact': isCompact }"
      >
        <!-- Clinic Header -->
        <div class="clinic-header-bar">
          <span class="clinic-title">
            {{ ruang.namaKlinik === ruang.namaRuang ? ruang.namaRuang : `${ruang.namaKlinik} - ${ruang.namaRuang}` }}
          </span>
          <v-chip :size="isCompact ? 'x-small' : 'small'" class="clinic-count">
            <v-icon :size="isCompact ? 14 : 16" color="white" class="mr-1">mdi-account-multiple</v-icon>
            <span class="count-text">{{ ruang.totalQueues }}</span>
          </v-chip>
        </div>

        <!-- Queue Content -->
        <div class="clinic-content">
          <!-- Pemeriksaan Awal Section -->
          <div class="tipe-layanan-section">
            <div class="tipe-label">PEMERIKSAAN AWAL</div>
            <div v-if="ruang.pemeriksaanAwal.currentQueue" class="current-section">
              <div class="current-label">SEKARANG</div>
              <div class="current-number">
                {{ ruang.pemeriksaanAwal.currentQueue.noAntrian.split(' |')[0] }}
              </div>
            </div>
            <div v-if="!ruang.pemeriksaanAwal.currentQueue" class="empty-state-small">
              <v-icon :size="isCompact ? 18 : 24" color="grey-lighten-4">mdi-clock-outline</v-icon>
              <p class="empty-text-small">Tidak Ada</p>
            </div>
          </div>

          <!-- Divider -->
          <v-divider :class="isCompact ? 'my-1' : 'my-3'" />

          <!-- Tindakan Section -->
          <div class="tipe-layanan-section">
            <div class="tipe-label">PEMERIKSAAN</div>
            <div v-if="ruang.tindakan.currentQueue" class="current-section">
              <div class="current-label">SEKARANG</div>
              <div class="current-number">
                {{ ruang.tindakan.currentQueue.noAntrian.split(' |')[0] }}
              </div>
            </div>
            <div v-if="!ruang.tindakan.currentQueue" class="empty-state-small">
              <v-icon :size="isCompact ? 18 : 24" color="grey-lighten-4">mdi-clock-outline</v-icon>
              <p class="empty-text-small">Tidak Ada</p>
            </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 }}</div>
          <div class="stat-label">Total Antrian</div>
        </div>
      </div>

      <div class="stat-divider"></div>

      <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.anjungan }}</div>
          <div class="stat-label">Menunggu</div>
        </div>
      </div>

      <div class="stat-divider"></div>

      <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 }}</div>
          <div class="stat-label">Sedang Dilayani</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 antrian Anda di layar</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useQueueStore } from '@/stores/queueStore'
import { useMasterStore } from '@/stores/masterStore'
import { useClinicStore } from '@/stores/clinicStore'
import { useRuangStore } from '@/stores/ruangStore'
import { useRoute } from '#app'
import { useWebSocket } from '@/composables/useWebSocket'

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 clinicStore = useClinicStore()
const ruangStore = useRuangStore()

const kodeKlinik = computed(() => {
  const kode = route.params.kodeKlinik
  // Handle both string and array cases
  return Array.isArray(kode) ? kode[0] : kode
})

// Get jenisLayanan from query parameter to differentiate same clinic code with different service types
const jenisLayanan = computed(() => {
  return route.query.jenisLayanan || null
})

const klinikData = computed(() => {
  const kode = kodeKlinik.value
  if (!kode) return null

  const fromGetter = masterStore.getAllRuangList?.value
  const fromState = masterStore.ruangData?.value || masterStore.ruangData || []

  let allRuang = Array.isArray(fromGetter) ? fromGetter : []
  if (allRuang.length === 0 && Array.isArray(fromState)) {
    fromState.forEach((r) => {
      (r?.ruangList || []).forEach((ru) => {
        allRuang.push({
          kodeKlinik: r.kodeKlinik,
          namaKlinik: r.namaKlinik,
          nomorRuang: ru.nomorRuang,
          namaRuang: ru.namaRuang,
          nomorScreen: ru.nomorScreen,
          jenisLayanan: r.jenisLayanan
        })
      })
    })
  }

  // Filter by kodeKlinik AND jenisLayanan if provided
  let filteredRuang
  if (jenisLayanan.value) {
    filteredRuang = allRuang.filter(r => 
      r.kodeKlinik === kode && r.jenisLayanan === jenisLayanan.value
    )
  } else {
    // Fallback: just filter by kodeKlinik
    filteredRuang = allRuang.filter(r => r.kodeKlinik === kode)
  }

  const firstRuang = filteredRuang[0]
  if (firstRuang) {
    return {
      kodeKlinik: firstRuang.kodeKlinik,
      namaKlinik: firstRuang.namaKlinik,
      jenisLayanan: firstRuang.jenisLayanan
    }
  }
  return null
})

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

const klinikPatients = computed(() => {
  // Get valid room numbers for this klinik+jenisLayanan combination
  // This ensures we only show patients whose rooms belong to the selected jenisLayanan
  const validRoomNumbers = ruangListForKlinik.value.map(r => r.nomorRuang)
  
  // Get patients from klinik-ruang stage (created from AdminKlinikRuang)
  // Filter out finished patients (status: 'processed' or 'selesai')
  // AND filter by room number to separate patients by jenisLayanan
  return queueStore.allPatients.filter(p => 
    p.processStage === 'klinik-ruang' && 
    p.kodeKlinik === kodeKlinik.value &&
    p.status !== 'processed' &&
    p.status !== 'selesai' &&
    validRoomNumbers.includes(p.nomorRuang) // Only show patients in rooms belonging to this jenisLayanan
  )
})

// Get ruang list for this specific klinik
const ruangListForKlinik = computed(() => {
  if (!kodeKlinik.value || !klinikData.value) return []

  const fromGetter = masterStore.getAllRuangList?.value
  const fromState = masterStore.ruangData?.value || masterStore.ruangData || []
  let allRuang = Array.isArray(fromGetter) ? fromGetter : []
  if (allRuang.length === 0 && Array.isArray(fromState)) {
    fromState.forEach((r) => {
      (r?.ruangList || []).forEach((ru) => {
        allRuang.push({
          kodeKlinik: r.kodeKlinik,
          namaKlinik: r.namaKlinik,
          nomorRuang: ru.nomorRuang,
          namaRuang: ru.namaRuang,
          nomorScreen: ru.nomorScreen,
          jenisLayanan: r.jenisLayanan
        })
      })
    })
  }
  
  // Filter by kodeKlinik AND jenisLayanan if provided
  let filtered
  if (jenisLayanan.value) {
    filtered = allRuang.filter(r => 
      r.kodeKlinik === kodeKlinik.value && r.jenisLayanan === jenisLayanan.value
    )
  } else {
    filtered = allRuang.filter(r => r.kodeKlinik === kodeKlinik.value)
  }
  
  return filtered.map(ruang => ({
    kodeKlinik: ruang.kodeKlinik,
    namaKlinik: ruang.namaKlinik,
    nomorRuang: ruang.nomorRuang,
    namaRuang: ruang.namaRuang,
    nomorScreen: ruang.nomorScreen,
    jenisLayanan: ruang.jenisLayanan
  }))
})

const displayedRuang = computed(() => {
  if (!kodeKlinik.value || ruangListForKlinik.value.length === 0) {
    return []
  }

  return ruangListForKlinik.value.map(ruang => {
    // Get queues for this specific room
    const allQueues = klinikPatients.value
      .filter(p => p.nomorRuang === ruang.nomorRuang)
      .sort((a, b) => {
        const statusPriority = {
          'di-loket': 1,
          'waiting': 2,
          'terlambat': 3,
          'pending': 4
        }
        
        const priorityDiff = (statusPriority[a.status] || 99) - (statusPriority[b.status] || 99)
        if (priorityDiff !== 0) return priorityDiff
        
        const numA = parseInt(a.noAntrian.replace(/\D/g, '') || '999')
        const numB = parseInt(b.noAntrian.replace(/\D/g, '') || '999')
        return numA - numB
      })

    const pemeriksaanAwalQueues = allQueues.filter(q => q.tipeLayanan === 'Pemeriksaan Awal')
    const tindakanQueues = allQueues.filter(q => q.tipeLayanan === 'Tindakan')

    const getCurrentAndNext = (queues, tipeLayanan) => {
      const currentCandidates = queues.filter(q => 
        q.status === 'di-loket' && q.tipeLayanan === tipeLayanan
      ).sort((a, b) => {
        const timeA = a.lastCalledAt ? new Date(a.lastCalledAt).getTime() : 0
        const timeB = b.lastCalledAt ? new Date(b.lastCalledAt).getTime() : 0
        return timeB - timeA
      })
      
      const current = currentCandidates.length > 0 ? currentCandidates[0] : null
      const next = queues.filter(q => 
        q.no !== current?.no && q.status === 'waiting'
      ).slice(0, 3)
      return { current, next }
    }

    const pemeriksaanAwal = getCurrentAndNext(pemeriksaanAwalQueues, 'Pemeriksaan Awal')
    const tindakan = getCurrentAndNext(tindakanQueues, 'Tindakan')

    return {
      kodeKlinik: ruang.kodeKlinik,
      namaKlinik: ruang.namaKlinik,
      nomorRuang: ruang.nomorRuang,
      namaRuang: ruang.namaRuang,
      nomorScreen: ruang.nomorScreen,
      pemeriksaanAwal: {
        currentQueue: pemeriksaanAwal.current,
        nextQueues: pemeriksaanAwal.next,
        totalQueues: pemeriksaanAwalQueues.length
      },
      tindakan: {
        currentQueue: tindakan.current,
        nextQueues: tindakan.next,
        totalQueues: tindakanQueues.length
      },
      totalQueues: allQueues.length
    }
  })
})

const currentCalledQueue = computed(() => {
  if (!kodeKlinik.value || !klinikData.value) return null
  
  const CALL_DISPLAY_DURATION = 60000 // 60 seconds
  const now = new Date()
  
  // Force reactivity for time updates if needed (though now is created fresh here)
  // To make it truly reactive to time passing, we might need a reactive timestamp
  // But since this is a computed property, it recalculates when dependencies change.
  // To auto-hide after 60s without data change, we'd need a timer.
  // For now, let's just use the current time when data updates. 
  // If we want auto-hide, we can rely on the timeInterval updating 'currentTime' 
  // but 'currentTime' is a string. 
  // Let's use a reactive timestamp or just rely on re-renders for now.
  // Better: use the 'currentTime' string change to trigger re-calc if we include it.
  const _ = currentTime.value 

  // Get most recently called patient (status di-loket)
  // Sort by lastCalledAt
  const calledQueues = klinikPatients.value
    .filter(p => p.status === 'di-loket')
    .sort((a, b) => {
      const timeA = a.lastCalledAt ? new Date(a.lastCalledAt) : new Date(a.createdAt || 0)
      const timeB = b.lastCalledAt ? new Date(b.lastCalledAt) : new Date(b.createdAt || 0)
      return timeB - timeA
    })
  
  if (calledQueues.length > 0) {
    const patient = calledQueues[0]
    
    // Check if within duration
    const callTime = patient.lastCalledAt ? new Date(patient.lastCalledAt) : new Date(patient.createdAt || 0)
    const timeDiff = now.getTime() - callTime.getTime()
    
    if (timeDiff <= CALL_DISPLAY_DURATION) {
      return {
        ...patient,
        ruang: patient.ruang || patient.namaRuang || 'Ruang 1'
      }
    }
  }
  
  return null
})

const statistics = computed(() => {
  if (!kodeKlinik.value || !klinikData.value) {
    return { total: 0, waiting: 0, active: 0 }
  }
  
  const all = klinikPatients.value
  return {
    total: all.length,
    anjungan: all.filter(p => p.status === 'anjungan').length,
    active: all.filter(p => p.status === 'di-loket').length
  }
})

const displayedRuangCount = computed(() => displayedRuang.value.length)

// Decide if we should use compact layout based on room count
const isCompact = computed(() => displayedRuangCount.value > 8)

// Dynamic grid logic: more columns for higher room counts
const gridColumns = computed(() => {
  const total = displayedRuangCount.value
  if (total <= 1) return 1
  if (total <= 4) return total
  if (total <= 8) return Math.ceil(total / 2)
  if (total <= 12) return 5
  return 6 // For 13+ rooms, use 6 columns
})

const gridGap = computed(() => {
  if (displayedRuangCount.value <= 4) return '24px'
  if (displayedRuangCount.value <= 8) return '16px'
  return '12px'
})

const gridStyle = computed(() => ({
  gridTemplateColumns: `repeat(${gridColumns.value}, 1fr)`,
  gap: gridGap.value
}))

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'
  })
}

// 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)
const uniqueSessionSuffix = ref(process.client ? Math.random().toString(36).substring(2, 8) : '')

const fetchAllData = async () => {
  if (!kodeKlinik.value) return;
  console.log('🔄 AntrianKlinikRuang refresh: Fetching data...');
  try {
    await clinicStore.fetchRegulerClinics();
    await ruangStore.fetchRuangFromAPI();
    queueStore.ensureInitialData();
    console.log('✅ AntrianKlinikRuang refresh: Success');
  } catch (err) {
    console.error('❌ AntrianKlinikRuang refresh error:', err);
  }
};

// WebSocket client ID for anjungan (you can make this dynamic based on screen number)
const anjunganClientId = computed(() => {
  if (!kodeKlinik.value) return ''
  
  // Priority 1: Try to get screen number from URL query params
  const screenParam = route.query.screen
  if (screenParam) {
    const clientId = `anjungan-klinik-ruang-${kodeKlinik.value}-screen-${screenParam}`
    console.log('🆔 Using client ID from URL query screen param:', clientId)
    return clientId
  }
  
  // Priority 2: Try to get screen number from ruangList (ambil nomorScreen dari ruang pertama yang ada)
  if (ruangListForKlinik.value && ruangListForKlinik.value.length > 0) {
    // Ambil nomorScreen dari ruang pertama yang memiliki nomorScreen
    const firstRuangWithScreen = ruangListForKlinik.value.find(r => r.nomorScreen)
    if (firstRuangWithScreen && firstRuangWithScreen.nomorScreen) {
      const clientId = `anjungan-klinik-ruang-${kodeKlinik.value}-screen-${firstRuangWithScreen.nomorScreen}`
      console.log('🆔 Using client ID from ruangList nomorScreen:', clientId)
      return clientId
    }
  }
  
  // Priority 3: Fallback to client ID without screen number (broadcast)
  const clientId = `anjungan-klinik-ruang-${kodeKlinik.value}-${uniqueSessionSuffix.value}`
  console.log('🆔 Using default client ID (tab-specific):', clientId)
  return clientId
})

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

// WebSocket configuration (Centralized in queueStore)
// Old implementation preserved for rollback
/*
const initWebSocketLocal = () => {
  if (!kodeKlinik.value || !anjunganClientId.value) {
    console.warn('Cannot initialize WebSocket: missing kodeKlinik or clientId')
    return null
  }

  console.log('🔌 Initializing WebSocket connection...')
  console.log('📍 URL:', wsBaseUrl)
  console.log('🆔 Client ID:', anjunganClientId.value)

    wsInstance = useWebSocket({
      url: wsBaseUrl,
      clientId: anjunganClientId.value,
      fallbackPostUrl: '/stats-api/ws',
      onMessage: (data) => {
      console.log('📨 WebSocket raw message received:', data)
      let messageData = data
      if (data && typeof data === 'object' && data.data) {
        messageData = data.data
      }
      if (messageData && messageData.noantrian) {
        const nomorAntrian = messageData.noantrian
        const tipeLayanan = messageData.tipeLayanan || null 
        const patientIndex = queueStore.allPatients.findIndex(p => {
          const pNoAntrian = p.noAntrian?.split(" |")[0] || p.noAntrian
          return (pNoAntrian === nomorAntrian || p.barcode === nomorAntrian) &&
                 p.kodeKlinik === kodeKlinik.value &&
                 p.processStage === 'klinik-ruang'
        })
        if (patientIndex !== -1) {
          const updateData = {
            ...queueStore.allPatients[patientIndex],
            status: 'di-loket',
            lastCalledAt: new Date().toISOString(),
            lastCalledTipeLayanan: tipeLayanan,
          }
          if (tipeLayanan) {
            updateData.tipeLayanan = tipeLayanan
          }
          if (tipeLayanan === 'Pemeriksaan Awal') {
            updateData.calledPemeriksaanAwal = true
          } else if (tipeLayanan === 'Tindakan') {
            updateData.calledTindakan = true
          }
          queueStore.allPatients[patientIndex] = updateData
        }
      }
    },
    onOpen: () => {
      isConnected.value = true
    },
    onClose: () => {
      isConnected.value = false
    },
    onError: (error) => {
      isConnected.value = false
    },
    reconnectInterval: 3000,
    maxReconnectAttempts: 10,
  })

  return wsInstance
}
*/

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

onMounted(async () => {
  console.log('🚀 AntrianKlinikRuang (Anjungan) mounted, syncing data...')
  
  // Wait for stores to be hydrated and ready
  await nextTick();

  // Initial fetch/sync
  await fetchAllData();

  // Redirect to index if klinik not found after sync
  if (!klinikData.value) {
    console.warn('⚠️ Klinik data not found after sync, redirecting...')
    navigateTo('/anjungan/antrianklinikruang')
    return
  }
  
  updateTime()
  timeInterval = setInterval(updateTime, 1000)

  // WebSocket initialization is now centralized in queueStore
  if (kodeKlinik.value) {
    queueStore.initWebSocket(anjunganClientId.value);
  }
})

onUnmounted(() => {
  if (timeInterval) clearInterval(timeInterval)
  // wsInstance is now global
})

// Watch for clientId changes and reconnect if needed
watch(anjunganClientId, (newClientId, oldClientId) => {
  if (newClientId && newClientId !== oldClientId) {
    console.log('🔄 Client ID changed, reconnecting centralized WebSocket...')
    queueStore.initWebSocket(newClientId)
  }
})
</script>

<style scoped lang="scss">
.antrian-display-container {
  background: var(--color-neutral-300);
  width: 100vw;
  height: 100dvh;
  padding: 16px; /* Match AntrianLoket */
  font-family: 'Inter', 'Roboto', sans-serif;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* ========== 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); /* Match AntrianLoket */
  margin-bottom: 12px;
  box-shadow: 0 8px 24px rgba(33, 150, 243, 0.3);
  flex-shrink: 0;
}

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

.logo-circle {
  background: rgba(255, 255, 255, 0.95);
  width: 80px;
  height: 80px;
  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: 64px;
  height: 64px;
  object-fit: contain;
  padding: 4px;
}

.hospital-name {
  font-size: 48px;
  font-weight: 800;
  color: var(--color-neutral-100);
  margin: 0;
  letter-spacing: 2px;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  line-height: 1;
}

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

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

.time-large {
  font-size: 56px;
  font-weight: 900;
  color: var(--color-neutral-100);
  letter-spacing: 2px;
  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: 18px;
  color: var(--color-neutral-100);
  margin-top: 8px;
  font-weight: 500;
  opacity: 0.95;
}

/* ========== HERO CALL SECTION ========== */
.hero-call-section {
  background: linear-gradient(135deg, var(--color-primary-600) 0%, var(--color-primary-700) 100%);
  border-radius: 20px;
  padding: clamp(16px, 2vh, 32px);
  margin-bottom: clamp(8px, 1.2vh, 16px);
  text-align: center;
  box-shadow: 0 12px 32px rgba(33, 150, 243, 0.35);
  animation: pulse-highlight 2s ease-in-out infinite;
  flex-shrink: 0;
  max-height: 40vh;
  overflow: hidden;
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.hero-call-section.is-compact {
  padding: 12px 20px;
  margin-bottom: 12px;
}

.hero-call-section.is-compact .call-label {
  font-size: 18px;
  margin-bottom: 4px;
}

.hero-call-section.is-compact .call-number {
  font-size: 80px;
  margin: 4px 0;
}

.hero-call-section.is-compact .call-clinic {
  font-size: 20px;
}

.call-label {
  font-size: 28px;
  font-weight: 700;
  color: var(--color-neutral-100);
  letter-spacing: 2px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-transform: uppercase;
}

.call-number {
  font-size: clamp(60px, 14vh, 140px);
  font-weight: 900;
  color: var(--color-neutral-100);
  margin: clamp(8px, 1vh, 16px) 0;
  letter-spacing: clamp(4px, 1vw, 8px);
  line-height: 1;
  text-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  animation: number-pulse 1.5s ease-in-out infinite;
  font-variant-numeric: tabular-nums; /* Stable digits */
}

.call-clinic {
  font-size: clamp(20px, 2.5vh, 36px);
  font-weight: 700;
  color: var(--color-neutral-100);
  letter-spacing: 1px;
}

/* Transition for Hero Section */
.hero-fade-enter-active,
.hero-fade-leave-active {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  max-height: 40vh;
  opacity: 1;
  margin-bottom: clamp(8px, 1.2vh, 16px);
}

.hero-fade-enter-from,
.hero-fade-leave-to {
  max-height: 0;
  opacity: 0;
  margin-bottom: 0;
  padding-top: 0;
  padding-bottom: 0;
  transform: translateY(-20px);
}

/* ========== CLINICS GRID ========== */
.clinics-grid {
  display: grid;
  /* grid-template-columns set via inline style */
  gap: clamp(8px, 1.2vw, 16px);
  margin-bottom: clamp(12px, 1.5vh, 20px);
  flex: 1;
  min-height: 0; 
  overflow-y: auto;
  padding: 0; /* Remove asymmetric padding to match AntrianLoket */
  
  /* Custom scrollbar for premium look */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(33, 150, 243, 0.3);
    border-radius: 10px;
  }
  &::-webkit-scrollbar-thumb:hover {
    background: rgba(33, 150, 243, 0.5);
  }
}

.clinics-grid.is-compact {
  margin-bottom: 12px;
}

.clinic-box {
  background: var(--color-neutral-100);
  border: 2px solid var(--color-primary-200);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.12);
  display: flex;
  flex-direction: column;
  min-height: 200px; /* Prevent shrinking too much */
}

.clinic-box.is-compact {
  border-width: 1.5px;
}

.clinic-header-bar {
  background: linear-gradient(135deg, var(--color-primary-600) 0%, var(--color-primary-700) 100%);
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.clinic-box.is-compact .clinic-header-bar {
  padding: 8px 12px;
}

.clinic-title {
  font-size: clamp(14px, 1.15vw, 22px);
  font-weight: 800;
  color: var(--color-neutral-100);
  letter-spacing: 0.5px;
  text-transform: uppercase;
  line-height: 1.2;
  flex: 1;
}

.clinic-box.is-compact .clinic-title {
  font-size: 14px;
}

.clinic-count {
  background: rgba(255, 255, 255, 0.2) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 700;
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  gap: 4px;
}

.count-text {
  font-size: 18px;
  font-weight: 800;
}

.clinic-box.is-compact .count-text {
  font-size: 14px;
}

.clinic-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 20px;
  background: var(--color-primary-50);
}

.clinic-box.is-compact .clinic-content {
  padding: 8px 12px;
}

.tipe-layanan-section {
  margin-bottom: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex: 1;
}

.tipe-label {
  font-size: clamp(16px, 1.2vw, 22px);
  font-weight: 800;
  color: var(--color-primary-700);
  margin-bottom: 12px;
  letter-spacing: 1px;
  text-transform: uppercase;
  padding: clamp(6px, 0.5vw, 10px) clamp(12px, 0.8vw, 20px);
  background: var(--color-primary-200);
  border-radius: 8px;
  display: inline-block;
  align-self: center;
}

.clinic-box.is-compact .tipe-label {
  font-size: 13px;
  padding: 4px 10px;
  margin-bottom: 6px;
}

.empty-state-small {
  text-align: center;
  padding: 16px 0;
}

.clinic-box.is-compact .empty-state-small {
  padding: 4px 0;
}

.empty-text-small {
  font-size: 12px;
  color: var(--color-neutral-600);
  margin-top: 8px;
  font-weight: 500;
}

.current-section {
  text-align: center;
  margin-bottom: 12px;
}

.clinic-box.is-compact .current-section {
  margin-bottom: 4px;
}

.current-label {
  font-size: 16px;
  font-weight: 700;
  color: var(--color-primary-600);
  margin-bottom: 8px;
  letter-spacing: 1px;
  text-transform: uppercase;
}

.clinic-box.is-compact .current-label {
  font-size: 10px;
  margin-bottom: 2px;
}

.current-number {
  font-size: clamp(48px, 4.17vw, 80px);
  font-weight: 900;
  color: var(--color-neutral-900);
  letter-spacing: 4px;
  line-height: 1;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-variant-numeric: tabular-nums; /* Stable digits */
}

.clinic-box.is-compact .current-number {
  font-size: clamp(32px, 3vw, 48px);
  letter-spacing: 2px;
}

/* ========== FOOTER STATS ========== */
.footer-stats-bar {
  background: var(--color-neutral-100);
  border: 2px solid var(--color-primary-200);
  border-radius: 16px;
  padding: clamp(10px, 1.2vw, 16px) clamp(16px, 2.5vw, 40px); /* Responsive padding */
  display: flex;
  align-items: center;
  gap: 32px;
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.12);
  flex-shrink: 0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

.stat-info {
  text-align: left;
}

.stat-value {
  font-size: 40px;
  font-weight: 900;
  color: var(--color-neutral-900);
  line-height: 1;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-variant-numeric: tabular-nums; /* Stable digits */
}

.stat-label {
  font-size: 14px;
  color: var(--color-neutral-700);
  font-weight: 600;
  margin-top: 4px;
  opacity: 0.95;
}

.stat-divider {
  width: 2px;
  height: 60px;
  background: var(--color-primary-200);
}

.footer-message {
  flex: 1;
  text-align: right;
  font-size: 20px;
  font-weight: 600;
  color: var(--color-neutral-800);
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

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

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

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

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

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

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

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

@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;
  }
}

/* Animations */
@keyframes pulse-highlight {
  0%, 100% {
    box-shadow: 0 12px 32px rgba(33, 150, 243, 0.35);
  }
  50% {
    box-shadow: 0 12px 48px rgba(33, 150, 243, 0.55);
  }
}

@keyframes number-pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

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


/* Single View Optimizations */
.clinic-box.is-single-view {
  display: flex;
  flex-direction: column;
}

.clinic-box.is-single-view .clinic-header-bar {
  padding: 32px 40px;
}

.clinic-box.is-single-view .clinic-title {
  font-size: 56px; /* Massive title */
  text-align: center;
}

.clinic-box.is-single-view .clinic-count {
  padding: 8px 16px;
}

.clinic-box.is-single-view .count-text {
  font-size: 24px;
}

.clinic-box.is-single-view .clinic-content {
  padding: 40px;
  justify-content: space-evenly; /* Distribute vertical space */
}

.clinic-box.is-single-view .tipe-layanan-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1; /* Take up available space */
  justify-content: center;
}

.clinic-box.is-single-view .tipe-label {
  font-size: 32px; /* Much larger label */
  padding: 12px 24px;
  margin-bottom: 24px;
}

.clinic-box.is-single-view .current-label {
  font-size: 24px;
  margin-bottom: 16px;
}

.clinic-box.is-single-view .current-number {
  font-size: 180px; /* Enormous number */
  line-height: 1;
 margin: 20px 0;
}

.clinic-box.is-single-view .empty-text-small {
  font-size: 24px;
}

.clinic-box.is-single-view .v-icon {
  transform: scale(1.5); /* Scale up icons */
}

/* Responsive adjustment for short screens (laptops/small monitors) */
/* Responsive adjustment for short screens (laptops/small monitors) */
@media (max-height: 900px) {
  .hero-call-section {
    padding: 12px;
    margin-bottom: 8px;
    max-height: 25vh; /* Reduced from 35vh */
  }

  .call-label {
    font-size: 18px; /* Reduced from 20px */
    margin-bottom: 4px;
  }

  .call-number {
    font-size: 64px; /* Reduced from 80px */
    margin: 4px 0;
  }

  .call-clinic {
    font-size: 20px; /* Reduced from 24px */
  }
  
  .clinic-box {
    min-height: 140px; /* Reduced from 180px */
    border-width: 1.5px;
  }

  .clinic-header-bar {
    padding: 8px 12px;
  }

  .clinic-title {
    font-size: 14px;
  }

  .clinic-content {
    padding: 8px 12px;
  }

  .tipe-label {
    font-size: 11px;
    padding: 2px 6px;
    margin-bottom: 2px;
  }

  .current-label {
    font-size: 10px;
    margin-bottom: 0;
  }

  .current-number {
    font-size: clamp(32px, 2.5vw, 48px); /* Significantly reduced */
    letter-spacing: 2px;
  }

  .empty-state-small {
    padding: 4px 0;
  }

  .empty-text-small {
    font-size: 10px;
    margin-top: 2px;
  }
  
  /* Hide "Tidak Ada" text to save space */
  .empty-text-small {
    display: none;
  }
}

@media (max-height: 768px) {
  .antrian-display-container {
    padding: 8px;
  }

  .display-header {
    padding: 8px 12px;
    margin-bottom: 4px;
  }
  
  .logo-circle {
    width: 48px;
    height: 48px;
  }
  
  .header-logo {
    width: 36px;
    height: 36px;
  }
  
  .hospital-name {
    font-size: 20px;
  }
  
  .time-large {
    font-size: 32px;
  }
  
  .date-small {
    font-size: 12px;
    margin-top: 2px;
  }

  .hero-call-section {
    padding: 8px;
    margin-bottom: 4px;
    max-height: 20vh; /* Further reduced */
    border-radius: 12px;
  }

  .call-label {
    font-size: 14px;
    margin-bottom: 2px;
  }

  .call-number {
    font-size: 48px;
    margin: 2px 0;
  }

  .call-clinic {
    font-size: 16px;
  }
  
  .clinics-grid {
    gap: 6px;
    margin-bottom: 4px;
  }

  .clinic-box {
    min-height: 120px; /* Further reduced */
    border-radius: 10px;
    border-width: 1px;
  }
  
  .clinic-header-bar {
    padding: 6px 10px;
  }
  
  .clinic-count {
    height: 20px !important;
  }
  
  .clinic-title {
    font-size: 12px;
  }
  
  .clinic-content {
    padding: 4px 8px;
  }
  
  .tipe-label {
    font-size: 10px;
    padding: 2px 4px;
    margin-bottom: 2px;
    border-radius: 4px;
  }
  
  .current-label {
    font-size: 9px;
    margin-bottom: 0;
  }
  
  .current-number {
    font-size: 28px;
    letter-spacing: 1px;
  }
  
  .footer-stats-bar {
    padding: 6px 12px;
    gap: 12px;
    border-radius: 10px;
  }
  
  .stat-icon {
    width: 36px;
    height: 36px;
    border-radius: 8px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .stat-label {
    font-size: 10px;
  }
  
  .footer-message {
    font-size: 12px;
  }
}

</style>

