<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 -->
    <div v-if="currentCalledQueue" class="hero-call-section">
      <div class="call-label">
        <v-icon size="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 }}</div>
    </div>

    <!-- Main Grid - Display Ruang -->
    <div class="clinics-grid" :style="gridStyle">
      <div
        v-for="ruang in displayedRuang"
        :key="`${ruang.kodeKlinik}-${ruang.nomorRuang}`"
        class="clinic-box"
        :class="{ 'is-single-view': displayedRuang.length === 1 }"
      >
        <!-- Clinic Header -->
        <div class="clinic-header-bar">
          <span class="clinic-title">{{ ruang.namaKlinik }} - {{ ruang.namaRuang }}</span>
          <v-chip size="small" class="clinic-count">
            <v-icon size="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="24" color="grey-lighten-3">mdi-clock-outline</v-icon>
              <p class="empty-text-small">Tidak Ada Antrian</p>
            </div>
          </div>

          <!-- Divider -->
          <v-divider class="my-3" />

          <!-- Tindakan Section -->
          <div class="tipe-layanan-section">
            <div class="tipe-label">TINDAKAN</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="24" color="grey-lighten-3">mdi-clock-outline</v-icon>
              <p class="empty-text-small">Tidak Ada Antrian</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.waiting }}</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 { 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 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
  
  // Get most recently called patient (status di-loket)
  // Sort by lastCalledAt if available, otherwise by createdAt
  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]
    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
  }
})

// Dynamic grid logic: divide total by 2 to balance across rows, cap at 5 for larger cards
// Meniru logika AntrianLoket
const gridColumns = computed(() => {
  const total = displayedRuang.value.length
  if (total <= 1) return 1
  if (total <= 5) return total 
  return Math.min(5, Math.ceil(total / 2))
})

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

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.150.100:8084/api/v1/ws'

// 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}`
  console.log('🆔 Using default client ID (no screen number):', clientId)
  return clientId
})

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

// Initialize WebSocket connection
const initWebSocket = () => {
  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)
      console.log('📨 Message type:', typeof data)
      
      // Backend mengirim data langsung atau dalam wrapper
      // Handle both cases
      let messageData = data
      
      // Jika data ada dalam property 'data', ambil itu
      if (data && typeof data === 'object' && data.data) {
        messageData = data.data
        console.log('📦 Extracted data from wrapper:', messageData)
      }
      
      // Handle patient called message - format: { noantrian: "AA001", tipeLayanan: "Pemeriksaan Awal" }
      if (messageData && messageData.noantrian) {
        const nomorAntrian = messageData.noantrian
        const tipeLayanan = messageData.tipeLayanan || null // "Pemeriksaan Awal" atau "Tindakan"
        console.log('✅ Processing patient call for nomor antrian:', nomorAntrian, 'tipeLayanan:', tipeLayanan)
        
        // Find patient by nomor antrian (check both noAntrian and barcode)
        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) {
          // Update patient status to 'di-loket' (called) dan update tipeLayanan serta tracking flags
          const oldPatient = { ...queueStore.allPatients[patientIndex] }
          const updateData = {
            ...queueStore.allPatients[patientIndex],
            status: 'di-loket',
            lastCalledAt: new Date().toISOString(),
            lastCalledTipeLayanan: tipeLayanan,
          }
          
          // Update tipeLayanan agar pasien muncul di kolom yang sesuai
          if (tipeLayanan) {
            updateData.tipeLayanan = tipeLayanan
          }
          
          // Update tracking flags berdasarkan tipeLayanan
          if (tipeLayanan === 'Pemeriksaan Awal') {
            updateData.calledPemeriksaanAwal = true
          } else if (tipeLayanan === 'Tindakan') {
            updateData.calledTindakan = true
          }
          
          queueStore.allPatients[patientIndex] = updateData
          
          console.log('✅ Patient data updated in store based on nomor antrian:', nomorAntrian)
          console.log('📊 Old:', { status: oldPatient.status, tipeLayanan: oldPatient.tipeLayanan })
          console.log('📊 New:', { 
            status: updateData.status, 
            tipeLayanan: updateData.tipeLayanan,
            calledPemeriksaanAwal: updateData.calledPemeriksaanAwal,
            calledTindakan: updateData.calledTindakan
          })
        } else {
          // If patient doesn't exist, log warning
          console.warn('⚠️ Patient not found in store with nomor antrian:', nomorAntrian)
          console.log('📋 Available patients:', klinikPatients.value.map(p => ({
            noAntrian: p.noAntrian?.split(" |")[0],
            barcode: p.barcode,
            kodeKlinik: p.kodeKlinik
          })))
        }
      } else {
        console.log('ℹ️ Message format is invalid or missing noantrian:', messageData)
      }
    },
    onOpen: () => {
      console.log('✅ Anjungan WebSocket connected successfully!')
      console.log('🆔 Connected as:', anjunganClientId.value)
      isConnected.value = true
    },
    onClose: () => {
      console.log('⚠️ Anjungan WebSocket closed')
      isConnected.value = false
    },
    onError: (error) => {
      console.error('❌ Anjungan WebSocket error:', error)
      isConnected.value = false
    },
    reconnectInterval: 3000,
    maxReconnectAttempts: 10,
  })

  // Watch connection status
  if (wsInstance.isConnected) {
    watch(wsInstance.isConnected, (connected) => {
      isConnected.value = connected
    })
  }

  return wsInstance
}

onMounted(() => {
  // Redirect to index if klinik not found
  if (!klinikData.value) {
    navigateTo('/anjungan/antrianklinikruang')
    return
  }
  
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
  
  // Initialize and connect WebSocket
  if (kodeKlinik.value) {
    wsInstance = initWebSocket()
    if (wsInstance) {
      wsInstance.connect()
      console.log('🚀 WebSocket connection initiated')
    }
  }
})

onUnmounted(() => {
  if (timeInterval) clearInterval(timeInterval)
  if (wsInstance) {
    wsInstance.disconnect()
    console.log('🔌 WebSocket disconnected')
  }
})

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

<style scoped lang="scss">
.antrian-display-container {
  background: var(--color-neutral-300);
  width: 100vw;
  height: 100vh;
  padding: 24px;
  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: 16px;
  padding: 24px 40px;
  margin-bottom: 20px;
  box-shadow: 0 8px 24px rgba(33, 150, 243, 0.3);
}

.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);
}

.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: 32px;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 12px 32px rgba(33, 150, 243, 0.35);
  animation: pulse-highlight 2s ease-in-out infinite;
}

.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: 140px;
  font-weight: 900;
  color: var(--color-neutral-100);
  margin: 16px 0;
  letter-spacing: 8px;
  line-height: 1;
  text-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  animation: number-pulse 1.5s ease-in-out infinite;
}

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

/* ========== CLINICS GRID ========== */
.clinics-grid {
  display: grid;
  /* grid-template-columns set via inline style */
  gap: 16px;
  margin-bottom: 20px;
  flex: 1;
  min-height: 0; /* Allow ensuring internal scroll if needed, but we aim for fit */
}

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

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

.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-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-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 20px;
  background: var(--color-primary-50);
}

.tipe-layanan-section {
  margin-bottom: 8px;
}

.tipe-label {
  font-size: clamp(14px, 1.04vw, 20px);
  font-weight: 700;
  color: var(--color-primary-700);
  margin-bottom: 12px;
  letter-spacing: 1px;
  text-transform: uppercase;
  padding: clamp(4px, 0.42vw, 8px) clamp(8px, 0.63vw, 12px);
  background: var(--color-primary-200);
  border-radius: 8px;
  display: inline-block;
}

.empty-state-small {
  text-align: center;
  padding: 16px 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;
}

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

.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);
}

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

.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);
}

.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 */
}
</style>

