<template>
  <div v-if="anjunganData">
    <div class="page-header">
      <div class="header-icon">
        <img
          src="/Rumah_Sakit_Umum_Daerah_Dr._Saiful_Anwar.webp"
          alt="RSUD Logo"
          class="header-logo"
          width="40"
          height="40"
          style="width: 40px; height: 40px; object-fit: contain"
        />
      </div>
      <div class="header-content">
        <h1 class="page-title">{{ anjunganData.namaAnjungan }}</h1>
        <p class="page-subtitle">
          Pilih Klinik untuk Pendaftaran - {{ anjunganData.jenisPasien }}
        </p>
      </div>
    </div>

    <div class="anjungan-container">
      <div v-if="filteredClinics.length > 0" class="clinic-grid">
        <v-card
          v-for="clinic in filteredClinics"
          :key="clinic.id"
          :class="{
            'clinic-card': true,
            'clinic-available': clinic.available,
            'clinic-closed': !clinic.available,
          }"
          :disabled="!clinic.available"
          @click="selectClinic(clinic)"
          elevation="0"
        >
          <v-card-text class="clinic-content">
            <h3 class="clinic-name">
              {{ clinic.name }}
            </h3>

            <div class="doctor-info">
              <v-icon
                size="14"
                :color="
                  clinic.available
                    ? 'var(--color-primary-600)'
                    : 'var(--color-neutral-600)'
                "
              >
                mdi-doctor
              </v-icon>
              <span>{{ getDisplayDoctorInfo(clinic) }}</span>
            </div>

            <div class="schedule-info">
              <v-icon
                size="12"
                :color="
                  clinic.available
                    ? 'var(--color-neutral-600)'
                    : 'var(--color-neutral-600)'
                "
              >
                mdi-clock-outline
              </v-icon>
              <span>{{ clinic.schedule || "Tidak tersedia" }}</span>
            </div>

            <div class="clinic-icon-wrapper">
              <v-icon
                :icon="clinic.icon"
                size="28"
                :color="
                  clinic.available
                    ? 'var(--color-primary-600)'
                    : 'var(--color-neutral-100)'
                "
              ></v-icon>
            </div>
          </v-card-text>
        </v-card>
      </div>

      <div v-if="filteredClinics.length === 0" class="empty-state">
        <v-icon size="48" color="grey-lighten-1"
          >mdi-hospital-marker-outline</v-icon
        >
        <h3 class="empty-title">Tidak ada klinik yang sesuai</h3>
        <p class="empty-subtitle">
          Anjungan ini belum memiliki klinik terpilih
        </p>
      </div>

      <v-dialog
        v-model="showVisitTypeDialog"
        max-width="900"
        @click:outside="showVisitTypeDialog = false"
      >
        <v-card class="dialog-card">
          <v-card-title class="dialog-header">
            <v-icon size="20" class="mr-2">mdi-check-circle</v-icon>
            Konfirmasi Pilihan
            <v-btn
              icon
              class="dialog-close-btn"
              size="small"
              @click="showVisitTypeDialog = false"
            >
              <v-icon size="20" color="white">mdi-close</v-icon>
            </v-btn>
          </v-card-title>

          <v-card-text class="pa-6" v-if="selectedClinic">
            <div class="dialog-content">
              <div class="dialog-icon mb-3">
                <v-icon
                  :icon="selectedClinic.icon"
                  size="32"
                  color="primary-600"
                ></v-icon>
              </div>
              <h3 class="dialog-clinic-name">{{ selectedClinic.name }}</h3>
              <p v-if="selectedClinic.subtitle" class="dialog-subtitle">
                {{ selectedClinic.subtitle }}
              </p>

              <v-divider class="my-4"></v-divider>

              <div class="dialog-info">
                <!-- Section Kuota -->
                <div class="quota-section mb-6">
                  <p>
                    <strong
                      >Kuota Hari Ini (Shift
                      {{ getCurrentShiftNumber() }}):</strong
                    >
                  </p>
                  <div
                    class="current-quota-display"
                    :class="{ 'quota-empty': getCurrentShiftQuota() === 0 }"
                  >
                    <span class="quota-large-number">{{
                      getCurrentShiftQuota()
                    }}</span>
                    <span class="quota-label">pasien tersedia</span>
                  </div>
                </div>

                <v-divider class="mb-6"></v-divider>

                <!-- Section Pemilihan Dokter untuk Pasien Eksekutif -->
                <div v-if="isEksekutif" class="doctor-selection-section mb-4">
                  <p class="mb-3"><strong>Pilih Dokter:</strong></p>
                  <div class="doctor-buttons-container">
                    <div
                      v-for="(doctor, index) in dialogDoctors"
                      :key="index"
                      class="doctor-button-wrapper"
                    >
                      <v-btn
                        :class="{
                          'doctor-button': true,
                          'doctor-button-selected': selectedDoctor === doctor,
                        }"
                        variant="outlined"
                        size="large"
                        block
                        @click="selectedDoctor = doctor"
                      >
                        <v-icon
                          v-if="selectedDoctor === doctor"
                          size="16"
                          color="success-600"
                          class="doctor-icon"
                        >
                          mdi-check-circle
                        </v-icon>
                        <v-icon
                          v-else
                          size="16"
                          color="neutral-600"
                          class="doctor-icon"
                        >
                          mdi-circle-outline
                        </v-icon>
                        <span class="doctor-name">{{ doctor }}</span>
                      </v-btn>
                    </div>
                    <p
                      v-if="dialogDoctors.length === 0"
                      class="text-error text-caption mt-2"
                    >
                      Tidak ada dokter tersedia untuk klinik ini
                    </p>
                  </div>
                </div>

                <!-- Section Info Dokter untuk Non-Eksekutif (hanya tampil) -->
                <div v-else class="doctor-list-section">
                  <p class="mb-2"><strong>Dokter yang Tersedia:</strong></p>
                  <div
                    v-if="dialogDoctors.length > 0"
                    class="doctor-info-unified"
                  >
                    <div
                      v-for="(doctor, index) in dialogDoctors"
                      :key="index"
                      class="doctor-info-unit"
                    >
                      <v-icon size="16" color="primary-600" class="mr-2 mt-1">
                        mdi-doctor
                      </v-icon>
                      <span class="doctor-info-name-unified">{{ doctor }}</span>
                    </div>
                  </div>
                  <p v-else class="text-error text-caption italic">
                    Tidak ada dokter tersedia untuk klinik ini
                  </p>
                </div>

                <p><strong>Jadwal:</strong> {{ selectedClinic.schedule }}</p>
              </div>
            </div>
          </v-card-text>

          <v-divider />

          <v-card-text class="pa-4">
            <!-- For Eksekutif: Show DAFTAR SEKARANG button -->
            <div v-if="isEksekutif">
              <v-row dense>
                <v-col cols="12">
                  <v-btn
                    color="success-600"
                    class="text-white"
                    size="large"
                    block
                    @click="registerPatientDirectly('Eksekutif')"
                    :disabled="isShift1Full(selectedClinic) || !selectedDoctor"
                    :class="{
                      'btn-disabled':
                        isShift1Full(selectedClinic) || !selectedDoctor,
                    }"
                  >
                    DAFTAR SEKARANG
                  </v-btn>
                  <p v-if="isShift1Full(selectedClinic)" class="disabled-hint">
                    Kuota hari ini habis
                  </p>
                  <p v-else-if="!selectedDoctor" class="disabled-hint">
                    Pilih dokter terlebih dahulu
                  </p>
                </v-col>
              </v-row>
            </div>

            <!-- For Non-Eksekutif: Show payment type buttons and action buttons -->
            <div v-else>
              <!-- Row 1: BPJS and UMUM -->
              <v-row dense>
                <v-col cols="6">
                  <v-btn
                    color="success-600"
                    class="text-white payment-type-btn"
                    size="large"
                    block
                    @click="registerPatientDirectly('BPJS')"
                    :disabled="isShift1Full(selectedClinic)"
                    :class="{ 'btn-disabled': isShift1Full(selectedClinic) }"
                  >
                    BPJS
                  </v-btn>
                </v-col>
                <v-col cols="6">
                  <v-btn
                    color="secondary-600"
                    class="text-white payment-type-btn"
                    size="large"
                    block
                    @click="registerPatientDirectly('UMUM')"
                    :disabled="isShift1Full(selectedClinic)"
                    :class="{ 'btn-disabled': isShift1Full(selectedClinic) }"
                  >
                    UMUM / JKMM / SPM / DLL
                  </v-btn>
                </v-col>
              </v-row>

              <p v-if="isShift1Full(selectedClinic)" class="disabled-hint mt-2">
                Kuota hari ini habis
              </p>

              <!-- Row 2: JADWAL LAIN and Fast Track -->
              <v-row dense class="mt-3">
                <v-col cols="6">
                  <v-btn
                    color="primary-600"
                    class="text-white payment-type-btn"
                    size="large"
                    block
                    @click="selectVisitType('JADWAL_LAIN')"
                  >
                    JADWAL LAIN
                  </v-btn>
                </v-col>
                <v-col cols="6">
                  <v-btn
                    color="danger-600"
                    class="text-neutral-900 text-white"
                    size="large"
                    block
                    @click="registerPatientDirectly('FAST_TRACK')"
                    :disabled="isShift1Full(selectedClinic)"
                    :class="{ 'btn-disabled': isShift1Full(selectedClinic) }"
                  >
                    FAST TRACK
                  </v-btn>
                </v-col>
              </v-row>
            </div>

            <!-- JADWAL LAIN button for eksekutif -->
            <v-row v-if="isEksekutif" dense class="mt-3">
              <v-col cols="12">
                <v-btn
                  color="primary-600"
                  class="text-white"
                  size="large"
                  block
                  @click="selectVisitType('JADWAL_LAIN')"
                  :disabled="!selectedDoctor"
                  :class="{ 'btn-disabled': !selectedDoctor }"
                >
                  JADWAL LAIN
                </v-btn>
                <p v-if="!selectedDoctor" class="disabled-hint">
                  Pilih dokter terlebih dahulu
                </p>
              </v-col>
            </v-row>
          </v-card-text>
        </v-card>
      </v-dialog>

      <!-- Dialog Pemilihan Dokter untuk Pasien Eksekutif -->
      <v-dialog
        v-model="showDoctorSelectionDialog"
        max-width="600"
        @click:outside="showDoctorSelectionDialog = false"
      >
        <v-card class="dialog-card">
          <v-card-title class="dialog-header">
            <v-icon class="mr-2">mdi-doctor</v-icon>
            Pilih Dokter
          </v-card-title>
          <v-divider />
          <v-card-text class="pa-6" v-if="selectedClinic">
            <div class="dialog-content">
              <p class="mb-4">
                <strong>Klinik:</strong> {{ selectedClinic.name }}
              </p>
              <v-select
                v-model="selectedDoctor"
                :items="dialogDoctors"
                label="Pilih Dokter"
                variant="outlined"
                density="compact"
                required
                :rules="[(v) => !!v || 'Pilih dokter terlebih dahulu']"
                class="mb-3"
              >
                <template v-slot:item="{ props, item }">
                  <v-list-item v-bind="props">
                    <v-list-item-title>{{ item.raw }}</v-list-item-title>
                  </v-list-item>
                </template>
              </v-select>
              <p
                v-if="dialogDoctors.length === 0"
                class="text-error text-caption"
              >
                Tidak ada dokter tersedia untuk klinik ini
              </p>
            </div>
          </v-card-text>
          <v-divider />
          <v-card-actions class="pa-4">
            <v-spacer />
            <v-btn
              variant="outlined"
              color="neutral-600"
              @click="showDoctorSelectionDialog = false"
            >
              Batal
            </v-btn>
            <v-btn
              color="success-600"
              class="text-white"
              variant="flat"
              @click="confirmDoctorSelection"
              :disabled="!selectedDoctor || dialogDoctors.length === 0"
            >
              Konfirmasi
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <v-dialog
        v-model="showBookingFormDialog"
        max-width="600"
        @click:outside="showBookingFormDialog = false"
      >
        <v-card class="dialog-card">
          <v-card-title class="dialog-header">
            Pilih Jadwal Kunjungan
          </v-card-title>
          <v-card-text class="pa-6">
            <v-form @submit.prevent="submitBooking">
              <v-text-field
                v-model="bookingForm.date"
                label="Tanggal"
                type="date"
                variant="outlined"
                density="compact"
                required
                class="mb-3"
                :min="getMinDate()"
                :max="getMaxDate()"
              ></v-text-field>

              <v-select
                v-model="bookingForm.shift"
                :items="getAvailableShiftsForBooking()"
                item-title="label"
                item-value="value"
                label="Pilih Shift"
                variant="outlined"
                density="compact"
                required
                class="mb-3"
              ></v-select>

              <v-select
                v-model="bookingForm.payment"
                :items="['BPJS', 'UMUM/JKMM/SPM/DLL']"
                label="Pembayaran"
                variant="outlined"
                density="compact"
                required
                class="mb-3"
              ></v-select>

              <!-- Field dokter untuk pasien Eksekutif (sudah dipilih di dialog sebelumnya) -->
              <v-text-field
                v-if="isEksekutif && bookingForm.doctor"
                :model-value="bookingForm.doctor"
                label="Dokter yang Dipilih"
                variant="outlined"
                density="compact"
                readonly
                class="mb-3"
              >
                <template v-slot:prepend-inner>
                  <v-icon size="16" color="success-600"
                    >mdi-check-circle</v-icon
                  >
                </template>
              </v-text-field>
            </v-form>
          </v-card-text>
          <v-card-actions class="pa-4">
            <v-spacer />
            <v-btn
              @click="showBookingFormDialog = false"
              variant="outlined"
              color="neutral-600"
            >
              Tutup
            </v-btn>
            <v-btn
              color="success-600"
              class="text-white"
              variant="flat"
              @click="submitBooking"
            >
              Simpan
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <!-- Fast Track Dialog -->
      <v-dialog
        v-model="showFastTrackDialog"
        max-width="600"
        @click:outside="showFastTrackDialog = false"
      >
        <v-card class="dialog-card">
          <v-card-title class="dialog-header">
            <v-icon class="mr-2">mdi-fast-forward</v-icon>
            Formulir Fast Track
          </v-card-title>
          <v-divider />
          <v-card-text class="pa-6">
            <v-form>
              <v-text-field
                v-model="fastTrackForm.penanggungJawab"
                label="Penanggung Jawab"
                variant="outlined"
                density="compact"
                required
                class="mb-3"
                :rules="[(v) => !!v || 'Mohon isi Penanggung Jawab']"
              />

              <v-textarea
                v-model="fastTrackForm.alasanFastTrack"
                label="Alasan Fast Track"
                variant="outlined"
                density="compact"
                required
                rows="3"
                class="mb-3"
                :rules="[(v) => !!v || 'Mohon isi Alasan Fast Track']"
              />

              <!-- Jenis Pembayaran hanya untuk non-Eksekutif -->
              <v-select
                v-if="!isEksekutif"
                v-model="fastTrackForm.jenisPembayaran"
                :items="['BPJS', 'UMUM']"
                label="Jenis Pembayaran"
                variant="outlined"
                density="compact"
                required
                class="mb-3"
                :rules="[(v) => !!v || 'Mohon pilih Jenis Pembayaran']"
              />
            </v-form>
          </v-card-text>
          <v-divider />
          <v-card-actions class="pa-4">
            <v-spacer />
            <v-btn
              variant="outlined"
              color="neutral-600"
              @click="showFastTrackDialog = false"
            >
              Batal
            </v-btn>
            <v-btn
              color="success-600"
              class="text-white"
              variant="flat"
              @click="submitFastTrackForm"
            >
              Lanjutkan
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <!-- Print Dialog -->
      <v-dialog
        v-model="showPrintDialog"
        max-width="500"
        @click:outside="skipPrint"
      >
        <v-card class="dialog-card">
          <v-card-title class="dialog-header">
            <v-icon class="mr-2">mdi-printer</v-icon>
            Cetak Nomor Antrian
          </v-card-title>
          <v-divider />
          <v-card-text class="pa-6">
            <div v-if="lastRegisteredPatient" class="dialog-content">
              <div class="text-center mb-4">
                <v-icon size="48" color="primary-600" class="mb-3"
                  >mdi-ticket-confirmation</v-icon
                >
                <h3 class="dialog-clinic-name mb-2">Tiket Berhasil Dibuat</h3>
                <p class="text-body-2 text-grey mb-4">
                  Nomor antrean Anda:
                  <strong>{{
                    lastRegisteredPatient.noAntrian?.split(" |")[0] ||
                    lastRegisteredPatient.noAntrian ||
                    "N/A"
                  }}</strong>
                </p>
              </div>

              <v-divider class="my-4" />

              <div class="dialog-info">
                <div class="info-row mb-3">
                  <span class="info-label">Klinik:</span>
                  <span class="info-value">{{
                    lastRegisteredPatient.klinik || "N/A"
                  }}</span>
                </div>
                <div class="info-row mb-3">
                  <span class="info-label">Shift:</span>
                  <span class="info-value">{{
                    lastRegisteredPatient.shift || "N/A"
                  }}</span>
                </div>
                <div class="info-row mb-3">
                  <span class="info-label">Pembayaran:</span>
                  <span class="info-value">{{
                    lastRegisteredPatient.pembayaran || "N/A"
                  }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">Barcode:</span>
                  <span class="info-value">{{
                    lastRegisteredPatient.barcode || "N/A"
                  }}</span>
                </div>
              </div>

              <v-alert
                type="info"
                variant="tonal"
                class="mt-4"
                density="compact"
              >
                <template v-slot:prepend>
                  <v-icon size="20">mdi-information</v-icon>
                </template>
                <div class="text-body-2">
                  Cetak tiket ini untuk digunakan saat check-in. QR Code pada
                  tiket dapat di-scan untuk proses check-in.
                </div>
              </v-alert>
            </div>
            <div v-else class="text-center py-6">
              <v-progress-circular
                indeterminate
                color="primary-600"
                class="mb-3"
              ></v-progress-circular>
              <p class="text-body-2 text-grey">Memuat data tiket...</p>
            </div>
          </v-card-text>
          <v-card-actions class="pa-4 pt-0 justify-center">
            <v-btn
              color="primary-600"
              class="text-white print-ticket-btn"
              size="x-large"
              variant="flat"
              @click="handlePrintTicket"
              :loading="isPrinting"
              :disabled="isPrinting"
              prepend-icon="mdi-printer"
              min-width="240"
              min-height="64"
              rounded="lg"
              elevation="4"
            >
              Cetak Tiket
            </v-btn>
          </v-card-actions>
          <v-card-actions class="pa-4 pt-0 justify-center">
            <v-btn
              variant="outlined"
              color="neutral-600"
              @click="skipPrint"
              :disabled="isPrinting"
              class="finish-btn"
              min-width="240"
              min-height="56"
              rounded="lg"
            >
              Selesai
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <v-snackbar
        v-model="snackbar"
        :color="snackbarColor"
        :timeout="3000"
        location="top right"
      >
        {{ snackbarText }}
        <template v-slot:actions>
          <v-btn icon @click="snackbar = false">
            <v-icon size="20">mdi-close</v-icon>
          </v-btn>
        </template>
      </v-snackbar>
    </div>
  </div>
  <div v-if="!anjunganData" class="not-found">
    <v-icon size="64" color="grey">mdi-alert-circle-outline</v-icon>
    <p>Anjungan tidak ditemukan</p>
    <v-btn color="primary" variant="flat" @click="backToList">Kembali</v-btn>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from "vue";
import { useRoute } from "#app";
import { storeToRefs } from "pinia";
import { useAnjunganStore } from "@/stores/anjunganStore";
import { useClinicStore } from "@/stores/clinicStore";
import { useQueueStore } from "@/stores/queueStore";
import { useDoctorStore } from "@/stores/doctorStore";
import { useWebSocket } from "@/composables/useWebSocket";
import { useThermalPrint } from "@/composables/useThermalPrint";

definePageMeta({
  layout: false,
});

const route = useRoute();
const anjunganStore = useAnjunganStore();
const clinicStore = useClinicStore();
const queueStore = useQueueStore();
const doctorStore = useDoctorStore();
const { printTicketFromPatient, isPrinting } = useThermalPrint();

// reactive refs from stores
const { anjunganItems } = storeToRefs(anjunganStore);
const { getAllClinics } = storeToRefs(clinicStore);
const { doctorsByKlinikId, loadingDoctors } = storeToRefs(doctorStore);

const anjunganId = computed(() => {
  const raw = route.params.id;
  const val = Array.isArray(raw) ? raw[0] : raw;
  const parsed = parseInt(val, 10);
  return isNaN(parsed) ? null : parsed;
});

const anjunganData = computed(() => {
  const idValue = anjunganId.value;
  if (!idValue) return null;

  // Use the refs from storeToRefs
  const list = anjunganItems.value || [];
  return list.find((a) => Number(a.id) === Number(idValue)) || null;
});

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

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

const fetchAllData = async () => {
  if (!anjunganId.value) return;
  console.log('🔄 Anjungan refresh: Fetching clinics and initial data...');
  try {
    if (anjunganData.value?.jenisPasien === "Reguler") {
      await clinicStore.fetchRegulerClinics();
    }
    queueStore.ensureInitialData();
    console.log('✅ Anjungan refresh: Success');
  } catch (err) {
    console.error('❌ Anjungan refresh error:', err);
  }
};

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

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

onMounted(async () => {
  console.log("🚀 Anjungan Component mounted");
  
  // Wait for stores to be hydrated and ready
  await nextTick();
  
  // Initial fetch
  await fetchAllData();

  // Use centralized WebSocket
  queueStore.initWebSocket(anjunganClientId.value);

  onUnmounted(() => {
    // wsInstance is now global
  });
});

// Lifecycle management consolidated below

// Validasi bahwa queueStore ter-load dengan benar
onMounted(() => {
  console.log("🔍 QueueStore initialized:", queueStore);
  console.log(
    "🔍 registerPatientFromAnjungan available:",
    typeof queueStore.registerPatientFromAnjungan,
  );
  if (typeof queueStore.registerPatientFromAnjungan !== "function") {
    console.error("❌ registerPatientFromAnjungan is not a function!");
    console.error("Available methods:", Object.keys(queueStore));
  }
});

// Initial data synchronization handled in watcher and onMounted

// doctorsByKlinikId and loadingDoctors are now from doctorStore

// Load doctors dari store
const loadDoctorsForClinic = async (clinic) => {
  await doctorStore.fetchDoctorsForClinic(clinic);
};

const prefetchDoctorsForCurrentAnjungan = async () => {
  if (!anjunganData.value || !anjunganData.value.klinik) {
    console.warn("⚠️ No anjungan data or klinik data available");
    return;
  }

  // Get all matched clinics for this anjungan (already filtered by type)
  const clinicsForAnjungan = filteredClinics.value;

  console.log(
    `🔄 Prefetching doctors for ${clinicsForAnjungan.length} klinik (${anjunganData.value.jenisPasien})`,
  );

  // Fetch doctors sequentially to avoid overwhelming the server
  for (const clinic of clinicsForAnjungan) {
    await loadDoctorsForClinic(clinic);
    // Tiny delay between requests
    await new Promise((resolve) => setTimeout(resolve, 30));
  }

  console.log(
    "✅ Prefetch complete. Doctors by klinik ID:",
    doctorsByKlinikId.value,
  );
};

const dialogDoctors = computed(() => {
  const clinic = selectedClinic.value;
  if (!clinic || !clinic.id) return [];

  const idklinik = clinic.id;
  const apiDoctors = doctorsByKlinikId.value[idklinik];

  // prioritas: API > Static
  if (apiDoctors && apiDoctors.length > 0) {
    return apiDoctors;
  }

  // fallback ke static data
  const staticDoctors = clinic.doctors || [];

  if (staticDoctors.length > 0) {
    console.log(
      `ℹ️ Using static doctors for ${clinic.name} (API data not available)`,
    );
  }

  return staticDoctors;
});

// Cleanup saat component unmount (Preserved old code in comments)
/*
import { onUnmounted } from "vue";
onUnmounted(() => {
  if (wsInstance) {
    wsInstance.disconnect();
  }
});
*/

const filteredClinics = computed(() => {
  if (!anjunganData.value || !anjunganData.value.klinik) return [];

  const targetJenis = anjunganData.value.jenisPasien;
  const targetKodes = anjunganData.value.klinik;

  return targetKodes
    .map(
      (kode) =>
        getAllClinics.value.find(
          (c) => c.kode === kode && c.jenisLayanan === targetJenis,
        ) || null,
    )
    .filter(Boolean);
});

// Watcher untuk anjunganData: Jika baru terisi setelah mount, pastikan prefetch berjalan
watch(
  anjunganData,
  async (newVal) => {
    if (newVal) {
      console.log("🎯 anjunganData changed/ready, performing pre-checks...");
      if (newVal.jenisPasien === "Reguler") {
        await clinicStore.fetchRegulerClinics();
      }
      await prefetchDoctorsForCurrentAnjungan();
    }
  },
  { immediate: true },
);

const showVisitTypeDialog = ref(false);
const showBookingFormDialog = ref(false);
const showDoctorSelectionDialog = ref(false);
const showPrintDialog = ref(false);
const showFastTrackDialog = ref(false);
const lastRegisteredPatient = ref(null);
const selectedClinic = ref(null);
const selectedDoctor = ref(null);
const snackbar = ref(false);
const snackbarText = ref("");
const snackbarColor = ref("success");

// Fast Track form data
const fastTrackForm = ref({
  penanggungJawab: "",
  alasanFastTrack: "",
  jenisPembayaran: "UMUM", // Default untuk non-Eksekutif
});

const bookingForm = ref({
  date: new Date().toISOString().substring(0, 10),
  shift: "Shift 1",
  payment: null,
  doctor: null,
});

// Cek apakah jenis pasien adalah Eksekutif
const isEksekutif = computed(() => {
  return anjunganData.value?.jenisPasien === "Eksekutif";
});

// tampilkan doctor info dengan prioritas API
const getDisplayDoctorInfo = (clinic) => {
  const idklinik = clinic.id;
  const apiDoctors = idklinik ? doctorsByKlinikId.value[idklinik] : null;
  const doctors =
    apiDoctors && apiDoctors.length > 0 ? apiDoctors : clinic.doctors || [];

  if (!doctors || doctors.length === 0) {
    return "Tidak ada dokter";
  }

  const maxDisplay = 1;

  if (doctors.length <= maxDisplay) {
    return doctors.join(", ");
  } else {
    const displayedDoctors = doctors.slice(0, maxDisplay).join(", ");
    const remainingCount = doctors.length - maxDisplay;
    return `${displayedDoctors}, dan ${remainingCount} dokter lainnya`;
  }
};

// Helper to get current day name in Indonesian
const getTodayName = () => {
  const days = [
    "Minggu",
    "Senin",
    "Selasa",
    "Rabu",
    "Kamis",
    "Jum'at",
    "Sabtu",
  ];
  return days[new Date().getDay()];
};

// Helper to get current hour
const getCurrentHour = () => {
  return new Date().getHours();
};

// Get current shift based on time and day
const getCurrentShift = (clinic) => {
  if (!clinic || !clinic.jamShiftPerHari) return null;

  const today = getTodayName();
  const shiftsToday = clinic.jamShiftPerHari[today];

  if (!shiftsToday || shiftsToday.length === 0) return null;

  const currentHour = getCurrentHour();
  const currentMinutes = new Date().getMinutes();
  const currentTime = currentHour * 60 + currentMinutes;

  // Find active shift
  for (const shift of shiftsToday) {
    const [startH, startM] = shift.dari.split(":").map(Number);
    const [endH, endM] = shift.sampai.split(":").map(Number);
    const startTime = startH * 60 + startM;
    const endTime = endH * 60 + endM;

    if (currentTime >= startTime && currentTime < endTime) {
      return shift;
    }
  }

  // If no active shift, return first shift
  return shiftsToday[0];
};

const isShift1Full = (clinic) => {
  if (!clinic || !clinic.jamShiftPerHari) return true;

  const today = getTodayName();
  const shiftsToday = clinic.jamShiftPerHari[today];

  if (!shiftsToday || shiftsToday.length === 0) return true;

  // Check first shift
  const firstShift = shiftsToday[0];
  return firstShift ? firstShift.kuota === 0 : true;
};

const getCurrentShiftNumber = () => {
  if (!selectedClinic.value) return 1;

  const today = getTodayName();
  const shiftsToday = selectedClinic.value.jamShiftPerHari?.[today];

  if (!shiftsToday || shiftsToday.length === 0) return 1;

  const currentShift = getCurrentShift(selectedClinic.value);
  if (!currentShift) return 1;

  return shiftsToday.indexOf(currentShift) + 1;
};

const getCurrentShiftQuota = () => {
  if (!selectedClinic.value || !selectedClinic.value.jamShiftPerHari) return 0;

  const today = getTodayName();
  const shiftsToday = selectedClinic.value.jamShiftPerHari[today];

  if (!shiftsToday || shiftsToday.length === 0) return 0;

  const currentShift = getCurrentShift(selectedClinic.value);
  return currentShift ? currentShift.kuota : 0;
};

const getAvailableShiftsForBooking = () => {
  if (!selectedClinic.value || !selectedClinic.value.jamShiftPerHari) return [];

  const selectedDate = bookingForm.value.date;
  const today = new Date().toISOString().substring(0, 10);
  const isToday = selectedDate === today;

  // Get day name from selected date
  const date = new Date(selectedDate);
  const days = [
    "Minggu",
    "Senin",
    "Selasa",
    "Rabu",
    "Kamis",
    "Jum'at",
    "Sabtu",
  ];
  const dayName = days[date.getDay()];

  const shiftsForDay = selectedClinic.value.jamShiftPerHari[dayName];

  if (!shiftsForDay || shiftsForDay.length === 0) {
    return [];
  }

  return shiftsForDay
    .map((shift, index) => {
      const shiftName = `Shift ${index + 1}`;
      const shiftTime = `${shift.dari} - ${shift.sampai}`;

      // If today, skip shift 1
      if (isToday && index === 0) {
        return null;
      }

      if (shift.kuota === 0) {
        return null;
      }

      return {
        label: `${shiftName} (${shiftTime}) - Kuota: ${shift.kuota} pasien`,
        value: shiftName,
      };
    })
    .filter(Boolean);
};

const getMinDate = () => {
  return new Date().toISOString().substring(0, 10);
};

const getMaxDate = () => {
  const today = new Date();
  const maxDate = new Date(today);
  maxDate.setDate(today.getDate() + 14);
  return maxDate.toISOString().substring(0, 10);
};

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

const selectClinic = (clinic) => {
  if (!clinic || !clinic.available) return;

  selectedClinic.value = clinic;
  // Reset selected doctor ketika memilih klinik baru
  selectedDoctor.value = null;
  showVisitTypeDialog.value = true;
};

const selectVisitType = (type) => {
  // Validasi: untuk pasien Eksekutif, dokter harus dipilih
  if (isEksekutif.value && !selectedDoctor.value) {
    showSnackbar("Mohon pilih dokter terlebih dahulu", "error");
    return;
  }

  showVisitTypeDialog.value = false;

  if (type === "JADWAL_LAIN") {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const tomorrowStr = tomorrow.toISOString().substring(0, 10);

    bookingForm.value = {
      date: tomorrowStr,
      shift: "",
      payment: null,
      doctor: isEksekutif.value ? selectedDoctor.value : null,
    };
    showBookingFormDialog.value = true;
  }
};

const registerPatientDirectly = async (paymentType) => {
  // Validasi: untuk pasien Eksekutif, dokter harus dipilih
  if (isEksekutif.value && !selectedDoctor.value) {
    showSnackbar("Mohon pilih dokter terlebih dahulu", "error");
    return;
  }

  // Validasi kuota
  if (isShift1Full(selectedClinic.value)) {
    showSnackbar("Kuota hari ini sudah habis", "error");
    return;
  }

  showVisitTypeDialog.value = false;

  // Handle Fast Track - tampilkan dialog Fast Track sebelum registrasi
  const isFastTrack = paymentType === "FAST_TRACK";

  if (isFastTrack) {
    // Reset form Fast Track
    fastTrackForm.value = {
      penanggungJawab: "",
      alasanFastTrack: "",
      jenisPembayaran: "UMUM", // Default untuk non-Eksekutif
    };
    // Tampilkan dialog Fast Track
    showFastTrackDialog.value = true;
  } else {
    // Untuk pasien Eksekutif, dokter sudah dipilih di dialog sebelumnya
    // Untuk Reguler/BPJS, tidak perlu dokter
    const namaDokter = isEksekutif.value ? selectedDoctor.value : null;
    await registerPatient("SEKARANG", paymentType, namaDokter, false);
  }
};

// Fungsi ini tidak lagi digunakan karena dokter dipilih di dialog konfirmasi
// Tapi tetap dipertahankan untuk kompatibilitas jika ada referensi lain
const confirmDoctorSelection = () => {
  if (!selectedDoctor.value) {
    showSnackbar("Mohon pilih dokter terlebih dahulu", "error");
    return;
  }

  showDoctorSelectionDialog.value = false;

  // Register dengan dokter yang dipilih untuk kunjungan hari ini
  // Untuk eksekutif, paymentType adalah "Eksekutif"
  registerPatient("SEKARANG", "Eksekutif", selectedDoctor.value);
};

const registerPatient = async (
  visitType,
  paymentType,
  namaDokter,
  isFastTrack = false,
  fastTrackData = null,
) => {
  try {
    // Validasi bahwa fungsi registerPatientFromAnjungan ada
    if (!queueStore) {
      console.error("❌ queueStore is not initialized");
      showSnackbar(
        "Store tidak ter-initialize. Silakan refresh halaman.",
        "error",
      );
      return;
    }

    if (typeof queueStore.registerPatientFromAnjungan !== "function") {
      console.error(
        "❌ queueStore.registerPatientFromAnjungan is not a function",
      );
      console.error("queueStore:", queueStore);
      console.error("Available methods:", Object.keys(queueStore || {}));
      showSnackbar(
        "Fungsi registrasi tidak tersedia. Silakan refresh halaman.",
        "error",
      );
      return;
    }

    // Register patient to queueStore
    let result;
    if (!isEksekutif.value) {
      // Create patient via API for REGULER
      result = await queueStore.registerRegulerPatientViaApi(
        selectedClinic.value,
        paymentType,
        visitType,
        isFastTrack,
        fastTrackData,
      );
    } else {
      // Existing logic for Eksekutif
      result = queueStore.registerPatientFromAnjungan(
        selectedClinic.value,
        paymentType,
        visitType,
        null,
        "Shift 1",
        namaDokter,
        isFastTrack,
        fastTrackData, // Pass fastTrackData (penanggungJawab, alasanFastTrack)
        null, // Stop passing anjunganId as targetLoketId (fix routing bug)
        null, // Stop passing anjunganName as targetLoket name
      );
    }

    if (result && result.success && result.patient) {
      const doctorInfo = namaDokter ? ` dengan dokter ${namaDokter}` : "";
      const fastTrackInfo = isFastTrack ? " (Fast Track)" : "";
      const message = `Pendaftaran ${selectedClinic.value.name} untuk kunjungan HARI INI dengan pembayaran ${paymentType}${fastTrackInfo}${doctorInfo} berhasil diproses. Nomor antrean: ${result.patient.noAntrian?.split(" |")[0] || result.patient.noAntrian || "N/A"}`;
      showSnackbar(message, "success");

      // Simpan data pasien untuk print
      lastRegisteredPatient.value = result.patient;
      console.log(
        "📋 Patient data saved for print:",
        lastRegisteredPatient.value,
      );

      // Tampilkan dialog print - gunakan nextTick untuk memastikan reactive update
      await nextTick();
      showPrintDialog.value = true;
      console.log(
        "✅ Print dialog opened, showPrintDialog:",
        showPrintDialog.value,
        "patient:",
        lastRegisteredPatient.value,
      );
    } else {
      console.error("❌ Registration failed or patient data missing:", result);
      showSnackbar(result?.message || "Gagal melakukan pendaftaran", "error");
    }
  } catch (error) {
    console.error("❌ Error in registerPatient:", error);
    showSnackbar(
      "Terjadi kesalahan saat melakukan pendaftaran. Silakan coba lagi.",
      "error",
    );
  } finally {
    selectedClinic.value = null;
    selectedDoctor.value = null;
  }
};

const submitBooking = async () => {
  if (
    !bookingForm.value.date ||
    !bookingForm.value.shift ||
    !bookingForm.value.payment
  ) {
    showSnackbar("Mohon lengkapi semua field.", "error");
    return;
  }

  // Validasi dokter untuk pasien Eksekutif
  if (isEksekutif.value && !bookingForm.value.doctor) {
    showSnackbar("Mohon pilih dokter terlebih dahulu.", "error");
    return;
  }

  showBookingFormDialog.value = false;

  try {
    // Register patient to queueStore for future visit
    const paymentType = bookingForm.value.payment === "BPJS" ? "BPJS" : "UMUM";
    const namaDokter = isEksekutif.value ? bookingForm.value.doctor : null;

    // Validasi bahwa fungsi registerPatientFromAnjungan ada
    if (!queueStore) {
      console.error("❌ queueStore is not initialized");
      showSnackbar(
        "Store tidak ter-initialize. Silakan refresh halaman.",
        "error",
      );
      return;
    }

    if (typeof queueStore.registerPatientFromAnjungan !== "function") {
      console.error(
        "❌ queueStore.registerPatientFromAnjungan is not a function",
      );
      console.error("queueStore:", queueStore);
      console.error("Available methods:", Object.keys(queueStore || {}));
      showSnackbar(
        "Fungsi registrasi tidak tersedia. Silakan refresh halaman.",
        "error",
      );
      return;
    }

    let result;
    if (!isEksekutif.value) {
      // Create patient via API for REGULER
      // NOTE: API might not support date, so it will generate for today
      result = await queueStore.registerRegulerPatientViaApi(
        selectedClinic.value,
        paymentType,
        "JADWAL_LAIN",
        false, // isFastTrack
        null, // fastTrackData
      );
    } else {
      result = queueStore.registerPatientFromAnjungan(
        selectedClinic.value,
        paymentType,
        "JADWAL_LAIN",
        bookingForm.value.date,
        bookingForm.value.shift,
        namaDokter,
        false, // isFastTrack
        null, // fastTrackData
        null, // Stop passing anjunganId as targetLoketId (fix routing bug)
        null, // Stop passing anjunganName as targetLoket name
      );
    }

    if (result && result.success && result.patient) {
      const doctorInfo = namaDokter ? ` dengan dokter ${namaDokter}` : "";
      const message = `Jadwal kunjungan ${selectedClinic.value.name} pada ${bookingForm.value.date} - ${bookingForm.value.shift} (${paymentType})${doctorInfo} berhasil disimpan. Nomor antrean: ${result.patient.noAntrian?.split(" |")[0] || result.patient.noAntrian || "N/A"}`;
      showSnackbar(message, "success");

      // Simpan data pasien untuk print
      lastRegisteredPatient.value = result.patient;
      console.log(
        "📋 Patient data saved for print (booking):",
        lastRegisteredPatient.value,
      );

      // Tampilkan dialog print - gunakan nextTick untuk memastikan reactive update
      await nextTick();
      showPrintDialog.value = true;
      console.log(
        "✅ Print dialog opened (booking), showPrintDialog:",
        showPrintDialog.value,
        "patient:",
        lastRegisteredPatient.value,
      );
    } else {
      console.error("❌ Booking failed or patient data missing:", result);
      showSnackbar(result?.message || "Gagal menyimpan jadwal", "error");
    }
  } catch (error) {
    console.error("❌ Error in submitBooking:", error);
    showSnackbar(
      "Terjadi kesalahan saat menyimpan jadwal. Silakan coba lagi.",
      "error",
    );
  } finally {
    selectedClinic.value = null;
    selectedDoctor.value = null;
    bookingForm.value.doctor = null;
  }
};

const handlePrintTicket = async () => {
  if (!lastRegisteredPatient.value) return;

  try {
    await printTicketFromPatient(lastRegisteredPatient.value);
    showSnackbar("Tiket berhasil dicetak", "success");
    showPrintDialog.value = false;
    lastRegisteredPatient.value = null;
  } catch (error) {
    console.error("Error printing ticket:", error);
    showSnackbar("Gagal mencetak tiket. Silakan coba lagi.", "error");
  }
};

const skipPrint = () => {
  showPrintDialog.value = false;
  lastRegisteredPatient.value = null;
};

// Handle Fast Track dialog submission
const submitFastTrackForm = async () => {
  // Validasi form
  if (!fastTrackForm.value.penanggungJawab.trim()) {
    showSnackbar("Mohon isi Penanggung Jawab", "error");
    return;
  }

  if (!fastTrackForm.value.alasanFastTrack.trim()) {
    showSnackbar("Mohon isi Alasan Fast Track", "error");
    return;
  }

  // Untuk non-Eksekutif, validasi jenis pembayaran
  if (!isEksekutif.value && !fastTrackForm.value.jenisPembayaran) {
    showSnackbar("Mohon pilih Jenis Pembayaran", "error");
    return;
  }

  // Tutup dialog Fast Track
  showFastTrackDialog.value = false;

  // Untuk pasien Eksekutif, dokter sudah dipilih di dialog sebelumnya
  // Untuk Reguler/BPJS, tidak perlu dokter
  const namaDokter = isEksekutif.value ? selectedDoctor.value : null;

  // Tentukan paymentType berdasarkan jenis pasien
  const paymentType = isEksekutif.value
    ? "Eksekutif"
    : fastTrackForm.value.jenisPembayaran;

  // Siapkan data Fast Track
  const fastTrackData = {
    penanggungJawab: fastTrackForm.value.penanggungJawab.trim(),
    alasanFastTrack: fastTrackForm.value.alasanFastTrack.trim(),
  };

  // Register dengan Fast Track
  await registerPatient(
    "SEKARANG",
    paymentType,
    namaDokter,
    true,
    fastTrackData,
  );
};

const backToList = () => {
  navigateTo("/anjungan/anjungan");
};

// Watch showPrintDialog untuk debugging
watch(showPrintDialog, (newVal) => {
  console.log("🔔 showPrintDialog changed:", newVal);
  if (newVal) {
    console.log("📋 lastRegisteredPatient:", lastRegisteredPatient.value);
  }
});

// Watch lastRegisteredPatient untuk debugging
watch(
  lastRegisteredPatient,
  (newVal) => {
    console.log("🔔 lastRegisteredPatient changed:", newVal);
  },
  { deep: true },
);
</script>

<style scoped lang="scss">
.page-header {
  background: linear-gradient(
    135deg,
    var(--color-primary-600) 0%,
    var(--color-primary-700) 100%
  );
  border-radius: 0 !important;
  padding: 16px 28px;
  margin-bottom: 0;
  display: flex;
  align-items: center;
  gap: 16px;
  height: 80px;
  box-shadow: 0 4px 16px rgba(33, 150, 243, 0.2);
}

.anjungan-container {
  background: var(--color-neutral-300);
  min-height: calc(100vh - 80px);
  padding: 16px;
  overflow-y: auto;
}

.header-content {
  flex: 1;
  color: var(--color-neutral-100);
}

.header-icon {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  padding: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 54px;
  height: 54px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-logo {
  width: 40px;
  height: 40px;
  object-fit: contain;
}

.page-title {
  font-size: 32px;
  font-weight: 600;
  margin: 0;
  color: var(--color-neutral-100);
  line-height: 40px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-subtitle {
  font-size: 15px;
  font-weight: 400;
  margin: 2px 0 0 0;
  color: var(--color-neutral-100);
  opacity: 0.9;
  line-height: 22px;
}

.clinic-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
  width: 100%;
}

/* CLINIC CARD - Improved Hierarchy */
.clinic-card {
  cursor: pointer;
  border-radius: 12px !important;
  height: 180px;
  background: var(--color-neutral-100);
  border: 3px solid var(--color-neutral-500);
  position: relative;
  overflow: hidden;
}

.clinic-available {
  border-color: var(--color-primary-600);
  background: var(--color-neutral-200);
}

.clinic-closed {
  opacity: 0.65;
  cursor: not-allowed;
  border-color: var(--color-danger-600);
  background: var(--color-danger-100);
}

.clinic-content {
  padding: 18px !important;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: relative;
  gap: 8px;
}

.clinic-name {
  font-size: 22px;
  font-weight: 700;
  color: var(--color-neutral-900);
  margin: 0;
  line-height: 1.2;
  padding-right: 10px;
}

.clinic-closed .clinic-name {
  color: var(--color-neutral-700);
}

.doctor-info {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  font-size: 12px;
  color: var(--color-primary-700);
  font-weight: 600;
  line-height: 1.4;
  padding-right: 70px;
  flex: 1;
}

.clinic-closed .doctor-info {
  color: var(--color-neutral-600);
}

.schedule-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--color-neutral-700);
  font-weight: 500;
  position: absolute;
  bottom: 18px;
  left: 18px;
}

.clinic-closed .schedule-info {
  color: var(--color-neutral-600);
}

.clinic-icon-wrapper {
  position: absolute;
  bottom: 14px;
  right: 14px;
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  border: 2px solid var(--color-neutral-400);
}

.clinic-closed .clinic-icon-wrapper {
  opacity: 0.5;
}

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

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-neutral-700);
  margin: 16px 0 8px 0;
}

.empty-subtitle {
  font-size: 14px;
  color: var(--color-neutral-600);
  margin: 0;
}

.not-found {
  min-height: 80vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: var(--color-neutral-700);
}

/* Dialog Styles */
.dialog-card {
  border-radius: 16px !important;
}

.dialog-header {
  background: var(--color-primary-600);
  color: var(--color-neutral-100);
  padding: 20px 24px;
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
  position: relative;
}

.dialog-close-btn {
  position: absolute !important;
  top: 12px;
  right: 12px;
  background-color: rgba(255, 255, 255, 0.2) !important;
  z-index: 10;

  &:hover {
    background-color: rgba(255, 255, 255, 0.3) !important;
  }
}

.dialog-header-simple {
  padding: 20px 24px;
  font-size: 18px;
  font-weight: 700;
  color: var(--color-neutral-900);
}

.dialog-content {
  text-align: center;
}

.dialog-icon {
  display: flex;
  justify-content: center;
}

.dialog-clinic-name {
  font-size: 22px;
  font-weight: 700;
  color: var(--color-neutral-900);
  margin: 8px 0;
}

.dialog-subtitle {
  font-size: 14px;
  color: var(--color-neutral-700);
  margin: 0;
}

.dialog-info {
  text-align: left;
  font-size: 14px;

  p {
    margin: 8px 0;
    color: var(--color-neutral-800);
  }

  strong {
    color: var(--color-neutral-900);
  }
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--color-neutral-200);

  &:last-child {
    border-bottom: none;
  }
}

.info-label {
  font-weight: 600;
  color: var(--color-neutral-700);
  flex: 0 0 40%;
}

.info-value {
  color: var(--color-neutral-900);
  flex: 1;
  text-align: right;
  word-break: break-word;
}

.doctor-list-section {
  margin-bottom: 16px;

  p {
    margin-bottom: 12px;
    font-size: 15px;
    color: var(--color-neutral-800);
  }
}

.doctor-info-unified {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  background-color: var(--color-neutral-100);
  border: 1px solid var(--color-neutral-300);
  border-radius: 8px;
  overflow-y: auto;
  margin-bottom: 20px;
  max-height: 420px;
}

.doctor-info-unit {
  display: flex;
  align-items: flex-start;
  padding: 12px 14px;
  border-bottom: 1px solid var(--color-neutral-200);
  border-right: 1px solid var(--color-neutral-200);
}

.doctor-info-name-unified {
  font-size: 13px;
  line-height: 1.4;
  color: var(--color-neutral-800);
  white-space: normal;
  word-wrap: break-word;
  flex: 1;
}

/* Responsive & Separator Logic */
.doctor-info-unit:nth-child(2n) {
  border-right: none;
}

@media (max-width: 480px) {
  .doctor-info-unified {
    grid-template-columns: 1fr;
  }
  .doctor-info-unit {
    border-right: none;
  }
  .doctor-info-unit:nth-child(2n) {
    border-right: none;
  }
}

.doctor-selection-section {
  margin-bottom: 16px;

  p {
    margin-bottom: 12px;
    font-size: 15px;
    color: var(--color-neutral-800);
  }
}

.doctor-buttons-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 8px;
  max-height: 540px;
  overflow-y: auto;
  padding-right: 4px;
  align-content: start;
}

.doctor-button-wrapper {
  width: 100%;
}

.doctor-button {
  justify-content: center !important;
  text-transform: none !important;
  text-align: center !important;
  padding: 16px 10px !important;
  border: 2px solid var(--color-neutral-500) !important;
  background-color: var(--color-neutral-100) !important;
  color: var(--color-neutral-800) !important;
  font-weight: 500 !important;
  font-size: 13px !important;
  line-height: 1.3 !important;
  border-radius: 8px !important;
  transition: all 0.2s ease !important;
  min-height: 90px !important;
  height: auto !important;
  flex-direction: column !important;
  touch-action: manipulation !important;
  -webkit-tap-highlight-color: transparent !important;

  .v-btn__content {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 0 !important;
  }

  &:hover {
    background-color: var(--color-primary-100) !important;
    border-color: var(--color-primary-600) !important;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  &:active {
    transform: translateY(0);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }
}

.doctor-button-selected {
  background-color: var(--color-success-200) !important;
  border-color: var(--color-success-600) !important;
  color: var(--color-success-800) !important;
  font-weight: 600 !important;
  box-shadow: 0 2px 8px rgba(0, 146, 98, 0.2) !important;

  &:hover {
    background-color: var(--color-success-300) !important;
    border-color: var(--color-success-700) !important;
    box-shadow: 0 3px 10px rgba(0, 146, 98, 0.3) !important;
  }
}

.doctor-icon {
  flex-shrink: 0;
}

.doctor-name {
  width: 100%;
  text-align: center;
  white-space: normal;
  word-wrap: break-word;
  line-height: 1.3;
}

/* Responsive untuk layar lebih kecil */
@media (max-width: 768px) {
  .doctor-buttons-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .doctor-button {
    padding: 14px 8px !important;
    font-size: 12px !important;
    min-height: 85px !important;
  }
}

@media (max-width: 480px) {
  .doctor-buttons-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 6px;
  }

  .doctor-button {
    padding: 12px 6px !important;
    font-size: 11px !important;
    min-height: 80px !important;
  }
}

.quota-section {
  margin-bottom: 16px;

  p {
    margin-bottom: 12px;
    font-size: 15px;
  }
}

.current-quota-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: linear-gradient(
    135deg,
    var(--color-neutral-100) 0%,
    var(--color-neutral-200) 100%
  );
  border-radius: 12px;
  border: 2px solid var(--color-primary-400);
  margin-bottom: 12px;

  &.quota-empty {
    background: linear-gradient(
      135deg,
      var(--color-neutral-200) 0%,
      var(--color-neutral-300) 100%
    );
    border-color: var(--color-neutral-500);

    .quota-large-number {
      color: var(--color-neutral-600);
    }

    .quota-label {
      color: var(--color-neutral-700);
    }
  }
}

.quota-large-number {
  font-size: 48px;
  font-weight: 700;
  color: var(--color-success-700);
  line-height: 1;
  margin-bottom: 4px;
}

.quota-label {
  font-size: 14px;
  font-weight: 600;
  color: var(--color-success-800);
}

.disabled-hint {
  font-size: 11px;
  color: var(--color-danger-600);
  text-align: center;
  margin: 4px 0 0 0;
  font-weight: 600;
}

.btn-disabled {
  opacity: 0.5 !important;
  background-color: var(--color-neutral-500) !important;
}

.payment-btn {
  font-weight: 700;
  height: 64px;
  font-size: 16px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

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

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

  .header-right {
    width: 100%;
  }

  .info-guide {
    width: 100%;
  }

  .guide-item {
    font-size: 12px;
    justify-content: center;
  }

  .guide-number {
    width: 22px;
    height: 22px;
    font-size: 12px;
  }

  .page-title {
    font-size: 36px;
    letter-spacing: 1.5px;
  }

  .page-subtitle {
    font-size: 18px;
  }

  .header-icon {
    width: 36px;
    height: 36px;
  }

  .header-logo {
    width: 24px;
    height: 24px;
  }

  .clinic-card {
    height: 170px;
  }

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

@media (max-width: 768px) {
  .anjungan-container {
    padding: 12px;
  }

  .header-content {
    padding: 16px;
  }

  .page-title {
    font-size: 28px;
    letter-spacing: 1px;
  }

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

  .header-icon {
    width: 32px;
    height: 32px;
  }

  .header-logo {
    width: 20px;
    height: 20px;
  }

  .clinic-card {
    height: 165px;
  }

  .clinic-name {
    font-size: 19px;
  }

  .clinic-icon-wrapper {
    width: 50px;
    height: 50px;
  }

  .clinic-icon-wrapper .v-icon {
    font-size: 24px !important;
  }

  .doctor-info,
  .schedule-info {
    font-size: 11px;
  }

  .doctor-info {
    padding-right: 60px;
  }
}

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

.navigation-footer .v-btn {
  text-transform: none;
  font-weight: 600;
}

.print-ticket-btn {
  font-size: 20px !important;
  font-weight: 700 !important;
  letter-spacing: 0.5px !important;
  text-transform: uppercase !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
}

.finish-btn {
  font-size: 18px !important;
  font-weight: 600 !important;
  text-transform: none !important;
}

.print-ticket-btn:hover {
  transform: scale(1.05) translateY(-2px);
  box-shadow: 0 12px 24px rgba(25, 118, 210, 0.4) !important;
}

.print-ticket-btn:active {
  transform: scale(0.98);
}
</style>
