<template>
  <div>
    <!-- Header -->
    <PageHeader
      icon="mdi-door-open"
      :title="`Admin Klinik Ruang - ${klinikData?.namaKlinik || ''}`"
      :subtitle="currentDate"
      :show-add-button="false"
      theme="primary"
    />

    <div class="admin-klinik-ruang-container">
      <!-- Global Search and Actions -->
    <div class="global-search-section sticky-search-section">
      <div class="search-actions-row">
        <v-text-field
          v-model="globalSearchQuery"
          placeholder="Cari pasien di semua ruang (barcode, nomor antrian, nama...)"
          density="compact"
          hide-details
          class="global-search-field"
          prepend-inner-icon="mdi-magnify"
          variant="outlined"
          clearable
        >
          <template v-slot:append-inner v-if="globalSearchQuery">
            <v-chip size="small" color="primary-600" class="text-white">
              {{ getGlobalSearchResults().length }} hasil
            </v-chip>
          </template>
        </v-text-field>
        <v-btn
          class="btn-pindah-pasien"
          variant="flat"
          size="default"
          @click="showKelolaPasienDialog = true"
        >
          <v-icon start size="18">mdi-account-cog</v-icon>
          Kelola Pasien
        </v-btn>
      </div>
    </div>

    <!-- Rooms Grid -->
    <div class="rooms-grid-wrapper mt-4">
      <div class="rooms-grid">
        <v-card
          v-for="ruang in ruangList"
          :key="`${klinikData?.kodeKlinik}-${ruang.nomorRuang}`"
          class="room-card"
          elevation="0"
        >
        <v-card-title class="room-header">
          <div class="room-title">
            <v-icon color="warning-600" class="mr-2">mdi-door</v-icon>
            <span>{{ ruang.namaRuang }}</span>
            <v-chip size="small" class="ml-2" color="warning-600">
              Kamar : R.{{ ruang.nomorRuang }}
            </v-chip>
          </div>
        </v-card-title>

        <v-card-text class="pa-4">
          <!-- Current Processing Patient -->
          <div v-if="getCurrentProcessingForRoom(ruang)" class="current-patient-section mb-4">
            <div class="current-patient-header mb-2">
              <div class="section-label-small">SEDANG DIPROSES</div>
              <div class="action-icon-buttons">
                <v-btn
                  class="action-icon-btn text-white"
                  color="danger-600"
                  variant="flat"
                  size="small"
                  @click="handlePatientAction(ruang, 'pending')"
                >
                  <v-icon size="16">mdi-pause</v-icon>
                  <span class="btn-label">Pending</span>
                </v-btn>
                <v-btn
                  class="action-icon-btn text-white"
                  color="success-600"
                  variant="flat"
                  size="small"
                  @click="handlePatientAction(ruang, 'selesai')"
                >
                  <v-icon size="16">mdi-check</v-icon>
                  <span class="btn-label">Selesai</span>
                </v-btn>
              </div>
            </div>
            <div class="current-patient-info">
              <div class="patient-number-large">
                {{ getCurrentProcessingForRoom(ruang)?.noAntrian?.split(" |")[0] || '-' }}
              </div>
              <div class="patient-details">
                <div class="action-grid">
                  <v-btn
                    class="text-white"
                    color="primary-600"
                    variant="flat"
                    size="small"
                    @click="handleCallPatientByTipe(ruang, 'Pemeriksaan Awal')"
                  >
                    <v-icon start size="18">mdi-bullhorn</v-icon>
                    Pemeriksaan Awal
                  </v-btn>
                  <v-btn
                    class="text-white"
                    color="secondary-600"
                    variant="flat"
                    size="small"
                    :disabled="!getCurrentProcessingForRoom(ruang)?.calledPemeriksaanAwal"
                    @click="handleCallPatientByTipe(ruang, 'Tindakan')"
                  >
                    <v-icon start size="18">mdi-bullhorn</v-icon>
                    Panggil Pemeriksaan
                  </v-btn>
                </div>
              </div>
            </div>
          </div>

          <!-- Empty State for Current Processing -->
          <div v-else class="empty-current mb-4">
            <div class="section-label-small mb-2">SEDANG DIPROSES</div>
            <div class="empty-text">Tidak ada pasien yang diproses</div>
          </div>

          <!-- Daftar Pasien -->
          <div v-if="getAllPatientsForRoom(ruang).length > 0" class="patient-list-section">
            <div class="section-label-small mb-2">
              <div class="d-flex align-center justify-space-between">
                <div>
                  DAFTAR PASIEN
                  <v-chip size="x-small" color="warning-600" class="ml-2">
                    {{ getFilteredAndSortedPatientsForRoom(ruang).length }}
                  </v-chip>
                </div>
                <div class="filter-sort-actions">
                  <v-btn
                    size="small"
                    variant="outlined"
                    class="btn-filter"
                    @click="openFilterDialog(ruang)"
                  >
                    <v-icon start size="16">mdi-filter</v-icon>
                    Filter
                    <v-chip
                      v-if="getActiveFilterCount(ruang) > 0"
                      size="x-small"
                      color="primary-600"
                      class="text-white ml-2"
                    >
                      {{ getActiveFilterCount(ruang) }}
                    </v-chip>
                  </v-btn>
                </div>
              </div>
            </div>
            
            <!-- Patient List -->
            <div v-if="getFilteredAndSortedPatientsForRoom(ruang).length > 0" class="patient-queue-list">
              <v-tooltip
                v-for="patient in paginatedAllPatients(ruang)"
                :key="patient.no"
                :text="patient.status === 'pending' ? 'Pasien Pending' : ''"
                :disabled="patient.status !== 'pending'"
              >
                <template v-slot:activator="{ props }">
                  <div
                    v-bind="props"
                    :class="getPatientCardClass(patient, ruang)"
                  >
                    <!-- Top Row: Number, Status Icons, and Actions -->
                    <div class="patient-card-header-row">
                      <div class="patient-card-left-group">
                        <div class="patient-queue-number-wrapper">
                          <div class="patient-queue-number">
                            {{ patient.noAntrian?.split(" |")[0] || patient.barcode || '-' }}
                          </div>
                          <div class="patient-status-icons">
                            <div 
                              v-if="patient.status === 'pending'"
                              class="status-icon-wrapper status-icon-pending"
                            >
                              <v-icon 
                                color="var(--color-danger-600)"
                                size="14"
                                class="status-icon"
                              >
                                mdi-pause
                              </v-icon>
                            </div>
                            <div 
                              v-if="(patient.fastTrack ?? '').toString().trim().toUpperCase() === 'YA'"
                              class="status-icon-wrapper status-icon-fast-track"
                            >
                              <v-icon 
                                color="#E53935"
                                size="14"
                                class="status-icon"
                              >
                                mdi-flash
                              </v-icon>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="patient-card-right-group">
                        <div class="patient-queue-actions">
                          <v-btn
                            icon
                            size="small"
                            variant="text"
                            @click="showPatientDetail(patient)"
                          >
                            <v-icon size="18">mdi-eye</v-icon>
                            <v-tooltip activator="parent">Lihat Detail</v-tooltip>
                          </v-btn>
                          <v-btn
                            v-if="patient.no !== getCurrentProcessingForRoom(ruang)?.no"
                            class="text-white"
                            color="success-600"
                            variant="flat"
                            size="small"
                            @click="patient.status === 'pending' ? handleProcessPendingPatient(ruang, patient) : handleProcessPatient(ruang, patient)"
                          >
                            <v-icon start size="16">mdi-play</v-icon>
                            Proses
                          </v-btn>
                        </div>
                      </div>
                    </div>

                    <!-- Bottom Row: Status Chips -->
                    <div class="patient-card-bottom-row" v-if="patient.calledPemeriksaanAwal || patient.calledTindakan">
                      <div class="patient-queue-status-chips">
                        <v-chip
                          v-if="patient.calledPemeriksaanAwal"
                          size="small"
                          color="primary-600"
                          variant="flat"
                          class="status-chip status-chip-pawal"
                        >
                          <v-icon start size="16">mdi-check-circle</v-icon>
                          P.Awal
                        </v-chip>
                        <v-chip
                          v-if="patient.calledTindakan"
                          size="small"
                          color="secondary-600"
                          variant="flat"
                          class="status-chip status-chip-tindakan"
                        >
                          <v-icon start size="16">mdi-check-circle</v-icon>
                          Pemeriksaan
                        </v-chip>
                      </div>
                    </div>
                  </div>
                </template>
              </v-tooltip>
              
              <!-- Pagination -->
              <v-pagination
                v-if="getFilteredAndSortedPatientsForRoom(ruang).length > 10"
                v-model="pendingPage[ruang.nomorRuang]"
                :length="Math.ceil(getFilteredAndSortedPatientsForRoom(ruang).length / 10)"
                :total-visible="5"
                size="small"
                class="mt-3"
                @update:model-value="() => {}"
              />
            </div>
            
            <!-- Empty State for Filtered Results -->
            <div v-else class="empty-filtered-state">
              <v-icon size="48" color="neutral-500">mdi-filter-remove</v-icon>
              <div class="empty-text mt-3">
                Tidak ada pasien yang sesuai dengan filter
              </div>
              <div class="empty-text-small">
                Coba ubah opsi sorting atau kata kunci pencarian
              </div>
            </div>
          </div>
        </v-card-text>
      </v-card>
      </div>
    </div>

    <!-- Dialog Kelola Pasien -->
    <v-dialog v-model="showKelolaPasienDialog" max-width="800px" persistent>
      <v-card class="dialog-card">
        <v-card-title class="dialog-header dialog-header-warning">
          <span class="headline-4">Kelola Pasien</span>
          <v-btn icon variant="text" size="small" class="btn-close" @click="closeKelolaPasienDialog">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>
        <v-divider />
        <v-card-text class="dialog-content">
          <!-- Step 1: Pilih Pasien -->
          <div v-if="!selectedPatientForKelola" class="pindah-ruang-step">
            <div class="step-title mb-3">
              <v-icon color="primary-600" class="mr-2">mdi-account</v-icon>
              <span class="headline-5">Pilih Pasien</span>
            </div>
            <v-text-field
              v-model="searchPatientQuery"
              placeholder="Cari pasien (barcode, nomor antrian, nama...)"
              density="compact"
              hide-details
              class="mb-3"
              prepend-inner-icon="mdi-magnify"
              variant="outlined"
              clearable
            />
            <div class="patient-selection-list">
              <div
                v-for="patient in getAvailablePatientsForKelola()"
                :key="patient.no"
                class="patient-selection-card"
                :class="{ 'patient-selection-card-selected': selectedPatientForKelola?.no === patient.no }"
                @click="selectedPatientForKelola = patient"
              >
                <div class="patient-selection-info">
                  <div class="patient-selection-number">
                    {{ patient.noAntrian?.split(" |")[0] || patient.barcode || '-' }}
                  </div>
                  <div class="patient-selection-details">
                    <div class="patient-selection-room">
                      <v-icon size="16" class="mr-1">mdi-door</v-icon>
                      {{ patient.ruang || '-' }} (R.{{ patient.nomorRuang || '-' }})
                    </div>
                  </div>
                </div>
                <v-icon v-if="selectedPatientForKelola?.no === patient.no" color="primary-600" size="24">
                  mdi-check-circle
                </v-icon>
              </div>
              <div v-if="getAvailablePatientsForKelola().length === 0" class="empty-patient-list">
                <v-icon size="48" color="neutral-500">mdi-account-off</v-icon>
                <div class="empty-text mt-3">
                  Tidak ada pasien yang tersedia
                </div>
              </div>
            </div>
          </div>

          <!-- Step 2: Pilih Aksi -->
          <div v-else-if="!selectedAction" class="pindah-ruang-step">
            <div class="step-title mb-3">
              <v-icon color="primary-600" class="mr-2">mdi-cog</v-icon>
              <span class="headline-5">Pilih Aksi</span>
            </div>
            <div class="selected-patient-simple mb-4">
              <div class="selected-patient-simple-text">
                <span class="selected-patient-simple-label">Pasien:</span>
                <span class="selected-patient-simple-value">
                  {{ selectedPatientForKelola?.noAntrian?.split(" |")[0] || selectedPatientForKelola?.barcode || '-' }}
                </span>
                <span class="selected-patient-simple-room">
                  ({{ selectedPatientForKelola?.ruang || '-' }})
                </span>
              </div>
              <v-btn
                size="small"
                variant="text"
                color="primary-600"
                @click="selectedPatientForKelola = null"
              >
                <v-icon start size="16">mdi-arrow-left</v-icon>
                Ubah
              </v-btn>
            </div>
            <div class="action-selection-grid">
              <div
                class="action-selection-card"
                @click="selectedAction = 'pindah-ruang'"
              >
                <v-icon size="32" color="primary-600" class="mb-2">mdi-swap-horizontal</v-icon>
                <div class="action-selection-name">Pindah Ruang</div>
              </div>
              <div
                class="action-selection-card"
                @click="selectedAction = 'pindah-klinik'"
              >
                <v-icon size="32" color="secondary-600" class="mb-2">mdi-hospital-building</v-icon>
                <div class="action-selection-name">Pindah Klinik</div>
              </div>
              <div
                class="action-selection-card"
                @click="selectedAction = 'konsultasi'"
              >
                <v-icon size="32" color="success-600" class="mb-2">mdi-stethoscope</v-icon>
                <div class="action-selection-name">Konsultasi</div>
              </div>
            </div>
          </div>

          <!-- Step 3: Pilih Ruang/Klinik Tujuan -->
          <div v-else class="pindah-ruang-step">
            <div class="step-title mb-3">
              <v-icon color="primary-600" class="mr-2">mdi-door</v-icon>
              <span class="headline-5">
                {{ selectedAction === 'pindah-ruang' ? 'Pilih Ruang Tujuan' : 'Pilih Klinik Ruang Tujuan' }}
              </span>
            </div>
            <div class="selected-patient-simple mb-4">
              <div class="selected-patient-simple-text">
                <span class="selected-patient-simple-label">Pasien:</span>
                <span class="selected-patient-simple-value">
                  {{ selectedPatientForKelola?.noAntrian?.split(" |")[0] || selectedPatientForKelola?.barcode || '-' }}
                </span>
                <span class="selected-patient-simple-room">
                  ({{ selectedPatientForKelola?.ruang || '-' }})
                </span>
              </div>
              <v-btn
                size="small"
                variant="text"
                color="primary-600"
                @click="selectedAction = null"
              >
                <v-icon start size="16">mdi-arrow-left</v-icon>
                Kembali
              </v-btn>
            </div>
            
            <!-- Pilih Ruang (untuk Pindah Ruang) -->
            <div v-if="selectedAction === 'pindah-ruang'" class="ruang-selection-grid">
              <div
                v-for="ruangOption in ruangList"
                :key="ruangOption.nomorRuang"
                class="ruang-selection-card"
                :class="{
                  'ruang-selection-card-selected': selectedRuangBaru?.nomorRuang === ruangOption.nomorRuang,
                  'ruang-selection-card-disabled': ruangOption.nomorRuang === selectedPatientForKelola?.nomorRuang
                }"
                @click="ruangOption.nomorRuang !== selectedPatientForKelola?.nomorRuang && (selectedRuangBaru = ruangOption)"
              >
                <div class="ruang-selection-content">
                  <div class="ruang-selection-name">{{ ruangOption.namaRuang }}</div>
                  <div class="ruang-selection-number">Ruang {{ ruangOption.nomorRuang }}</div>
                  <v-chip
                    v-if="ruangOption.nomorRuang === selectedPatientForKelola?.nomorRuang"
                    size="x-small"
                    color="neutral-500"
                    class="mt-2"
                  >
                    Saat Ini
                  </v-chip>
                </div>
              </div>
            </div>
            
            <!-- Pilih Klinik Ruang (untuk Pindah Klinik dan Konsultasi) -->
            <div v-else>
              <v-text-field
                v-model="klinikRuangSearch"
                placeholder="Cari Klinik Ruang..."
                prepend-inner-icon="mdi-magnify"
                variant="outlined"
                density="compact"
                hide-details
                class="mb-4"
                clearable
              />
              
              <v-expansion-panels v-model="activePanel" class="expansion-panels">
                <v-expansion-panel
                  v-for="klinikRuang in filteredKlinikRuang"
                  :key="klinikRuang.kodeKlinik"
                  :value="klinikRuang.kodeKlinik"
                  class="expansion-panel"
                >
                  <v-expansion-panel-title class="expansion-title">
                    <div class="expansion-header">
                      <v-chip size="small" color="secondary-600" class="mr-2">
                        {{ klinikRuang.kodeKlinik }}
                      </v-chip>
                      <span class="body-2 text-semibold">{{ klinikRuang.namaKlinik }}</span>
                    </div>
                    <template #actions>
                      <v-chip size="x-small" variant="outlined">
                        {{ klinikRuang.ruangList?.length || 0 }} Ruang
                      </v-chip>
                    </template>
                  </v-expansion-panel-title>

                  <v-expansion-panel-text>
                    <div class="ruang-selection-grid p-2">
                      <div
                        v-for="ruang in klinikRuang.ruangList"
                        :key="ruang.nomorRuang"
                        class="ruang-selection-card"
                        :class="{
                          'ruang-selection-card-selected': selectedKlinikRuangBaru?.kodeKlinik === klinikRuang.kodeKlinik && selectedKlinikRuangBaru?.nomorRuang === ruang.nomorRuang,
                          'ruang-selection-card-disabled': klinikRuang.kodeKlinik === selectedPatientForKelola?.kodeKlinik && ruang.nomorRuang === selectedPatientForKelola?.nomorRuang
                        }"
                        @click="!(klinikRuang.kodeKlinik === selectedPatientForKelola?.kodeKlinik && ruang.nomorRuang === selectedPatientForKelola?.nomorRuang) && (selectedKlinikRuangBaru = { kodeKlinik: klinikRuang.kodeKlinik, namaKlinik: klinikRuang.namaKlinik, nomorRuang: ruang.nomorRuang, namaRuang: ruang.namaRuang, nomorScreen: ruang.nomorScreen })"
                      >
                        <div class="ruang-selection-content">
                          <div class="ruang-selection-name">{{ ruang.namaRuang }}</div>
                          <div class="ruang-selection-number">Ruang {{ ruang.nomorRuang }}</div>
                          <v-chip
                            v-if="klinikRuang.kodeKlinik === selectedPatientForKelola?.kodeKlinik && ruang.nomorRuang === selectedPatientForKelola?.nomorRuang"
                            size="x-small"
                            color="neutral-500"
                            class="mt-2"
                          >
                            Saat Ini
                          </v-chip>
                          <v-icon 
                            v-if="selectedKlinikRuangBaru?.kodeKlinik === klinikRuang.kodeKlinik && selectedKlinikRuangBaru?.nomorRuang === ruang.nomorRuang"
                            class="mt-2"
                            size="18" 
                            color="primary-600"
                          >
                            mdi-check-circle
                          </v-icon>
                        </div>
                      </div>
                    </div>
                  </v-expansion-panel-text>
                </v-expansion-panel>
              </v-expansion-panels>
            </div>
          </div>
        </v-card-text>
        <v-card-actions class="dialog-actions">
          <v-spacer />
          <v-btn variant="outlined" class="btn-cancel" @click="closeKelolaPasienDialog">
            <v-icon left size="18">mdi-close</v-icon>
            Batal
          </v-btn>
          <v-btn
            v-if="selectedAction === 'pindah-ruang' && selectedPatientForKelola && selectedRuangBaru"
            variant="flat"
            class="btn-submit"
            @click="confirmPindahRuang"
          >
            <v-icon left size="18">mdi-swap-horizontal</v-icon>
            Pindah Ruang
          </v-btn>
          <v-btn
            v-if="selectedAction === 'pindah-klinik' && selectedPatientForKelola && selectedKlinikRuangBaru"
            variant="flat"
            class="btn-submit"
            @click="confirmPindahKlinik"
          >
            <v-icon left size="18">mdi-hospital-building</v-icon>
            Pindah Klinik
          </v-btn>
          <v-btn
            v-if="selectedAction === 'konsultasi' && selectedPatientForKelola && selectedKlinikRuangBaru"
            variant="flat"
            class="btn-submit"
            @click="confirmKonsultasi"
          >
            <v-icon left size="18">mdi-stethoscope</v-icon>
            Konsultasi
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Dialog Patient Detail -->
    <!-- Dialog Patient Detail -->
    <v-dialog v-model="showDetailDialog" max-width="500px" persistent>
      <v-card class="patient-detail-card">
        <v-card-title class="dialog-header">
          <span class="headline-5 font-weight-bold">Detail Pasien</span>
          <v-btn icon variant="text" size="small" class="btn-close" @click="showDetailDialog = false">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>
        
        <v-card-text class="dialog-content pa-0" v-if="selectedPatientDetail">
          <!-- Hero Section: Queue Number -->
          <div class="patient-hero-section">
            <div class="hero-label">NOMOR ANTRIAN</div>
            <div class="hero-number">{{ selectedPatientDetail.noAntrian?.split(" |")[0] || '-' }}</div>
            <div class="hero-status-wrapper d-flex justify-center ga-2 mt-2">
              <v-chip 
                size="small" 
                :color="getStatusColor(selectedPatientDetail.status)"
                variant="flat"
                class="status-chip-hero"
              >
                {{ getStatusLabel(selectedPatientDetail.status) }}
              </v-chip>
              <v-chip 
                size="small" 
                :color="selectedPatientDetail.fastTrack === 'YA' ? 'danger-600' : 'neutral-200'"
                :class="selectedPatientDetail.fastTrack === 'YA' ? 'text-white' : 'text-neutral-600'"
                variant="flat"
                class="status-chip-hero"
              >
                {{ selectedPatientDetail.fastTrack === 'YA' ? 'FAST TRACK' : 'REGULER' }}
              </v-chip>
            </div>
          </div>



          <!-- Main Info Grid -->
          <div class="patient-info-container px-5 py-4">
            <div class="info-grid">
               <!-- Row 1 -->
               <div class="info-item">
                  <div class="info-label">No. Rekam Medis</div>
                  <div class="info-value">{{ selectedPatientDetail.noRM || '-' }}</div>
               </div>
               <div class="info-item text-right">
                  <div class="info-label">Jenis Pembayaran</div>
                  <div class="info-value">{{ selectedPatientDetail.pembayaran || '-' }}</div>
               </div>

               <!-- Row 2 -->
               <div class="info-item">
                 <div class="info-label">Barcode / NIK</div>
                 <div class="info-value">{{ selectedPatientDetail.barcode || '-' }}</div>
               </div>
               <div class="info-item text-right">
                 <div class="info-label">Jam Panggil</div>
                 <div class="info-value">
                    {{ selectedPatientDetail.jamPanggil ? (selectedPatientDetail.jamPanggil.includes('T') ? selectedPatientDetail.jamPanggil.split('T')[1].substring(0, 5) : selectedPatientDetail.jamPanggil.substring(0, 5)) : '-' }}
                 </div>
               </div>
               
                <!-- Row 3 -->
                <div class="info-item" v-if="selectedPatientDetail.referencePatient">
                   <div class="info-label">Nomor Antrian Loket</div>
                   <div class="info-value text-primary-600">
                     <v-icon size="14" class="mr-1" color="primary-600">mdi-link</v-icon>
                     {{ selectedPatientDetail.referencePatient }}
                   </div>
                </div>
                <div class="info-item" v-if="selectedPatientDetail.fastTrack === 'YA'">
                   <!-- Empty placeholder if we want to keep grid symmetry, or just leave it -->
                </div>

                <!-- Row 4 (Removed Fast Track from grid) -->
             </div>

            <!-- Service Actions -->
            <div class="service-actions-section mt-4">
              <div class="section-label-small mb-3">LAYANAN & PANGGILAN</div>
              <div class="service-actions-grid">
                <div 
                  class="service-action-card"
                  :class="{ 'active': selectedPatientDetail.calledPemeriksaanAwal }"
                  @click="toggleLayananStatus('Pemeriksaan Awal')"
                >
                  <div class="action-icon-wrapper color-primary">
                    <v-icon size="20">mdi-monitor-dashboard</v-icon>
                  </div>
                  <div class="action-content">
                    <div class="action-title">Pemeriksaan Awal</div>
                    <div class="action-status">
                      {{ selectedPatientDetail.calledPemeriksaanAwal ? 'Sudah Dipanggil' : 'Belum Dipanggil' }}
                    </div>
                  </div>
                  <v-icon v-if="selectedPatientDetail.calledPemeriksaanAwal" color="primary" class="check-icon">mdi-check-circle</v-icon>
                </div>

                <div 
                  class="service-action-card"
                  :class="{ 'active': selectedPatientDetail.calledTindakan }"
                  @click="toggleLayananStatus('Tindakan')"
                >
                   <div class="action-icon-wrapper color-secondary">
                    <v-icon size="20">mdi-stethoscope</v-icon>
                  </div>
                  <div class="action-content">
                    <div class="action-title">Pemeriksaan Dokter</div>
                    <div class="action-status">
                      {{ selectedPatientDetail.calledTindakan ? 'Sudah Dipanggil' : 'Belum Dipanggil' }}
                    </div>
                  </div>
                  <v-icon v-if="selectedPatientDetail.calledTindakan" color="secondary" class="check-icon">mdi-check-circle</v-icon>
                </div>
              </div>
            </div>


          </div>
        </v-card-text>
        <v-divider />
        <v-card-actions class="dialog-actions pa-4">
          <v-btn
            block
            variant="flat"
            color="neutral-200"
            class="btn-close-large text-neutral-800"
            height="44"
            @click="showDetailDialog = false"
          >
            Tutup
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Filter Dialog -->
    <v-dialog
      v-for="ruang in ruangList"
      :key="`filter-${ruang.nomorRuang}`"
      :model-value="showFilterDialog[ruang.nomorRuang]"
      @update:model-value="(val) => showFilterDialog[ruang.nomorRuang] = val"
      max-width="600px"
      persistent
    >
      <v-card class="dialog-card filter-dialog-card">
        <v-card-title class="dialog-header">
          <span class="headline-4">Semua Filter</span>
          <v-btn icon variant="text" size="small" class="btn-close" @click="closeFilterDialog(ruang)">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>
        <v-divider />
        <v-card-text class="dialog-content filter-dialog-content">
          <!-- Pemeriksaan Awal Filter -->
          <div class="filter-section">
            <div class="filter-section-header">
              <span class="filter-section-title">Pemeriksaan Awal</span>
            </div>
            <div class="filter-chip-group">
              <v-chip
                v-for="option in filterOptionsList.pemeriksaanAwal"
                :key="`pawal-${option.value}`"
                :class="{ 'active-chip': filterOptions[ruang.nomorRuang]?.pemeriksaanAwal === option.value }"
                class="filter-chip"
                @click="filterOptions[ruang.nomorRuang].pemeriksaanAwal = option.value"
              >
                {{ option.title }}
              </v-chip>
            </div>
          </div>

          <!-- Tindakan Filter -->
          <div class="filter-section">
            <div class="filter-section-header">
              <span class="filter-section-title">Tindakan</span>
            </div>
            <div class="filter-chip-group">
              <v-chip
                v-for="option in filterOptionsList.tindakan"
                :key="`tindakan-${option.value}`"
                :class="{ 'active-chip': filterOptions[ruang.nomorRuang]?.tindakan === option.value }"
                class="filter-chip"
                @click="filterOptions[ruang.nomorRuang].tindakan = option.value"
              >
                {{ option.title }}
              </v-chip>
            </div>
          </div>
        </v-card-text>
        <v-card-actions class="dialog-actions">
          <v-btn
            variant="text"
            class="btn-reset-filter"
            @click="resetFilters(ruang)"
          >
            <v-icon left size="18">mdi-refresh</v-icon>
            Reset
          </v-btn>
          <v-spacer />
          <v-btn variant="outlined" class="btn-cancel" @click="closeFilterDialog(ruang)">
            <v-icon left size="18">mdi-close</v-icon>
            Batal
          </v-btn>
          <v-btn variant="flat" class="btn-submit" @click="applyFilters(ruang)">
            <v-icon left size="18">mdi-check</v-icon>
            Terapkan
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Snackbar -->
    <AppSnackbar
      v-model="snackbar"
      :message="snackbarText"
      :color="snackbarColor"
    />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useQueueStore } from '@/stores/queueStore';
import { useMasterStore } from '@/stores/masterStore';
import { useClinicStore } from '@/stores/clinicStore';
import { useRuangStore } from '@/stores/ruangStore';
import PageHeader from '@/components/common/PageHeader.vue';
import PatientCard from '@/components/features/queue/PatientCard.vue';
import AppSnackbar from '@/components/common/AppSnackbar.vue';
import { useWebSocket } from '@/composables/useWebSocket';
import { useThermalPrint } from '@/composables/useThermalPrint';

const route = useRoute();
const router = useRouter();
const queueStore = useQueueStore();
const masterStore = useMasterStore();
const clinicStore = useClinicStore();
const ruangStore = useRuangStore();

const kodeKlinik = computed(() => {
  const kode = route.params.kodeKlinik;
  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 ruangData = masterStore.ruangData || [];
  
  // Filter by kodeKlinik AND jenisLayanan if provided (to differentiate Reguler vs Eksekutif)
  let klinikRuang;
  if (jenisLayanan.value) {
    klinikRuang = ruangData.find(r => r.kodeKlinik === kode && r.jenisLayanan === jenisLayanan.value);
  } else {
    // Fallback: just use kodeKlinik (for backward compatibility)
    klinikRuang = ruangData.find(r => r.kodeKlinik === kode);
  }
  
  if (klinikRuang) {
    return {
      kodeKlinik: klinikRuang.kodeKlinik,
      namaKlinik: klinikRuang.namaKlinik,
      jenisLayanan: klinikRuang.jenisLayanan
    };
  }
  return null;
});

const ruangList = computed(() => {
  const kode = kodeKlinik.value;
  if (!kode) return [];

  const ruangData = masterStore.ruangData || [];
  
  // Filter by kodeKlinik AND jenisLayanan if provided
  let klinikRuang;
  if (jenisLayanan.value) {
    klinikRuang = ruangData.find(r => r.kodeKlinik === kode && r.jenisLayanan === jenisLayanan.value);
  } else {
    // Fallback: just use kodeKlinik
    klinikRuang = ruangData.find(r => r.kodeKlinik === kode);
  }
  
  return klinikRuang?.ruangList || [];
});

const currentDate = ref(
  new Date().toLocaleDateString('id-ID', {
    weekday: 'long',
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  })
);

const snackbar = ref(false);
const snackbarText = ref('');
const snackbarColor = ref('success');
const showDetailDialog = ref(false);
const selectedPatientDetail = ref(null);
const pendingPage = ref({});
const showKelolaPasienDialog = ref(false);
const selectedPatientForKelola = ref(null);
const selectedAction = ref(null); // 'pindah-ruang', 'pindah-klinik', 'konsultasi'
const selectedRuangBaru = ref(null);
const selectedKlinikRuangBaru = ref(null);
const globalSearchQuery = ref('');
const sortOptions = ref({});
const searchPatientQuery = ref('');
const showFilterDialog = ref({});
const filterOptions = ref({});
const klinikRuangSearch = ref('');

const apiError = ref(null);
const activePanel = ref(null); // Tracks the open Klinik Ruang panel in dialog

// Helper: Check if a patient is from today
const isTodayPatient = (patient) => {
  if (!patient.createdAt && !patient.jamPanggil) return false;
  
  const patientDate = new Date(patient.createdAt || patient.jamPanggil);
  const today = new Date();
  
  return (
    patientDate.getDate() === today.getDate() &&
    patientDate.getMonth() === today.getMonth() &&
    patientDate.getFullYear() === today.getFullYear()
  );
};

// Initialize filter options for each room
const initializeFilterOptions = (ruang) => {
  if (!filterOptions.value[ruang.nomorRuang]) {
    filterOptions.value[ruang.nomorRuang] = {
      pemeriksaanAwal: null, // null = semua, true = sudah, false = belum
      tindakan: null // null = semua, true = sudah, false = belum
    };
  }
};

const filterOptionsList = {
  pemeriksaanAwal: [
    { title: 'Semua', value: null },
    { title: 'Sudah Pemeriksaan Awal', value: true },
    { title: 'Belum Pemeriksaan Awal', value: false }
  ],
  tindakan: [
    { title: 'Semua', value: null },
    { title: 'Sudah Tindakan', value: true },
    { title: 'Belum Tindakan', value: false }
  ]
};

// WebSocket configuration
const config = useRuntimeConfig();

// Generate a unique session suffix (random ID)
const uniqueSessionSuffix = ref(process.client ? Math.random().toString(36).substring(2, 8) : '')

// WebSocket client ID for admin
const adminClientId = computed(() => {
  return `admin-klinik-ruang-${kodeKlinik.value}-${uniqueSessionSuffix.value}`
})

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

const fetchAllData = async () => {
  if (!kodeKlinik.value) return;
  // console.log('🔄 AdminKlinikRuang refresh: Syncing data...');
  try {
    await queueStore.fetchPatientsForClinic(kodeKlinik.value);
    queueStore.ensureInitialData();
    // console.log('✅ AdminKlinikRuang refresh: Success');
  } catch (err) {
    console.error('❌ AdminKlinikRuang refresh error:', err);
  }
};

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

const showSnackbar = (message, color = 'success') => {
  snackbarText.value = message;
  snackbarColor.value = color;
  snackbar.value = true;
};

/**
 * Fetch patients from API for the clinic
 * Uses filters: klinik_id, klinik_ruang_id, active, limit
 */
// Local merging and fetching logic removed, now handled by queueStore.fetchPatientsForClinic

// Get all patients for room (menggunakan data dari API)
const getAllPatientsForRoom = (ruang) => {
  // Prioritize API patients, fallback to queueStore patients
  const patients = queueStore.allPatients
    .filter(p => {
      const matches = 
        p.kodeKlinik === klinikData.value?.kodeKlinik &&
        p.nomorRuang === ruang.nomorRuang &&
        p.processStage === 'klinik-ruang' &&
        p.status !== 'processed'; // Exclude finished patients
      
      return matches;
    });
  
  // Deduplicate by barcode/visitId (keep the one with most advanced status)
  const deduplicatedMap = new Map();
  const statusPriority = { 'processed': 4, 'diproses': 3, 'pemeriksaan': 2, 'di-loket': 1 };
  
  patients.forEach(p => {
    // FIXED: Prioritaskan No Antrian (stripped) sebagai key utama karena paling konsisten
    // Jika visitId ada di satu data dan tidak di yang lain, mereka tidak akan ter-merge jika visitId jadi prioritas utama
    const noAntrianClean = p.noAntrian ? p.noAntrian.split(" |")[0].trim() : null;
    const key = noAntrianClean || p.visitId || p.scanCode || p.barcode || p.no;
    
    if (!key) return;

    const existing = deduplicatedMap.get(key);
    
    if (!existing) {
      deduplicatedMap.set(key, p);
    } else {
      const pPrio = statusPriority[p.status] || 0;
      const ePrio = statusPriority[existing.status] || 0;
      
      // Jika status lebih tinggi, atau status sama tapi data lebih lengkap (misal ada visitId)
      if (pPrio > ePrio) {
         deduplicatedMap.set(key, p);
      } else if (pPrio === ePrio) {
        // Prefer one with visitId if available
        if (p.visitId && !existing.visitId) {
           deduplicatedMap.set(key, p);
        }
      }
    }
  });
  
  return Array.from(deduplicatedMap.values());
};

// Get filtered and sorted patients for room
const getFilteredAndSortedPatientsForRoom = (ruang) => {
  let patients = getAllPatientsForRoom(ruang);
  
  // Apply global search filter
  if (globalSearchQuery.value) {
    const searchLower = globalSearchQuery.value.toLowerCase();
    patients = patients.filter(p => 
      p.barcode?.toLowerCase().includes(searchLower) ||
      p.noAntrian?.toLowerCase().includes(searchLower) ||
      p.nama?.toLowerCase().includes(searchLower) ||
      p.klinik?.toLowerCase().includes(searchLower)
    );
  }
  
  // Initialize filter options if not exists
  initializeFilterOptions(ruang);
  
  // Apply multiple filter conditions
  const filters = filterOptions.value[ruang.nomorRuang];
  if (filters) {
    // Filter by Pemeriksaan Awal
    if (filters.pemeriksaanAwal !== null) {
      patients = patients.filter(p => 
        filters.pemeriksaanAwal ? p.calledPemeriksaanAwal : !p.calledPemeriksaanAwal
      );
    }
    
    // Filter by Tindakan
    if (filters.tindakan !== null) {
      patients = patients.filter(p => 
        filters.tindakan ? p.calledTindakan : !p.calledTindakan
      );
    }
  }
  
  // Default sorting
  return patients.sort((a, b) => {
    // 1. Prioritaskan Fast Track (Selalu paling atas di status yang sama)
    const aFT = (a.fastTrack ?? "").toString().trim().toUpperCase() === "YA";
    const bFT = (b.fastTrack ?? "").toString().trim().toUpperCase() === "YA";
    if (aFT && !bFT) return -1;
    if (!aFT && bFT) return 1;

    // 2. Prioritaskan yang sudah diproses (punya tipeLayanan)
    const aHasTiket = !!a.tipeLayanan || a.status === 'pemeriksaan';
    const bHasTiket = !!b.tipeLayanan || b.status === 'pemeriksaan';
    
    // Jika satu sudah punya tiket dan yang lain belum, yang sudah tiket di atas
    if (aHasTiket && !bHasTiket) return -1;
    if (!aHasTiket && bHasTiket) return 1;
    
    // 3. Sort berdasarkan status priority
    const statusPriority = {
      'pemeriksaan': 1,
      'di-loket': 2,
      'menunggu': 3,
      'waiting': 3, // Fallback for local/legacy data
      'terlambat': 4,
      'pending': 5
    };
    const priorityDiff = (statusPriority[a.status] || 99) - (statusPriority[b.status] || 99);
    if (priorityDiff !== 0) return priorityDiff;
    
    // 4. Sort by createdAt dari nomor tiket awal (referencePatient)
    let createdAtA = a.createdAt;
    let createdAtB = b.createdAt;
    
    if (a.referencePatient) {
      const sourceA = queueStore.allPatients.find(p => p.noAntrian === a.referencePatient);
      if (sourceA?.createdAt) createdAtA = sourceA.createdAt;
    }
    
    if (b.referencePatient) {
      const sourceB = queueStore.allPatients.find(p => p.noAntrian === b.referencePatient);
      if (sourceB?.createdAt) createdAtB = sourceB.createdAt;
    }
    
    if (createdAtA && createdAtB) {
      const dateA = new Date(createdAtA).getTime();
      const dateB = new Date(createdAtB).getTime();
      if (dateA !== dateB) return dateA - dateB;
    }
    
    // 5. Fallback: Sort by time
    const timeA = a.jamPanggil?.split(':').map(Number) || [0, 0];
    const timeB = b.jamPanggil?.split(':').map(Number) || [0, 0];
    return timeA[0] * 60 + timeA[1] - (timeB[0] * 60 + timeB[1]);
  });
};

// Get global search results across all rooms
const getGlobalSearchResults = () => {
  if (!globalSearchQuery.value) return [];
  
  const searchLower = globalSearchQuery.value.toLowerCase();
  return queueStore.allPatients.filter(p => 
    p.kodeKlinik === klinikData.value?.kodeKlinik &&
    p.processStage === 'klinik-ruang' &&
    (
      p.barcode?.toLowerCase().includes(searchLower) ||
      p.noAntrian?.toLowerCase().includes(searchLower) ||
      p.nama?.toLowerCase().includes(searchLower) ||
      p.klinik?.toLowerCase().includes(searchLower)
    )
  );
};

// Get pending patients (untuk backward compatibility jika masih digunakan)
const getPendingPatientsForRoom = (ruang) => {
  return getAllPatientsForRoom(ruang).filter(p => !p.tipeLayanan || p.status === 'pending');
};



const getCurrentProcessingForRoom = (ruang) => {
  if (!klinikData.value) return null;
  
  const key = `klinik-ruang-${klinikData.value.kodeKlinik}-${ruang.nomorRuang}`;
  const current = queueStore.currentProcessingPatient[key];
  
  // Return pasien yang sedang diproses (tidak dipisah per tipe layanan)
  return current || null;
};


const handleGenerateTicket = (patient, currentRuang) => {
  // Jika pasien sudah punya ruang, langsung generate tanpa dialog
  if (patient.ruang && patient.nomorRuang) {
    // Pasien sudah terdaftar di ruang tertentu
    // Cek apakah sudah punya antrean di ruang ini
    const existingAntrean = queueStore.allPatients.find(p => 
      p.referencePatient === patient.noAntrian &&
      p.kodeKlinik === klinikData.value?.kodeKlinik &&
      p.nomorRuang === patient.nomorRuang &&
      p.processStage === 'klinik-ruang'
    );

    if (existingAntrean) {
      // Sudah punya antrean, langsung proses
      const processResult = queueStore.processPatientKlinikRuang(
        existingAntrean,
        'proses',
        klinikData.value.kodeKlinik,
        patient.nomorRuang
      );
      showSnackbar(processResult.message, processResult.success ? 'success' : 'error');
      return;
    }

    // Belum punya antrean, generate baru dengan ruang yang sama
    const ruangData = ruangList.value.find(r => r.nomorRuang === patient.nomorRuang) || currentRuang;
    
    if (!ruangData) {
      showSnackbar('Ruang tidak ditemukan', 'error');
      return;
    }

    const klinikRuang = {
      kodeKlinik: klinikData.value.kodeKlinik,
      namaKlinik: klinikData.value.namaKlinik
    };

    // Generate dengan tipe layanan default: Pemeriksaan Awal
    const result = queueStore.scanAndCreateAntreanKlinikRuang(
      patient.barcode,
      klinikRuang,
      ruangData,
      'Pemeriksaan Awal'
    );

    if (result.success && result.patient) {
      // Auto proses pasien yang baru digenerate tiket
      const processResult = queueStore.processPatientKlinikRuang(
        result.patient,
        'proses',
        klinikData.value.kodeKlinik,
        ruangData.nomorRuang
      );
      showSnackbar(processResult.message, processResult.success ? 'success' : 'error');
    } else {
      showSnackbar(result.message, result.success ? 'success' : 'error');
    }
  } else {
    // Pasien belum punya ruang, isi field dan trigger scan (akan muncul dialog)
    barcodeInput.value = patient.noAntrian?.split(" |")[0] || patient.barcode || '';
    handleScanBarcode();
  }
};

// Get available patients for kelola pasien (all patients in this klinik)
const getAvailablePatientsForKelola = () => {
  let patients = queueStore.allPatients.filter(p => 
    p.kodeKlinik === klinikData.value?.kodeKlinik &&
    p.processStage === 'klinik-ruang' &&
    (p.status === 'anjungan' || p.status === 'di-loket' || p.status === 'terlambat' || p.status === 'pending')
  );

  // Apply search filter
  if (searchPatientQuery.value) {
    const searchLower = searchPatientQuery.value.toLowerCase();
    patients = patients.filter(p => 
      p.barcode?.toLowerCase().includes(searchLower) ||
      p.noAntrian?.toLowerCase().includes(searchLower) ||
      p.nama?.toLowerCase().includes(searchLower)
    );
  }

  return patients;
};

const closeKelolaPasienDialog = () => {
  showKelolaPasienDialog.value = false;
  selectedPatientForKelola.value = null;
  selectedAction.value = null;
  selectedRuangBaru.value = null;
  selectedKlinikRuangBaru.value = null;
  searchPatientQuery.value = '';
  klinikRuangSearch.value = '';
};

// Get all available klinik ruang options (for pindah klinik and konsultasi)
const getAllKlinikRuangOptions = () => {
  const ruangData = masterStore.ruangData || [];
  const options = [];
  
  ruangData.forEach(klinikRuang => {
    klinikRuang.ruangList?.forEach(ruang => {
      options.push({
        kodeKlinik: klinikRuang.kodeKlinik,
        namaKlinik: klinikRuang.namaKlinik,
        nomorRuang: ruang.nomorRuang,
        namaRuang: ruang.namaRuang,
        nomorScreen: ruang.nomorScreen
      });
    });
  });
  
  return options;
};

// Get klinik ruang data grouped by klinik (for expansion panels)
const klinikRuangList = computed(() => {
  return masterStore.ruangData || [];
});

// Filtered klinik ruang based on search query
const filteredKlinikRuang = computed(() => {
  if (!klinikRuangSearch.value) return klinikRuangList.value;
  
  const searchLower = klinikRuangSearch.value.toLowerCase();
  return klinikRuangList.value
    .map(klinikRuang => {
      // Check if klinik name or code matches
      const klinikMatches = 
        klinikRuang.namaKlinik?.toLowerCase().includes(searchLower) ||
        klinikRuang.kodeKlinik?.toLowerCase().includes(searchLower);
      
      // Filter ruangList based on search
      const filteredRuangList = klinikRuang.ruangList?.filter(ruang =>
        ruang.namaRuang?.toLowerCase().includes(searchLower) ||
        ruang.nomorRuang?.toString().includes(searchLower) ||
        ruang.nomorScreen?.toString().includes(searchLower)
      ) || [];
      
      // Return klinik if klinik matches or has matching ruang
      if (klinikMatches || filteredRuangList.length > 0) {
        return {
          ...klinikRuang,
          ruangList: klinikMatches ? klinikRuang.ruangList : filteredRuangList
        };
      }
      
      return null;
    })
    .filter(k => k !== null && k.ruangList && k.ruangList.length > 0);
});

const confirmPindahRuang = () => {
  if (!selectedRuangBaru.value || !selectedPatientForKelola.value) {
    showSnackbar('Pilih ruang tujuan', 'error');
    return;
  }

  const patientIndex = queueStore.allPatients.findIndex(p => p.no === selectedPatientForKelola.value.no);
  
  if (patientIndex === -1) {
    showSnackbar('Pasien tidak ditemukan', 'error');
    return;
  }

  const patient = queueStore.allPatients[patientIndex];
  
  // Jika pasien sudah punya antrean klinik ruang (sudah digenerate tiket), update antreannya juga
  if (patient.processStage === 'klinik-ruang' && patient.tipeLayanan) {
      // Update antrean yang sudah ada
      const baseNoAntrian = patient.noAntrian?.split(" |")[0] || patient.barcode || '';
      queueStore.allPatients[patientIndex] = {
        ...queueStore.allPatients[patientIndex],
        ruang: selectedRuangBaru.value.namaRuang,
        nomorRuang: selectedRuangBaru.value.nomorRuang,
        nomorScreen: selectedRuangBaru.value.nomorScreen,
        // Update noAntrian untuk reflect ruang baru
        noAntrian: `${baseNoAntrian} | ${klinikData.value.namaKlinik} - ${selectedRuangBaru.value.namaRuang} - ${patient.tipeLayanan}`,
        noAntrianRuang: `${klinikData.value.namaKlinik} - ${selectedRuangBaru.value.namaRuang} | ${baseNoAntrian}`
      };
    
    // Clear current processing dari ruang lama jika ada
    const oldRuang = ruangList.value.find(r => r.nomorRuang === patient.nomorRuang);
    if (oldRuang) {
      const oldKey = `klinik-ruang-${klinikData.value.kodeKlinik}-${oldRuang.nomorRuang}`;
      if (queueStore.currentProcessingPatient[oldKey]?.no === patient.no) {
        queueStore.currentProcessingPatient[oldKey] = null;
      }
    }
  } else {
    // Pasien belum digenerate tiket, hanya update ruang
    queueStore.allPatients[patientIndex] = {
      ...queueStore.allPatients[patientIndex],
      ruang: selectedRuangBaru.value.namaRuang,
      nomorRuang: selectedRuangBaru.value.nomorRuang,
      nomorScreen: selectedRuangBaru.value.nomorScreen
    };
  }

  showSnackbar(
    `Pasien ${selectedPatientForKelola.value.noAntrian?.split(" |")[0] || selectedPatientForKelola.value.barcode || '-'} berhasil dipindah ke ${selectedRuangBaru.value.namaRuang}`,
    'success'
  );

  // Trigger real-time update
  broadcastUpdate();

  closeKelolaPasienDialog();
};

const confirmPindahKlinik = async () => {
  if (!selectedKlinikRuangBaru.value || !selectedPatientForKelola.value) {
    showSnackbar('Pilih klinik ruang tujuan', 'error');
    return;
  }

  const result = queueStore.pindahKlinikRuang(
    selectedPatientForKelola.value,
    {
      kodeKlinik: selectedKlinikRuangBaru.value.kodeKlinik,
      namaKlinik: selectedKlinikRuangBaru.value.namaKlinik
    },
    {
      nomorRuang: selectedKlinikRuangBaru.value.nomorRuang,
      namaRuang: selectedKlinikRuangBaru.value.namaRuang,
      nomorScreen: selectedKlinikRuangBaru.value.nomorScreen
    }
  );

  if (result.success) {
    showSnackbar(result.message, 'success');
    broadcastUpdate();
    closeKelolaPasienDialog();
  } else {
    showSnackbar(result.message, 'error');
  }
};

const confirmKonsultasi = async () => {
  if (!selectedKlinikRuangBaru.value || !selectedPatientForKelola.value) {
    showSnackbar('Pilih klinik ruang tujuan', 'error');
    return;
  }

  const result = queueStore.konsultasiKlinikRuang(
    selectedPatientForKelola.value,
    {
      kodeKlinik: selectedKlinikRuangBaru.value.kodeKlinik,
      namaKlinik: selectedKlinikRuangBaru.value.namaKlinik
    },
    {
      nomorRuang: selectedKlinikRuangBaru.value.nomorRuang,
      namaRuang: selectedKlinikRuangBaru.value.namaRuang,
      nomorScreen: selectedKlinikRuangBaru.value.nomorScreen
    },
    'Pemeriksaan Awal'
  );

  if (result.success && result.patient) {
    showSnackbar(result.message, 'success');
    
    // Print tiket konsultasi
    try {
      const { printTicketFromPatient } = useThermalPrint();
      await printTicketFromPatient(result.patient);
      showSnackbar('Tiket konsultasi berhasil dicetak', 'success');
    } catch (error) {
      console.error('Error printing konsultasi ticket:', error);
      showSnackbar('Tiket konsultasi berhasil dibuat, namun gagal dicetak', 'warning');
    }
    
    closeKelolaPasienDialog();
    broadcastUpdate();
  } else {
    showSnackbar(result.message, 'error');
  }
};

// Handle call patient from list (dari card pasien di daftar)
const handleCallPatientFromList = async (ruang, patient, tipeLayanan) => {
  if (!patient || !patient.no) {
    showSnackbar('Pasien tidak valid', 'error');
    return;
  }

  // Update tipeLayanan pasien untuk tracking panggilan terakhir
  // Hanya memanggil, tidak memproses pasien (tidak naik ke current processing)
  const patientIndex = queueStore.allPatients.findIndex(p => p.no === patient.no);
  if (patientIndex === -1) {
    showSnackbar('Pasien tidak ditemukan', 'error');
    return;
  }

  // Update tracking panggilan berdasarkan tipeLayanan
  // Update tipeLayanan pasien agar muncul di kolom yang sesuai di Anjungan
  const updateData = {
    ...queueStore.allPatients[patientIndex],
    status: queueStore.allPatients[patientIndex].status, // Tetap status yang sama, tidak diubah ke 'di-loket'
    tipeLayanan: tipeLayanan, // Update tipeLayanan untuk display di Anjungan
    lastCalledAt: new Date().toISOString(),
    lastCalledTipeLayanan: tipeLayanan
  };

  // Set penanda panggilan sesuai tipeLayanan
  if (tipeLayanan === 'Pemeriksaan Awal') {
    updateData.calledPemeriksaanAwal = true;
  } else if (tipeLayanan === 'Tindakan') {
    updateData.calledTindakan = true;
  }

  queueStore.allPatients[patientIndex] = updateData;

  // TIDAK mengupdate current processing - pasien tetap di daftar pasien

  const patientCode = queueStore.allPatients[patientIndex].noAntrian?.split(" |")[0] || 
                      queueStore.allPatients[patientIndex].barcode || 
                      '-';

  // Send via WebSocket to Anjungan clients
  try {
    // Get all possible client IDs for this klinik (anjungan screens)
    const anjunganClientIds = [];
    
    // Always send to client ID without screen number (broadcast to all screens for this klinik)
    anjunganClientIds.push(`anjungan-klinik-ruang-${klinikData.value.kodeKlinik}`);
    
    // Also send to specific screen if ruang has nomorScreen
    if (ruang.nomorScreen) {
      const specificScreenId = `anjungan-klinik-ruang-${klinikData.value.kodeKlinik}-screen-${ruang.nomorScreen}`;
      if (!anjunganClientIds.includes(specificScreenId)) {
        anjunganClientIds.push(specificScreenId);
      }
    }
    
    // Also send to all other screens for this klinik (from ruangList)
    ruangList.value.forEach(r => {
      if (r.nomorScreen) {
        const screenId = `anjungan-klinik-ruang-${klinikData.value.kodeKlinik}-screen-${r.nomorScreen}`;
        if (!anjunganClientIds.includes(screenId)) {
          anjunganClientIds.push(screenId);
        }
      }
    });
    
    console.log('📋 All target client IDs:', anjunganClientIds);

    // Extract nomor antrian (ambil bagian sebelum " |")
    const nomorAntrian = updateData.noAntrian?.split(" |")[0] || updateData.barcode || '-';

    console.log('📤 Sending WebSocket message via POST...');
    console.log('📍 Target clients:', anjunganClientIds);
    console.log('📦 Nomor antrian:', nomorAntrian);
    console.log('📦 Tipe layanan:', tipeLayanan);

    // Send to all relevant clients
    for (const clientId of anjunganClientIds) {
      // Kirim nomor antrian + tipe layanan agar Anjungan tahu harus tampilkan di kolom mana
      const message = {
        to_client: clientId,
        data: {
          noantrian: nomorAntrian,
          tipeLayanan: tipeLayanan // "Pemeriksaan Awal" atau "Tindakan"
        },
      };
      
      console.log(`📨 Sending to ${clientId}:`, message);
      const result = await sendViaPost(message);
      console.log(`✅ Response from ${clientId}:`, result);
    }
    
    console.log('✅ All WebSocket messages sent successfully');
  } catch (error) {
    console.error('❌ Error sending WebSocket message:', error);
    // Don't block the UI if WebSocket fails
  }

  showSnackbar(`Memanggil pasien ${patientCode} untuk ${tipeLayanan}`, 'success');
};

const showPatientDetail = (patient) => {
  // Get latest patient data from store
  const patientIndex = queueStore.allPatients.findIndex(p => p.no === patient.no);
  if (patientIndex !== -1) {
    selectedPatientDetail.value = { ...queueStore.allPatients[patientIndex] };
  } else {
    selectedPatientDetail.value = { ...patient };
  }
  showDetailDialog.value = true;
};

// Toggle layanan status (membatalkan panggilan jika sudah dipanggil)
const toggleLayananStatus = (tipeLayanan) => {
  if (!selectedPatientDetail.value || !selectedPatientDetail.value.no) return;
  
  const patientIndex = queueStore.allPatients.findIndex(p => p.no === selectedPatientDetail.value.no);
  if (patientIndex === -1) {
    showSnackbar('Pasien tidak ditemukan', 'error');
    return;
  }
  
  const patient = queueStore.allPatients[patientIndex];
  const updateData = { ...patient };
  
  if (tipeLayanan === 'Pemeriksaan Awal') {
    // Toggle status: jika sudah dipanggil, batalkan; jika belum, tidak bisa diaktifkan dari sini
    if (patient.calledPemeriksaanAwal) {
      updateData.calledPemeriksaanAwal = false;
      // Jika tipeLayanan saat ini adalah Pemeriksaan Awal, reset tipeLayanan
      if (patient.tipeLayanan === 'Pemeriksaan Awal') {
        updateData.tipeLayanan = null;
      }
      showSnackbar('Status panggilan Pemeriksaan Awal dibatalkan', 'info');
    } else {
      showSnackbar('Pemeriksaan Awal belum dipanggil', 'warning');
      return;
    }
  } else if (tipeLayanan === 'Tindakan') {
    // Toggle status: jika sudah dipanggil, batalkan; jika belum, tidak bisa diaktifkan dari sini
    if (patient.calledTindakan) {
      updateData.calledTindakan = false;
      // Jika tipeLayanan saat ini adalah Tindakan, reset tipeLayanan
      if (patient.tipeLayanan === 'Tindakan') {
        updateData.tipeLayanan = null;
      }
      showSnackbar('Status panggilan Pemeriksaan dibatalkan', 'info');
    } else {
      showSnackbar('Pemeriksaan belum dipanggil', 'warning');
      return;
    }
  }
  
  // Update patient data
  queueStore.allPatients[patientIndex] = updateData;
  
  // Update selectedPatientDetail untuk refresh dialog
  selectedPatientDetail.value = { ...updateData };
  
  // Update current processing jika pasien sedang diproses
  const ruangList = masterStore.ruangData || [];
  for (const klinikRuang of ruangList) {
    if (klinikRuang.kodeKlinik === patient.kodeKlinik) {
      const key = `klinik-ruang-${patient.kodeKlinik}-${patient.nomorRuang}`;
      if (queueStore.currentProcessingPatient[key]?.no === patient.no) {
        queueStore.currentProcessingPatient[key] = updateData;
      }
      break;
    }
  }

  // Trigger real-time update for Anjungan
  broadcastUpdate();
};

/**
 * Broadcast update to all Anjungan screens for this clinic
 */
const broadcastUpdate = async () => {
  try {
    const anjunganClientIds = [];
    
    // Base broadcast ID
    anjunganClientIds.push(`anjungan-klinik-ruang-${klinikData.value.kodeKlinik}`);
    
    // Screen-specific IDs
    ruangList.value.forEach(r => {
      if (r.nomorScreen) {
        anjunganClientIds.push(`anjungan-klinik-ruang-${klinikData.value.kodeKlinik}-screen-${r.nomorScreen}`);
      }
    });

    for (const clientId of anjunganClientIds) {
      await sendViaPost({
        to_client: clientId,
        data: {
          klinikId: klinikData.value.kodeKlinik,
          triggerRefresh: true
        }
      });
    }
  } catch (error) {
    console.error('❌ [AdminKlinikRuang] Error broadcasting update:', error);
  }
};

const getStatusColor = (status) => {
  const colors = {
    'pemeriksaan': 'success-600',
    'di-loket': 'warning-600',
    'menunggu': 'primary-600',
    'waiting': 'primary-600',
    'terlambat': 'secondary-600',
    'pending': 'danger-600'
  };
  return colors[status] || 'grey';
};

const getStatusLabel = (status) => {
  const labels = {
    'di-loket': 'Di Loket',
    'menunggu': 'Menunggu',
    'waiting': 'Menunggu',
    'terlambat': 'Terlambat',
    'pending': 'Pending',
    'pemeriksaan': 'Pemeriksaan'
  };
  return labels[status] || status;
};


// Handle call patient by tipe (untuk pasien yang sedang diproses)
const handleCallPatientByTipe = async (ruang, tipeLayanan) => {
  const current = getCurrentProcessingForRoom(ruang);
  if (!current || !current.no) {
    showSnackbar('Tidak ada pasien yang sedang diproses', 'error');
    return;
  }

  const patientIndex = queueStore.allPatients.findIndex(p => p.no === current.no);
  if (patientIndex === -1) {
    showSnackbar('Pasien tidak ditemukan', 'error');
    return;
  }

  const updateData = {
    ...queueStore.allPatients[patientIndex],
    status: 'pemeriksaan',
    tipeLayanan: tipeLayanan,
    lastCalledAt: new Date().toISOString(),
    lastCalledTipeLayanan: tipeLayanan
  };

  if (tipeLayanan === 'Pemeriksaan Awal') {
    updateData.calledPemeriksaanAwal = true;
  } else if (tipeLayanan === 'Tindakan') {
    updateData.calledTindakan = true;
  }

  queueStore.allPatients[patientIndex] = updateData;

  const key = `klinik-ruang-${klinikData.value.kodeKlinik}-${ruang.nomorRuang}`;
  queueStore.currentProcessingPatient[key] = queueStore.allPatients[patientIndex];

  const patientCode = queueStore.allPatients[patientIndex].noAntrian?.split(" |")[0] || 
                      queueStore.allPatients[patientIndex].barcode || 
                      '-';

  try {
    const anjunganClientIds = [];
    anjunganClientIds.push(`anjungan-klinik-ruang-${klinikData.value.kodeKlinik}`);
    
    if (ruang.nomorScreen) {
      const specificScreenId = `anjungan-klinik-ruang-${klinikData.value.kodeKlinik}-screen-${ruang.nomorScreen}`;
      if (!anjunganClientIds.includes(specificScreenId)) {
        anjunganClientIds.push(specificScreenId);
      }
    }
    
    ruangList.value.forEach(r => {
      if (r.nomorScreen) {
        const screenId = `anjungan-klinik-ruang-${klinikData.value.kodeKlinik}-screen-${r.nomorScreen}`;
        if (!anjunganClientIds.includes(screenId)) {
          anjunganClientIds.push(screenId);
        }
      }
    });
    
    const nomorAntrian = updateData.noAntrian?.split(" |")[0] || updateData.barcode || '-';

    for (const clientId of anjunganClientIds) {
      const message = {
        to_client: clientId,
        data: {
          noantrian: nomorAntrian,
          tipeLayanan: tipeLayanan
        },
      };
      await sendViaPost(message);
    }
  } catch (error) {
    console.error('❌ Error sending WebSocket message:', error);
  }

  showSnackbar(`Memanggil pasien ${patientCode} untuk ${tipeLayanan}`, 'success');
};

const handlePatientAction = async (ruang, action) => {
  const current = getCurrentProcessingForRoom(ruang);
  if (!current) return;

  const result = await queueStore.processPatientKlinikRuang(
    current,
    action,
    klinikData.value.kodeKlinik,
    ruang.nomorRuang
  );
  
  // Jika pending, pastikan pasien kembali ke daftar dengan status pending
  // dan clear dari current processing
  if (action === 'pending' && result.success) {
    const patientIndex = queueStore.allPatients.findIndex(p => p.no === current.no);
    if (patientIndex !== -1) {
      queueStore.allPatients[patientIndex] = {
        ...queueStore.allPatients[patientIndex],
        status: 'pending'
      };
      
      // Clear current processing
      const key = `klinik-ruang-${klinikData.value.kodeKlinik}-${ruang.nomorRuang}`;
      queueStore.currentProcessingPatient[key] = null;
    }
  }
  
  showSnackbar(result.message, result.success ? 'success' : 'error');
  if (result.success) {
    broadcastUpdate();
  }
};

// Handle proses pasien (untuk pasien yang belum diproses)
const handleProcessPatient = (ruang, patient) => {
  const patientIndex = queueStore.allPatients.findIndex(p => p.no === patient.no);
  if (patientIndex === -1) {
    showSnackbar('Pasien tidak ditemukan', 'error');
    return;
  }
  
  // Set sebagai current processing
  const result = queueStore.processPatientKlinikRuang(
    queueStore.allPatients[patientIndex],
    'proses',
    klinikData.value.kodeKlinik,
    ruang.nomorRuang
  );
  
  showSnackbar(result.message, result.success ? 'success' : 'error');
  if (result.success) {
    broadcastUpdate();
  }
};

const handleProcessPendingPatient = (ruang, patient) => {
  // Proses kembali pasien yang dipending
  const patientIndex = queueStore.allPatients.findIndex(p => p.no === patient.no);
  if (patientIndex === -1) {
    showSnackbar('Pasien tidak ditemukan', 'error');
    return;
  }
  
  // Update status pasien dari pending menjadi waiting
  queueStore.allPatients[patientIndex] = {
    ...queueStore.allPatients[patientIndex],
    status: 'anjungan'
  };
  
  // Set sebagai current processing
  const result = queueStore.processPatientKlinikRuang(
    queueStore.allPatients[patientIndex],
    'proses',
    klinikData.value.kodeKlinik,
    ruang.nomorRuang
  );
  
  showSnackbar(result.message, result.success ? 'success' : 'error');
  if (result.success) {
    broadcastUpdate();
  }
};

const paginatedAllPatients = (ruang) => {
  const allPatients = getFilteredAndSortedPatientsForRoom(ruang);
  const page = pendingPage.value[ruang.nomorRuang] || 1;
  const startIndex = (page - 1) * 10;
  const endIndex = startIndex + 10;
  return allPatients.slice(startIndex, endIndex);
};

// Helper untuk menentukan class card berdasarkan status pasien
const getPatientCardClass = (patient, ruang) => {
  const baseClass = 'patient-queue-item';
  const isFastTrack = (patient.fastTrack ?? '').toString().trim().toUpperCase() === 'YA';
  const isProcessing = patient.no === getCurrentProcessingForRoom(ruang)?.no;
  
  let dynamicClass = 'patient-queue-item-default';
  if (isProcessing) {
    dynamicClass = 'patient-queue-item-processing';
  } else if (isFastTrack) {
    dynamicClass = 'patient-queue-item-fast-track';
  }
  
  return `${baseClass} ${dynamicClass}`;
};



// Helper functions for filter
const openFilterDialog = (ruang) => {
  initializeFilterOptions(ruang);
  showFilterDialog.value[ruang.nomorRuang] = true;
};

const closeFilterDialog = (ruang) => {
  showFilterDialog.value[ruang.nomorRuang] = false;
};

const getActiveFilterCount = (ruang) => {
  const filters = filterOptions.value[ruang.nomorRuang];
  if (!filters) return 0;
  let count = 0;
  if (filters.pemeriksaanAwal !== null) count++;
  if (filters.tindakan !== null) count++;
  return count;
};

const resetFilters = (ruang) => {
  if (filterOptions.value[ruang.nomorRuang]) {
    filterOptions.value[ruang.nomorRuang] = {
      pemeriksaanAwal: null,
      tindakan: null
    };
  }
};

const applyFilters = (ruang) => {
  closeFilterDialog(ruang);
  // Reset pagination when filters change
  pendingPage.value[ruang.nomorRuang] = 1;
};

// Watch for ruangList changes to re-initialize filters
watch(ruangList, (newList) => {
  if (newList && newList.length > 0) {
    newList.forEach(ruang => {
      if (!pendingPage.value[ruang.nomorRuang]) {
        pendingPage.value[ruang.nomorRuang] = 1;
      }
      initializeFilterOptions(ruang);
    });
  }
}, { immediate: true });

onMounted(async () => {
  console.log('🚀 AdminKlinikRuang mounted, syncing data...');
  
  // 1. Sync master data if needed
  try {
    await clinicStore.fetchRegulerClinics();
    await ruangStore.fetchRuangFromAPI();
  } catch (error) {
    console.error('❌ Error syncing data in AdminKlinikRuang:', error);
  }

  // 2. Initial fetch
  await fetchAllData();

  // 3. Centralized WebSocket & interest registration
  // initWebSocket is already called via the watcher on adminClientId
  if (kodeKlinik.value) {
     queueStore.registerClinicInterest(kodeKlinik.value);
  }
});

// 4. Lifecycle cleanup (Keep outside async block to preserve context)
let pollInterval;
onMounted(() => {
  // Check for daily reset and poll data every minute
  pollInterval = setInterval(() => {
    const didReset = queueStore.checkAndResetDaily();
    if (didReset) {
      console.log("🕒 [AdminKlinikRuang] 2 AM threshold reached. Data reset performed.");
    }
    fetchAllData();
  }, 60000);
});

onUnmounted(() => {
  if (pollInterval) clearInterval(pollInterval);
  if (kodeKlinik.value) {
    queueStore.unregisterClinicInterest(kodeKlinik.value);
  }
});
</script>

<style scoped lang="scss">
.admin-klinik-ruang-container {
  background: var(--color-neutral-300);
  min-height: 100vh;
  padding: 16px;
  border-radius: 0 !important;
}

/* Remove rounded edges from PageHeader component */
:deep(.page-header) {
  border-radius: 0 !important;
}

.generate-ticket-card {
  border-radius: 12px;
  border: 1px solid var(--color-neutral-500);
  background: var(--color-neutral-100);
}

.section-label {
  font-size: 12px;
  line-height: 16px;
  font-weight: 700;
  letter-spacing: 0.5px;
  color: var(--color-neutral-600);
  text-transform: uppercase;
}

.section-label-small {
  font-size: 12px;
  line-height: 16px;
  font-weight: 700;
  letter-spacing: 0.5px;
  color: var(--color-neutral-600);
  text-transform: uppercase;
}

.instruction-text {
  font-size: 12px;
  line-height: 16px;
  color: var(--color-neutral-700);
}

.rooms-grid-wrapper {
  margin-top: 24px;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: thin;
  scrollbar-color: var(--color-neutral-500) var(--color-neutral-300);
}

.rooms-grid-wrapper::-webkit-scrollbar {
  height: 8px;
}

.rooms-grid-wrapper::-webkit-scrollbar-track {
  background: var(--color-neutral-300);
  border-radius: 4px;
}

.rooms-grid-wrapper::-webkit-scrollbar-thumb {
  background: var(--color-neutral-500);
  border-radius: 4px;
}

.rooms-grid-wrapper::-webkit-scrollbar-thumb:hover {
  background: var(--color-neutral-600);
}

.rooms-grid {
  display: flex;
  flex-direction: row;
  gap: 16px;
  min-width: fit-content;
}

.global-search-section {
  background: var(--color-neutral-100);
  padding: 16px;
  border-radius: 12px;
  border: 1px solid var(--color-neutral-400);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.sticky-search-section {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 16px;
  z-index: 100;
  margin-bottom: 0;
}

.search-actions-row {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: flex-end;
}

.global-search-field {
  flex: 1;
  max-width: none;
  margin-right: auto;
}

.btn-pindah-pasien {
  text-transform: none !important;
  font-weight: 600 !important;
  font-size: 14px !important;
  line-height: 20px !important;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
  min-height: 40px !important;
  padding: 8px 20px !important;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
  transition: all 0.2s ease !important;
  white-space: nowrap !important;
  background-color: #FF9800 !important;
  color: #FFFFFF !important;
  border: none !important;
}

.btn-pindah-pasien:hover {
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15) !important;
  background-color: #F57C00 !important;
}

.btn-pindah-pasien:active {
  transform: translateY(0) !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
  background-color: #E65100 !important;
}

.btn-pindah-pasien .v-icon {
  color: #FFFFFF !important;
}

.sort-select {
  font-size: 12px;
}

.room-card {
  border-radius: 12px;
  border: 1px solid var(--color-neutral-500);
  background: var(--color-neutral-100);
  width: 700px;
  min-width: 700px;
  max-width: 700px;
  height: fit-content;
  box-sizing: border-box;
  overflow: hidden;
  flex-shrink: 0;
}

.room-header {
  background: linear-gradient(135deg, var(--color-primary-600) 0%, var(--color-primary-700) 100%);
  color: var(--color-neutral-100);
  padding: 16px 20px;
  box-shadow: 0 2px 8px rgba(255, 152, 0, 0.2);
}

.room-title {
  display: flex;
  align-items: center;
  font-weight: 700;
  font-size: 16px;
  gap: 8px;
}

.current-patient-section {
  background: linear-gradient(135deg, var(--color-primary-50) 0%, var(--color-primary-100) 100%);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid var(--color-primary-400);
}

.current-patient-info {
  text-align: center;
}

.patient-number-large {
  font-size: 32px;
  line-height: 40px;
  font-weight: 700;
  color: var(--color-neutral-900);
  margin-bottom: 12px;
}

.patient-details {
  font-size: 14px;
  line-height: 20px;
  color: var(--color-neutral-700);
  margin-bottom: 4px;
}

.current-patient-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.action-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-top: 16px;
  align-items: center;
}

.action-icon-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-icon-btn {
  min-width: auto !important;
  width: auto !important;
  height: 32px !important;
  padding: 0 12px !important;
  border-radius: 16px !important;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
  transition: all 0.2s ease;
  text-transform: none !important;
  display: flex !important;
  align-items: center !important;
  gap: 4px;
}

.btn-label {
  font-size: 10px;
  font-weight: 600;
  white-space: nowrap;
}

.action-icon-btn:disabled {
  background-color: #c59494 !important;
  color: #ffffff !important;
  opacity: 0.8;
  cursor: not-allowed;
  box-shadow: none !important;
  transform: none !important;
}

.action-grid .v-btn {
  text-transform: none;
  font-weight: 600;
  font-size: 14px;
  line-height: 20px;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  padding: 8px 12px;
  min-height: 40px;
  white-space: nowrap;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.action-grid .v-btn:disabled {
  background-color: var(--color-neutral-600) !important;
  color: var(--color-neutral-100) !important;
  opacity: 0.8 !important;
  box-shadow: none !important;
  transform: none !important;
}

.empty-current {  
  text-align: center;
  padding: 24px 16px;
  background: var(--color-neutral-200);
  border-radius: 8px;
  border: 1px solid var(--color-neutral-300);
}

.empty-text {
  font-size: 14px;
  line-height: 20px;
  color: var(--color-neutral-600);
  font-weight: 500;
}

.queue-sections {
  margin-top: 16px;
}

.queue-section {
  border: 1px solid var(--color-neutral-400);
  border-radius: 8px;
  padding: 12px;
  background: var(--color-neutral-200);
}

.queue-section-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid var(--color-neutral-400);
}

.queue-section-title {
  font-size: 14px;
  line-height: 20px;
  font-weight: 700;
  color: var(--color-neutral-900);
  flex: 1;
}

.queue-cards {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 400px;
  overflow-y: auto;
}

.empty-queue {
  text-align: center;
  padding: 24px;
}

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

.empty-filtered-state {
  text-align: center;
  padding: 40px 20px;
  background: var(--color-neutral-200);
  border-radius: 8px;
  border: 1px dashed var(--color-neutral-400);
}

/* Dialog Styles - Consistent with AdminLoket */
.dialog-card {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  border-radius: 12px;
  overflow: hidden;
}

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

.dialog-header-warning {
  background: linear-gradient(135deg, var(--color-primary-600) 0%, var(--color-primary-700) 100%);
}

.headline-4 {
  font-size: 20px;
  line-height: 28px;
  font-weight: 600;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  margin: 0;
  color: var(--color-neutral-100);
}

.btn-close {
  color: var(--color-neutral-100) !important;
  transition: all 0.2s ease;
}

.btn-close:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  transform: rotate(90deg);
}

.dialog-content {
  padding: 24px !important;
  background: var(--color-neutral-300);
}

.dialog-actions {
  padding: 16px 24px;
  background: var(--color-neutral-300);
  border-top: 1px solid var(--color-neutral-400);
}

.dialog-actions .v-btn {
  text-transform: none;
  font-weight: 600;
  font-size: 16px;
  line-height: 24px;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  min-width: 100px;
}

.btn-cancel {
  border-color: var(--color-neutral-600) !important;
  color: var(--color-neutral-800) !important;
}

.btn-submit {
  background-color: var(--color-secondary-600) !important;
  color: var(--color-neutral-100) !important;
}

.patient-card {
  background: var(--color-neutral-100);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid var(--color-neutral-400);
}

.detail-row {
  margin-bottom: 16px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-label {
  font-size: 12px;
  line-height: 16px;
  color: var(--color-neutral-600);
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.detail-value {
  font-size: 16px;
  line-height: 24px;
  font-weight: 600;
  color: var(--color-neutral-900);
}

.detail-value.reference-value {
  font-size: 14px;
  line-height: 20px;
  word-break: break-word;
}

.detail-chip {
  font-weight: 600;
  text-transform: none;
}

.detail-chips-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.detail-chip-clickable {
  cursor: pointer;
  transition: all 0.2s ease;
  font-weight: 600;
  text-transform: none;
}

.detail-chip-clickable:hover {
  transform: scale(1.05);
  opacity: 0.9;
}

.detail-chip-clickable.chip-active {
  cursor: pointer;
}

.detail-chip-clickable:not(.chip-active) {
  cursor: not-allowed;
  opacity: 0.6;
}

.body-2 {
  font-size: 16px;
  line-height: 24px;
}

.body-3 {
  font-size: 14px;
  line-height: 20px;
}

.caption-2 {
  font-size: 12px;
  line-height: 16px;
}

.text-semibold {
  font-weight: 600 !important;
}

.text-muted {
  color: var(--color-neutral-700);
}

.patient-list-section {
  background: var(--color-neutral-200);
  border: 1px solid var(--color-neutral-400);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}

.patient-queue-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}

.patient-queue-item {
  display: flex;
  flex-direction: column;
  padding: 12px 20px;
  border-radius: 8px;
  transition: all 0.2s ease;
  gap: 4px;
  min-height: auto;
  width: 100%;
  box-sizing: border-box;
}

.patient-card-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  gap: 16px;
}

.patient-card-left-group {
  display: flex;
  align-items: center;
  flex: 0 0 auto;
}

.patient-card-right-group {
  display: flex;
  align-items: center;
  flex: 0 0 auto;
  justify-content: flex-end;
}

.patient-card-bottom-row {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}


/* Pasien default */
.patient-queue-item-default {
  background: var(--color-neutral-100);
  border: 1px solid var(--color-neutral-300);
}

.patient-queue-item-default:hover {
  background: var(--color-neutral-200);
  border-color: var(--color-neutral-400);
}

/* Pasien sedang diproses */
.patient-queue-item-processing {
  background: linear-gradient(135deg, var(--color-primary-50) 0%, var(--color-primary-100) 100%) !important;
  border: 1px solid var(--color-primary-400) !important;
}

.patient-queue-item-processing:hover {
  background: linear-gradient(135deg, var(--color-primary-100) 0%, var(--color-primary-200) 100%) !important;
}

/* Pasien fast track - harus setelah processed dan default agar bisa override */
.patient-queue-item-fast-track {
  background: #FBE9E8 !important;
  border-color: rgba(255, 132, 65, 0.5) !important;
}

.patient-queue-item-fast-track:hover {
  background: #F1B3AE !important;
  border-color: rgba(255, 132, 65, 0.6) !important;
}

/* Fast track dengan default - override default styling */
.patient-queue-item-default.patient-queue-item-fast-track {
  background: #FBE9E8 !important;
  border-color: rgba(255, 132, 65, 0.5) !important;
}

.patient-queue-item-default.patient-queue-item-fast-track:hover {
  background: #F1B3AE !important;
  border-color: rgba(255, 132, 65, 0.6) !important;
}

/* Left Section: Number and Status */
.patient-card-left {
  display: none;
}

.patient-queue-number-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.patient-queue-number {
  font-size: 20px;
  line-height: 28px;
  font-weight: 700;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  color: var(--color-neutral-900);
  letter-spacing: 0.5px;
  word-break: break-word;
  white-space: nowrap;
}

.patient-status-icons {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
}

.status-icon-wrapper {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.status-icon-wrapper .status-icon {
  transition: all 0.2s ease;
}

/* Fast Track Icon Styling */
.status-icon-fast-track {
  background: rgba(239, 83, 80, 0.15);
  border: 2px solid rgba(229, 57, 53, 0.4);
  box-shadow: 0 2px 8px rgba(229, 57, 53, 0.2);
}

.status-icon-fast-track .status-icon {
  color: #E53935 !important;
}

/* Pending Icon Styling */
.status-icon-pending {
  background: rgba(222, 71, 59, 0.15);
  border: 2px solid rgba(216, 39, 25, 0.4);
  box-shadow: 0 2px 8px rgba(216, 39, 25, 0.2);
}

.status-icon-pending .status-icon {
  color: var(--color-danger-600) !important;
}

.patient-queue-status-chips {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 4px;
  max-width: 100%;
}

.status-chip {
  font-size: 12px !important;
  line-height: 16px !important;
  font-weight: 600 !important;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
  height: 20px !important;
  padding: 0 6px !important;
  min-width: 60px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08) !important;
  border: 1px solid transparent !important;
  letter-spacing: 0.1px !important;
  transition: all 0.2s ease !important;
}

.status-chip-pawal {
  background: var(--color-primary-600) !important;
  color: white !important;
  border-color: var(--color-primary-700) !important;
}

.status-chip-pawal:hover {
  background: var(--color-primary-700) !important;
  box-shadow: 0 2px 4px rgba(255, 165, 50, 0.2) !important;
  transform: translateY(-1px);
}

.status-chip-tindakan {
  background: var(--color-secondary-600) !important;
  color: white !important;
  border-color: var(--color-secondary-700) !important;
}

.status-chip-tindakan:hover {
  background: var(--color-secondary-700) !important;
  box-shadow: 0 2px 4px rgba(6, 113, 224, 0.2) !important;
  transform: translateY(-1px);
}

.status-chip .v-icon {
  font-size: 12px !important;
  margin-right: 4px !important;
  color: white !important;
}

/* Right Section: Actions */
.patient-card-right {
  display: none;
}

.patient-queue-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: nowrap;
  justify-content: flex-end;
  min-width: fit-content;
  max-width: 100%;
  box-sizing: border-box;
}

.patient-queue-actions .v-btn {
  text-transform: none;
  font-weight: 600;
  font-size: 13px;
  line-height: 18px;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  flex-shrink: 0;
  min-height: 38px;
  padding: 8px 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
  white-space: nowrap;
  max-width: 100%;
  box-sizing: border-box;
}

.patient-queue-actions .v-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.patient-queue-actions .v-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.patient-queue-actions .v-btn.variant--text {
  box-shadow: none;
  min-height: 38px;
  padding: 8px;
  flex-shrink: 0;
  min-width: 38px;
}

.patient-queue-actions .v-btn.variant--text:hover {
  background: rgba(0, 0, 0, 0.05);
  transform: scale(1.1);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.patient-queue-actions .v-btn.variant--text:active {
  transform: scale(1.05);
}

.call-btn {
  min-width: 160px;
  font-size: 13px;
  line-height: 18px;
  white-space: nowrap;
  padding: 8px 18px;
  max-width: fit-content;
  box-sizing: border-box;
}

.call-btn .v-icon {
  margin-right: 6px;
  flex-shrink: 0;
}

/* Responsive untuk card */
@media (max-width: 1400px) {
  .room-card {
    min-width: 700px;
    max-width: 700px;
    width: 700px;
  }
  
  .patient-queue-item {
    padding: 10px 16px;
    gap: 4px;
  }
  
  .patient-card-left-group {
    min-width: 140px;
  }
  
  .patient-card-right-group {
    min-width: 300px;
  }
  
  .patient-queue-actions {
    gap: 8px;
    flex-wrap: nowrap;
  }
  
  .patient-queue-actions .v-btn {
    font-size: 12px;
    line-height: 16px;
    min-height: 36px;
    padding: 7px 14px;
  }
  
  .call-btn {
    min-width: 140px;
    font-size: 12px;
    line-height: 16px;
    padding: 7px 16px;
  }
  
  .call-btn .v-icon {
    margin-right: 4px;
  }
  
  .patient-queue-actions .v-btn.variant--text {
    padding: 7px;
    min-width: 36px;
  }
  
  .action-grid {
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
  
  .action-grid .v-btn {
    font-size: 12px;
    padding: 6px 12px;
    min-height: 36px;
  }
  
  .action-grid .v-btn .v-icon {
    font-size: 16px;
  }
  
  .action-icon-btn {
    height: 32px !important;
  }
}

@media (max-width: 960px) {
  .room-card {
    min-width: 100%;
    max-width: 100%;
    width: 100%;
  }
  
  .patient-queue-item {
    padding: 8px 12px;
    gap: 2px;
  }
  
  .patient-card-header-row {
    gap: 8px;
  }

  .patient-card-left-group {
    min-width: auto;
  }
  
  .patient-card-right-group {
    min-width: auto;
  }
  
  .patient-queue-actions {
    width: auto;
    justify-content: flex-end;
    flex-wrap: nowrap;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
  }
  
  .patient-queue-actions::-webkit-scrollbar {
    display: none;
  }
  
  .global-search-field {
    max-width: 100%;
  }
  
  .sort-select {
    max-width: 150px !important;
  }
  
  .action-grid {
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
  
  .action-grid .v-btn {
    font-size: 11px;
    padding: 6px 8px;
    min-height: 36px;
  }
  
  .action-grid .v-btn .v-icon {
    font-size: 14px;
  }
  
  .action-icon-btn {
    height: 32px !important;
  }
  
  .action-icon-btn .v-icon {
    font-size: 16px;
  }
  
  .action-icon-btn {
    min-width: 32px !important;
    width: 32px !important;
    height: 32px !important;
  }
  
  .action-icon-btn .v-icon {
    font-size: 16px;
  }
  
  .patient-queue-actions {
    gap: 4px;
    flex-wrap: nowrap;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
  }
  
  .patient-queue-actions::-webkit-scrollbar {
    display: none;
  }
  
  .patient-queue-actions .v-btn {
    font-size: 10px;
    line-height: 14px;
    min-height: 32px;
    padding: 6px 8px;
  }
  
  .call-btn {
    min-width: 100px;
    font-size: 10px;
    line-height: 14px;
    padding: 6px 8px;
  }
  
  .call-btn .v-icon {
    margin-right: 2px;
    font-size: 14px;
  }
  
  .patient-queue-actions .v-btn.variant--text {
    padding: 6px;
    min-width: 32px;
  }
  
  .patient-queue-actions .v-btn .v-icon {
    font-size: 16px;
  }

  .search-actions-row {
    flex-direction: column;
    align-items: stretch;
  }

  .global-search-field {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .btn-pindah-pasien {
    width: 100%;
  }
  
  .ruang-selection-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 8px;
  }
  
  .ruang-selection-card {
    min-height: 70px;
    padding: 12px;
  }
  
  .ruang-selection-name {
    font-size: 13px;
    line-height: 18px;
  }
  
  .ruang-selection-number {
    font-size: 11px;
    line-height: 14px;
  }
}

/* Dialog Pindah Ruang Styles */
.pindah-ruang-step {
  width: 100%;
}

.step-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  line-height: 24px;
  font-weight: 600;
  color: var(--color-neutral-900);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.headline-5 {
  font-size: 18px;
  line-height: 24px;
  font-weight: 600;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.patient-selection-list {
  max-height: 400px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.patient-selection-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: var(--color-neutral-100);
  border: 2px solid var(--color-neutral-300);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.patient-selection-card:hover {
  background: var(--color-neutral-200);
  border-color: var(--color-primary-400);
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.patient-selection-card-selected {
  background: var(--color-primary-100);
  border-color: var(--color-primary-600);
  box-shadow: 0 2px 8px rgba(255, 152, 0, 0.2);
}

.patient-selection-info {
  flex: 1;
}

.patient-selection-number {
  font-size: 16px;
  line-height: 24px;
  font-weight: 700;
  color: var(--color-neutral-900);
  margin-bottom: 4px;
}

.patient-selection-details {
  font-size: 12px;
  line-height: 16px;
  color: var(--color-neutral-600);
}

.patient-selection-room {
  display: flex;
  align-items: center;
  font-size: 12px;
  line-height: 16px;
  color: var(--color-neutral-600);
}

.empty-patient-list {
  text-align: center;
  padding: 40px 20px;
  background: var(--color-neutral-200);
  border-radius: 8px;
  border: 1px dashed var(--color-neutral-400);
}

.selected-patient-simple {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: var(--color-primary-100);
  border: 1px solid var(--color-primary-300);
  border-radius: 8px;
  margin-bottom: 16px;
}

.selected-patient-simple-text {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.selected-patient-simple-label {
  font-size: 12px;
  line-height: 16px;
  color: var(--color-neutral-600);
  font-weight: 500;
}

.selected-patient-simple-value {
  font-size: 14px;
  line-height: 20px;
  font-weight: 600;
  color: var(--color-neutral-900);
}

.selected-patient-simple-room {
  font-size: 12px;
  line-height: 16px;
  color: var(--color-neutral-600);
}

.ruang-selection-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.ruang-selection-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background: var(--color-neutral-100);
  border: 1px solid var(--color-neutral-400);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: center;
  min-height: 80px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.ruang-selection-card:hover:not(.ruang-selection-card-disabled) {
  background: var(--color-neutral-200);
  border-color: var(--color-primary-400);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.ruang-selection-card:active:not(.ruang-selection-card-disabled) {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.ruang-selection-card-selected {
  background: var(--color-primary-100);
  border-color: var(--color-primary-600);
  box-shadow: 0 2px 8px rgba(255, 152, 0, 0.2);
}

.ruang-selection-card-selected:hover {
  background: var(--color-primary-200);
  border-color: var(--color-primary-700);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 152, 0, 0.3);
}

.ruang-selection-card-disabled {
  background: var(--color-neutral-200);
  border-color: var(--color-neutral-400);
  cursor: not-allowed;
  opacity: 0.6;
}

.ruang-selection-card-disabled:hover {
  transform: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.ruang-selection-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  gap: 4px;
}

.ruang-selection-name {
  font-size: 14px;
  line-height: 20px;
  font-weight: 600;
  color: var(--color-neutral-900);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.ruang-selection-number {
  font-size: 12px;
  line-height: 16px;
  color: var(--color-neutral-600);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

/* Action Selection Styles */
.action-selection-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-top: 16px;
}

.action-selection-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 24px 16px;
  background: var(--color-neutral-100);
  border: 2px solid var(--color-neutral-400);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: center;
  min-height: 140px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.action-selection-card:hover {
  background: var(--color-neutral-200);
  border-color: var(--color-primary-400);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.action-selection-card:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.action-selection-name {
  font-size: 16px;
  line-height: 24px;
  font-weight: 600;
  color: var(--color-neutral-900);
  margin-top: 8px;
  margin-bottom: 4px;
}

/* Klinik Ruang Selection Styles - Expansion Panels */
.expansion-panels {
  background: transparent;
}

.expansion-panel {
  background: var(--color-neutral-100);
  border: 1px solid var(--color-neutral-400);
  border-radius: 12px !important;
  margin-bottom: 12px;
  overflow: hidden;
}

.expansion-panel::before {
  box-shadow: none !important;
}

.expansion-title {
  background: var(--color-neutral-100);
  min-height: 60px;
}

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

/* Ruang List replacement with common grid styles */
.expansion-panel-text :deep(.v-expansion-panel-text__wrapper) {
  padding: 8px 16px 16px !important;
}

.ruang-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* Filter and Sort Actions */
.filter-sort-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.btn-filter {
  text-transform: none !important;
  font-weight: 600 !important;
  font-size: 13px !important;
  line-height: 18px !important;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
  min-height: 36px !important;
  padding: 6px 16px !important;
  border-color: var(--color-neutral-400) !important;
  color: var(--color-neutral-700) !important;
  transition: all 0.2s ease !important;
}

.btn-filter:hover {
  background-color: var(--color-neutral-200) !important;
  border-color: var(--color-primary-400) !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* Filter Dialog Styles */
.filter-dialog-card {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.filter-dialog-content {
  padding: 24px !important;
  background: var(--color-neutral-300);
  max-height: 600px;
  overflow-y: auto;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-section:last-child {
  margin-bottom: 0;
}

.filter-section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.filter-section-title {
  font-size: 16px;
  line-height: 24px;
  font-weight: 600;
  color: var(--color-neutral-900);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.filter-chip-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-chip {
  font-size: 12px !important;
  font-weight: 600 !important;
  height: 32px !important;
  border: 1px solid var(--color-neutral-500) !important;
  background: var(--color-neutral-100) !important;
  color: var(--color-neutral-600) !important;
  transition: all 0.2s ease !important;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
  text-transform: none !important;
  cursor: pointer !important;
}

.filter-chip:hover {
  background: var(--color-neutral-300) !important;
}

.filter-chip.active-chip {
  background: var(--color-secondary-600) !important;
  color: var(--color-neutral-100) !important;
  border-color: var(--color-secondary-600) !important;
}

.btn-reset-filter {
  text-transform: none !important;
  font-weight: 500 !important;
  font-size: 14px !important;
  color: var(--color-neutral-600) !important;
  transition: all 0.2s ease !important;
}

.btn-reset-filter:hover {
  color: var(--color-primary-600) !important;
  background-color: var(--color-primary-50) !important;
}

@media (max-width: 960px) {
  .filter-chip-group {
    gap: 6px;
  }

  .filter-chip {
    height: 28px !important;
    font-size: 11px !important;
  }
}

/* Patient Detail Redesign Styles */
.patient-detail-card {
  border-radius: 16px !important;
  overflow: hidden;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.patient-hero-section {
  background: linear-gradient(135deg, var(--color-primary-50) 0%, #fff 100%);
  padding: 24px 20px;
  text-align: center;
  border-bottom: 1px solid var(--color-neutral-300);
}

.hero-label {
  font-size: 11px;
  text-transform: uppercase;
  letter-spacing: 1px;
  color: var(--color-neutral-700);
  margin-bottom: 4px;
  font-weight: 700;
}

.hero-number {
  font-size: 42px;
  line-height: 1.2;
  font-weight: 800;
  color: var(--color-neutral-900);
  margin-bottom: 8px;
  letter-spacing: -1px;
}

.status-chip-hero {
  font-weight: 600 !important;
  font-size: 13px !important;
  padding: 0 12px !important;
  height: 28px !important;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.fast-track-banner {
  background: linear-gradient(90deg, #d32f2f, #e53935);
  color: white;
  padding: 10px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(211, 47, 47, 0.2);
  font-size: 14px;
  letter-spacing: 0.5px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px 24px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item.text-right {
  text-align: right;
  align-items: flex-end;
}

.info-item.full-width {
  grid-column: 1 / -1;
  text-align: left;
  align-items: flex-start;
}

.info-label {
  font-size: 12px;
  color: var(--color-neutral-600);
  font-weight: 600;
}

.info-value {
  font-size: 15px;
  color: var(--color-neutral-900);
  font-weight: 700;
}

.section-label-small {
  font-size: 11px;
  color: var(--color-neutral-600);
  font-weight: 800;
  text-transform: uppercase;
  letter-spacing: 0.8px;
}

.service-actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.service-action-card {
  border: 1px solid var(--color-neutral-300);
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  background: var(--color-neutral-50);
  transition: all 0.2s ease;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 12px;
}

.service-action-card:hover {
  background: white;
  border-color: var(--color-primary-300);
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  transform: translateY(-2px);
}

.service-action-card.active {
  background: var(--color-primary-50);
  border-color: var(--color-primary-500);
}

.service-action-card.active:nth-child(2) {
  background: var(--color-secondary-50);
  border-color: var(--color-secondary-500);
}

.action-icon-wrapper {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border: 1px solid rgba(0,0,0,0.05);
}

.service-action-card.active .action-icon-wrapper {
  background: white;
}

.color-primary { color: var(--color-primary-600); }
.color-secondary { color: var(--color-secondary-600); }

.action-content {
  flex: 1;
}

.action-title {
  font-size: 13px;
  font-weight: 700;
  color: var(--color-neutral-900);
  margin-bottom: 2px;
  line-height: 1.3;
}

.action-status {
  font-size: 11px;
  color: var(--color-neutral-500);
}

.service-action-card.active .action-title {
  color: var(--color-primary-800);
}

.service-action-card.active:nth-child(2) .action-title {
  color: var(--color-secondary-800);
}

.check-icon {
  position: absolute;
  top: 12px;
  right: 12px;
}

.btn-close-large {
  text-transform: none;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: 0;
}
</style>

