// stores/queueStore.js
import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { useClinicStore } from './clinicStore';
import { usePenunjangStore } from './penunjangStore';
import { useLoketStore } from './loketStore';

export const useQueueStore = defineStore('queue', () => {
  const clinicStore = useClinicStore();
  const penunjangStore = usePenunjangStore();
  const loketStore = useLoketStore();

  // ============================================
  // API INTEGRATION FOR LOKET PATIENTS
  // ============================================
  
  // State untuk API patient data per loket
  const apiPatientsPerLoket = ref({});
  const isLoadingPatients = ref(false);
  const apiPatientsError = ref(null);
  
  // Throttle mechanism: track last fetch time per loket
  const lastFetchTime = ref({});
  
  // Synchronization Guard: track last update time to break loops across tabs
  const lastUpdated = ref(Date.now());
  // synchronization guard (moved lower)

  /**
   * Sync patient status to apiPatientsPerLoket for reactivity
   */
  const syncApiPatientStatus = (patient, newStatus) => {
    if (!patient) return;
    
    // Allow syncing if strictly 'api' OR if we can find a matching ID in the API store
    // This handles cases where we have an 'onsite' patient locally that corresponds to an API patient
    
    const loketId = patient.loketId;
    if (loketId && apiPatientsPerLoket.value[loketId]) {
      // Try to find patient in the API list
      const index = apiPatientsPerLoket.value[loketId].findIndex(p => {
        if (patient.registrationType === 'api' && p.no === patient.no) return true;
        
        // Fallback matching for 'onsite' patients
        if (patient.idtiket && p.idtiket && String(patient.idtiket) === String(p.idtiket)) return true;
        if (patient.barcode && p.barcode && String(patient.barcode) === String(p.barcode)) return true;
        
        return false;
      });

      if (index !== -1) {
        const updated = [...apiPatientsPerLoket.value[loketId]];
        updated[index] = { ...updated[index], status: newStatus };
        apiPatientsPerLoket.value[loketId] = updated;
      }
    }
  };

  /**
   * Reference mapping for patient status from API idvisit
   * idvisit 1, 2 = menunggu (CT ANJUNGAN, RT ANJUNGAN)
   * idvisit 3, 4 = anjungan (PG ANJUNGAN, RT CHECK-IN)
   * idvisit 5, 6 = di-loket (PS CHECK-IN, TP LOKET)
   */
  const PATIENT_STATUS_MAP = {
    1: 'menunggu',
    2: 'menunggu',
    3: 'anjungan',
    4: 'anjungan',
    5: 'di-loket',
    6: 'di-loket',
    "1": 'menunggu',
    "2": 'menunggu',
    "3": 'anjungan',
    "4": 'anjungan',
    "5": 'di-loket',
    "6": 'di-loket'
  };

  /**
   * Map status from idvisit API
   */
  const mapStatusFromIdVisit = (idvisit) => {
    return PATIENT_STATUS_MAP[idvisit] || 'menunggu';
  };

  /**
   * Map status dari deskripsi API ke status internal
   * menunggu (id 1, 2): "Cetak Tiket Antrian" atau "Ruang Tunggu Anjungan"
   * anjungan (id 3, 4): "Panggilan loket ke Anjungan" atau "Tunggu Pasien Check-In"
   * di-loket (id 5, 6): "Pasien Sudah Check-In" atau "Tunggu Panggilan Loket"
   */
  const mapStatusFromDeskripsi = (deskripsi) => {
    if (!deskripsi) return 'menunggu';
    
    const desc = deskripsi.toString().trim().toUpperCase();
    
    // di-loket (id 5, 6): PS CHECK-IN (Pasien Sudah Check-In), RT PENDAFTARAN (Tunggu Panggilan Loket)
    if (desc.includes('PASIEN SUDAH CHECK-IN') || desc.includes('TUNGGU PANGGILAN LOKET') || desc.includes('PS CHECK-IN') || desc.includes('RT PENDAFTARAN')) {
      return 'di-loket';
    }
    
    // anjungan (id 3, 4): PG ANJUNGAN (Panggilan loket ke Anjungan), RT CHECK-IN (Tunggu Pasien Check-In)
    if (desc.includes('PANGGILAN LOKET KE ANJUNGAN') || desc.includes('TUNGGU PASIEN CHECK-IN') || desc.includes('PG ANJUNGAN') || desc.includes('RT CHECK-IN')) {
      return 'anjungan';
    }
    
    // menunggu (id 1, 2): CT ANJUNGAN (Cetak Tiket Antrian), RT ANJUNGAN (Ruang Tunggu Anjungan)
    if (desc.includes('CETAK TIKET') || desc.includes('RUANG TUNGGU ANJUNGAN') || desc.includes('CT ANJUNGAN') || desc.includes('RT ANJUNGAN')) {
      return 'menunggu';
    }
    
    // Default: menunggu
    return 'menunggu';
  };



  /**
   * Map patient data dari API format ke store format
   */
  const mapApiPatientToStoreFormat = (apiPatient, index) => {
    // Use idtiket as unique patient number to avoid conflicts with seed data
    // Seed data uses sequential numbers 1-20, so we use idtiket + 10000 offset
    const uniqueNo = apiPatient.idtiket ? parseInt(apiPatient.idtiket) + 10000 : 10000 + index;
    
    // Handle nested positions to find the best status
    let status = 'menunggu';
    let posisiStr = apiPatient.posisi || '';
    let idvisit = apiPatient.idvisit;
    
    if (apiPatient.posisi && Array.isArray(apiPatient.posisi) && apiPatient.posisi.length > 0) {
      // Find the "best" status among all positions
      // Priority: di-loket > anjungan > menunggu
      const statusPriority = { 'di-loket': 3, 'anjungan': 2, 'menunggu': 1 };
      let bestPriority = 0;
      
      apiPatient.posisi.forEach(pos => {
        const pStatus = pos.idvisit 
          ? mapStatusFromIdVisit(pos.idvisit) 
          : mapStatusFromDeskripsi(pos.deskripsi);
          
        const pPrio = statusPriority[pStatus] || 0;
        if (pPrio > bestPriority) {
          bestPriority = pPrio;
          status = pStatus;
          posisiStr = pos.posisi || pos.deskripsi || '';
          idvisit = pos.idvisit || idvisit;
        }
      });
    } else {
      // Standard top-level status
      status = apiPatient.idvisit 
        ? mapStatusFromIdVisit(apiPatient.idvisit) 
        : mapStatusFromDeskripsi(apiPatient.deskripsi);
    }

    const mapped = {
      no: uniqueNo,
      jamPanggil: apiPatient.waktu || '',
      barcode: apiPatient.barcode || '',
      noAntrian: `${apiPatient.ticket || ''} | ${posisiStr}`,
      shift: apiPatient.shift ? `Shift ${apiPatient.shift}` : '',
      klinik: apiPatient.klinik || '',
      kodeKlinik: apiPatient.klinik || '', // Will be mapped later
      fastTrack: "TIDAK", 
      pembayaran: apiPatient.pembayaran || '',
      status: status,
      processStage: 'loket',
      createdAt: apiPatient.tanggal || new Date().toISOString(),
      registrationType: 'api',
      visitType: 'SEKARANG',
      visitDate: apiPatient.tanggal ? apiPatient.tanggal.split('T')[0] : new Date().toISOString().substring(0, 10),
      namaDokter: null,
      noRM: null,
      penanggungJawab: null,
      alasanFastTrack: null,
      idvisit: idvisit,
      idtiket: apiPatient.idtiket,
      ticket: apiPatient.ticket,
      posisi: apiPatient.posisi,
      deskripsi: apiPatient.deskripsi,
    };

    // Map klinik name to code using clinicStore
    const clinic = clinicStore.clinics.find(c => 
      c.name && apiPatient.klinik && 
      c.name.toUpperCase().includes(apiPatient.klinik.toUpperCase())
    );
    if (clinic) {
      mapped.kodeKlinik = clinic.kode;
    }

    return mapped;
  };

  /**
   * Fetch patient data untuk loket tertentu dari API
   */
  const fetchPatientsForLoket = async (loketId) => {
    if (!loketId) {
      console.error('loketId required for fetchPatientsForLoket');
      return { success: false, message: 'ID Loket diperlukan' };
    }

    isLoadingPatients.value = true;
    apiPatientsError.value = null;

    // THROTTLE: Check if we recently fetched (within last 5 seconds)
    const now = Date.now();
    const lastFetch = lastFetchTime.value[loketId] || 0;
    const timeSinceLastFetch = now - lastFetch;
    
    if (timeSinceLastFetch < 5000 && apiPatientsPerLoket.value[loketId]) {
      console.log(`⏭️ [queueStore] Skipping fetch for loket ${loketId} (last fetched ${Math.round(timeSinceLastFetch/1000)}s ago)`);
      isLoadingPatients.value = false;
      return {
        success: true,
        message: 'Using cached data',
        data: apiPatientsPerLoket.value[loketId]
      };
    }
    
    // Update last fetch time
    lastFetchTime.value[loketId] = now;

    // Check for daily reset before fetching
    checkAndResetDaily();

    try {
      console.log(`🔄 [queueStore] Fetching patients for loket ${loketId}...`);
      const response = await fetch(`http://10.10.150.131:8089/api/v1/loket/${loketId}`);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const rawData = await response.json();
      
      // Check response structure
      if (rawData.metadata && rawData.metadata.code !== 200) {
        throw new Error(rawData.message || 'API returned error status');
      }

      const patientsRaw = rawData.data || [];
      
      // Map API data to store format
      const mappedPatients = patientsRaw.map((apiPatient, index) => 
        mapApiPatientToStoreFormat(apiPatient, index)
      ).filter(p => isTodayPatient(p));

      // Deduplicate patients by idtiket
      // API returns multiple entries if patient is at multiple positions
      const deduplicatedMap = new Map();
      mappedPatients.forEach(p => {
        const id = p.idtiket || p.barcode || p.no;
        const existing = deduplicatedMap.get(id);
        
        if (!existing) {
          deduplicatedMap.set(id, p);
        } else {
          // Priority: di-loket > anjungan > menunggu
          const statusPriority = { 'di-loket': 3, 'anjungan': 2, 'menunggu': 1 };
          const pPrio = statusPriority[p.status] || 0;
          const ePrio = statusPriority[existing.status] || 0;
          
          if (pPrio > ePrio) {
            deduplicatedMap.set(id, p);
          }
        }
      });
      const finalPatients = Array.from(deduplicatedMap.values());

      // Store in API-specific state
      apiPatientsPerLoket.value[loketId] = finalPatients;

      // IMPORTANT: Also merge into allPatients so callMultiplePatients can find them
      
      // Prepare list of new API patients with loketId assigned
      const patientsWithLoketId = finalPatients.map(p => ({
        ...p,
        loketId: parseInt(loketId),
        registrationType: 'api'
      }));

      // ROBUST DEDUPLICATION & STATUS MERGE
      // 1. Identify matches between existing allPatients and new API patients
      const newPatientMap = new Map();
      patientsWithLoketId.forEach(p => {
        const key = p.idtiket ? `id-${p.idtiket}` : `bc-${p.barcode}`;
        newPatientMap.set(key, p);
      });

      // 2. Iterate existing patients to find matches and preserve status
      const preservedStatuses = new Map();
      allPatients.value.forEach(p => {
        const key = p.idtiket ? `id-${p.idtiket}` : `bc-${p.barcode}`;
        if (newPatientMap.has(key)) {
           // If existing patient has more advanced status (anjungan/di-loket), preserve it!
           // This handles cases where we updated status locally ('onsite' or 'api') but API is lagging
           const statusPriority = { 'di-loket': 3, 'anjungan': 2, 'menunggu': 1 };
           const existingPrio = statusPriority[p.status] || 0;
           const newPatient = newPatientMap.get(key);
           const newPrio = statusPriority[newPatient.status] || 0;
           
           if (existingPrio > newPrio) {
             preservedStatuses.set(key, p.status);
             // Also preserve lastCalledAt/calledByAdmin if available
             if (p.lastCalledAt) newPatient.lastCalledAt = p.lastCalledAt;
             if (p.calledByAdmin) newPatient.calledByAdmin = p.calledByAdmin;
           }
        }
      });

      // 3. Update new patients with preserved status
      patientsWithLoketId.forEach(p => {
        const key = p.idtiket ? `id-${p.idtiket}` : `bc-${p.barcode}`;
        if (preservedStatuses.has(key)) {
          p.status = preservedStatuses.get(key);
        }
      });

      // 4. Remove existing patients that collide with new ones (to be replaced)
      // AND remove stale 'api' patients for this loket
      allPatients.value = allPatients.value.filter(p => {
        const key = p.idtiket ? `id-${p.idtiket}` : `bc-${p.barcode}`;
        
        // Remove if it's being replaced by new batch
        if (newPatientMap.has(key)) return false;
        
        // Remove if it's a stale 'api' patient for this loket (that wasn't in the new batch)
        if (p.registrationType === 'api' && String(p.loketId) === String(loketId)) return false;
        
        return true;
      });
      
      // 5. Add merged patients
      allPatients.value.push(...patientsWithLoketId);

      console.log(`✅ [queueStore] Successfully fetched ${finalPatients.length} unique patients for loket ${loketId} (Original: ${mappedPatients.length})`);
      console.log(`📊 [queueStore] Total patients in allPatients: ${allPatients.value.length}`);

      return {
        success: true,
        message: `${mappedPatients.length} pasien berhasil dimuat`,
        data: mappedPatients
      };

    } catch (error) {
      console.error(`❌ [queueStore] Error fetching patients for loket ${loketId}:`, error);
      apiPatientsError.value = error.message;

      // Return empty array on error
      apiPatientsPerLoket.value[loketId] = [];

      return {
        success: false,
        message: `Gagal memuat data pasien: ${error.message}`,
        data: []
      };
    } finally {
      isLoadingPatients.value = false;
    }
  };

  /**
   * Get patients for a specific loket (from API or seed data based on loket type)
   */
  const getPatientsForLoket = (loketId) => {
    return computed(() => {
      const loket = loketStore.getLoketById(parseInt(loketId));
      
      // If loket is EKSEKUTIF, use seed data
      const isEksekutif = loket?.tipeloket === 'EKSEKUTIF' || 
                          loket?.tipeLoket === 'EKSEKUTIF' ||
                          (loket?.namaLoket || '').toUpperCase().includes('EKSEKUTIF');
      
      if (isEksekutif) {
        // Return EKSEKUTIF patients from seed data
        return allPatients.value.filter(p => {
          const isPembayaranEksekutif = (p.pembayaran || '').toUpperCase().includes('EKSEKUTIF') || 
                                        (p.pembayaran || '').toUpperCase().includes('VIP');
          return isPembayaranEksekutif && p.processStage === 'loket';
        });
      }
      
      // For REGULER loket, return API data
      return apiPatientsPerLoket.value[loketId] || [];
    });
  };


  // Helper function untuk mendapatkan loket default (Loket A)
  const getDefaultLoket = () => {
    const allLokets = loketStore.loketData?.value || loketStore.loketData || [];
    const loket1 = allLokets.find(l => l.id === 1 || l.no === 1);
    return loket1 ? loket1.namaLoket : 'Loket A';
  };

  // Helper function untuk increment barcode counter setelah barcode digunakan
  const incrementBarcodeCounter = () => {
    if (typeof window === 'undefined' || typeof localStorage === 'undefined') return;
    
    const now = new Date();
    const year = String(now.getFullYear()).slice(-2);
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const datePrefix = `${year}${month}${day}`;
    const STORAGE_KEY = `barcode_counter_${datePrefix}`;
    const LAST_DATE_KEY = 'barcode_last_date';
    
    const storedCounter = localStorage.getItem(STORAGE_KEY);
    if (storedCounter) {
      const currentCounter = parseInt(storedCounter, 10) || 1;
      localStorage.setItem(STORAGE_KEY, String(currentCounter + 1));
      localStorage.setItem(LAST_DATE_KEY, datePrefix);
    }
  };

  // Helper function untuk generate barcode dengan format: YYMMDD + 5 digit sequential
  // Format: YY (tahun 2 digit terakhir) + MM (bulan 2 digit) + DD (tanggal 2 digit) + XXXXX (5 digit sequential)
  // Contoh: 26011400001, 26011400002, dst
  // Counter akan reset setiap ganti tanggal (mulai dari 00001 lagi)
  // IMPORTANT: Memastikan barcode selalu UNIQUE dan sequential per tanggal
  // NOTE: allPatientsRef adalah optional parameter untuk menghindari TDZ error saat seed initialization
  const generateBarcode = (existingBarcodes = [], allPatientsRef = null) => {
    const now = new Date();
    const year = String(now.getFullYear()).slice(-2); // 2 digit tahun terakhir
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 2 digit bulan
    const day = String(now.getDate()).padStart(2, '0'); // 2 digit tanggal
    const datePrefix = `${year}${month}${day}`; // YYMMDD
    
    // Check if localStorage is available (browser environment)
    if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
      // Key untuk localStorage berdasarkan tanggal
      const STORAGE_KEY = `barcode_counter_${datePrefix}`;
      const LAST_DATE_KEY = 'barcode_last_date';
      
      // Cek apakah tanggal sudah berubah (reset counter)
      const lastDate = localStorage.getItem(LAST_DATE_KEY);
      const currentDate = datePrefix;
      
      let counter = 1; // Default mulai dari 1
      
      if (lastDate === currentDate) {
        // Tanggal sama, lanjutkan counter dari localStorage
        const storedCounter = localStorage.getItem(STORAGE_KEY);
        if (storedCounter) {
          counter = parseInt(storedCounter, 10) || 1;
        }
      } else {
        // Tanggal berbeda, reset counter ke 1
        counter = 1;
        // Hapus counter lama untuk tanggal sebelumnya (cleanup)
        if (lastDate) {
          localStorage.removeItem(`barcode_counter_${lastDate}`);
        }
      }
      
      // Generate barcode dengan counter saat ini
      let barcode = `${datePrefix}${String(counter).padStart(5, '0')}`;
      
      // Cek apakah barcode sudah ada di existingBarcodes atau allPatientsRef
      const checkExists = (b) => {
        if (existingBarcodes.includes(b)) return true;
        // Hanya cek allPatientsRef jika diberikan (tidak null/undefined)
        if (allPatientsRef && allPatientsRef.value && allPatientsRef.value.some(p => p.barcode === b)) return true;
        return false;
      };
      
      let attempts = 0;
      const maxAttempts = 1000; // Maksimal 1000 pasien per hari
      
      // Cek uniqueness dan increment jika duplikat
      while (checkExists(barcode) && attempts < maxAttempts) {
        counter++;
        barcode = `${datePrefix}${String(counter).padStart(5, '0')}`;
        attempts++;
      }
      
      // IMPORTANT: JANGAN tulis counter ke localStorage di sini!
      // Counter hanya di-increment dan di-save setelah barcode benar-benar digunakan
      // Ini mencegah counter naik meskipun barcode tidak digunakan (misalnya saat refresh)
      // Counter akan di-increment oleh incrementBarcodeCounter() setelah pasien dibuat
      // Hanya update LAST_DATE_KEY untuk tracking tanggal
      localStorage.setItem(LAST_DATE_KEY, currentDate);
      
      return barcode;
    } else {
      // Fallback untuk SSR atau environment tanpa localStorage
      // Gunakan counter berdasarkan existing barcodes atau allPatientsRef
      const existingCount = existingBarcodes.filter(b => b && b.startsWith(datePrefix)).length;
      const allCount = allPatientsRef && allPatientsRef.value 
        ? allPatientsRef.value.filter(p => p.barcode && p.barcode.startsWith(datePrefix)).length 
        : 0;
      const counter = Math.max(existingCount, allCount) + 1;
      const counterCode = String(counter).padStart(5, '0');
      return `${datePrefix}${counterCode}`;
    }
  };
  // Seed data for easy reset during dev
  // IMPORTANT: Setiap pasien HARUS memiliki barcode UNIK untuk menghindari konflik
  // Format barcode menggunakan generateBarcode() untuk konsistensi dengan format baru
  // Generate barcode dengan memastikan uniqueness menggunakan existingBarcodes array
  // NOTE: Seed data menggunakan barcode statis untuk menghindari increment counter saat refresh
  // Counter hanya di-increment ketika pasien baru benar-benar dibuat dari Anjungan
  
  // Gunakan barcode statis untuk seed data (tidak memanggil generateBarcode)
  // Format: YYMMDD + 5 digit sequential dimulai dari 00001
  // Ini mencegah counter naik setiap kali halaman di-refresh
  const getSeedBarcode = (index) => {
    if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
      const now = new Date();
      const year = String(now.getFullYear()).slice(-2);
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const datePrefix = `${year}${month}${day}`;
      
      // Gunakan barcode statis berdasarkan index (1-16)
      // Format: YYMMDD + 5 digit (contoh: 26011500001, 26011500002, dst)
      return `${datePrefix}${String(index).padStart(5, '0')}`;
    }
    // Fallback untuk SSR
    const now = new Date();
    const year = String(now.getFullYear()).slice(-2);
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const datePrefix = `${year}${month}${day}`;
    return `${datePrefix}${String(index).padStart(5, '0')}`;
  };
  
  const seedBarcode1 = getSeedBarcode(1);
  const seedBarcode2 = getSeedBarcode(2);
  const seedBarcode3 = getSeedBarcode(3);
  const seedBarcode4 = getSeedBarcode(4);
  const seedBarcode5 = getSeedBarcode(5);
  // Barcode untuk pasien Eksekutif only (REGULER akan dari API)
  const seedBarcodeE1 = getSeedBarcode(1);
  const seedBarcodeE2 = getSeedBarcode(2);
  const seedBarcodeE3 = getSeedBarcode(3);
  const seedBarcodeE4 = getSeedBarcode(4);
  
  // IMPORTANT: Set counter ke nilai yang sesuai dengan jumlah seed data
  // Ini mencegah counter naik tidak terkendali saat seed data di-generate
  // Counter akan di-set ke jumlah seed data (16) + 1 untuk next barcode
  // Hanya set jika counter belum ada atau lebih kecil dari jumlah seed data
  if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
    const now = new Date();
    const year = String(now.getFullYear()).slice(-2);
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const datePrefix = `${year}${month}${day}`;
    const STORAGE_KEY = `barcode_counter_${datePrefix}`;
    const LAST_DATE_KEY = 'barcode_last_date';
    const storedCounter = localStorage.getItem(STORAGE_KEY);
    const seedDataCount = 4; // Jumlah seed data (EKSEKUTIF only)
    
    // Hanya set counter jika belum ada atau lebih kecil dari jumlah seed data
    // Jangan overwrite counter yang sudah lebih besar (berarti sudah ada pasien baru)
    if (!storedCounter || parseInt(storedCounter, 10) < seedDataCount) {
      localStorage.setItem(STORAGE_KEY, String(seedDataCount + 1));
      localStorage.setItem(LAST_DATE_KEY, datePrefix);
    }
  }
  
  
  // SEED DATA: ONLY EKSEKUTIF PATIENTS
  // All REGULER patients will come from API
  const seedPatients = [
    // {
    //   no: 1,
    //   jamPanggil: "11:20",
    //   barcode: seedBarcodeE1,
    //   noAntrian: `EA001 | Online - ${seedBarcodeE1}`,
    //   shift: "Shift 1",
    //   klinik: "KANDUNGAN",
    //   kodeKlinik: "KD",
    //   fastTrack: "TIDAK",
    //   pembayaran: "Eksekutif",
    //   status: "anjungan",
    //   processStage: "loket",
    //   createdAt: new Date().toISOString(),
    //   registrationType: 'online',
    //   visitType: 'SEKARANG',
    //   visitDate: new Date().toISOString().substring(0, 10),
    //   namaDokter: "Dr. Ahmad Wijaya, Sp.OG",
    //   noRM: "RM-E001",
    //   penanggungJawab: null,
    //   alasanFastTrack: null,
    // },
    // {
    //   no: 2,
    //   jamPanggil: "13:45",
    //   barcode: seedBarcodeE2,
    //   noAntrian: `EA002 | Online - ${seedBarcodeE2}`,
    //   shift: "Shift 1",
    //   klinik: "IPD",
    //   kodeKlinik: "IP",
    //   fastTrack: "TIDAK",
    //   pembayaran: "Eksekutif",
    //   status: "anjungan",
    //   processStage: "loket",
    //   createdAt: new Date().toISOString(),
    //   registrationType: 'online',
    //   visitType: 'SEKARANG',
    //   visitDate: new Date().toISOString().substring(0, 10),
    //   namaDokter: "Dr. Budi Santoso, Sp.PD",
    //   noRM: "RM-E002",
    //   penanggungJawab: null,
    //   alasanFastTrack: null,
    // },
    // {
    //   no: 3,
    //   jamPanggil: "15:10",
    //   barcode: seedBarcodeE3,
    //   noAntrian: `F-EA003 | Online - ${seedBarcodeE3}`,
    //   shift: "Shift 2",
    //   klinik: "SARAF",
    //   kodeKlinik: "SR",
    //   fastTrack: "YA",
    //   pembayaran: "Eksekutif",
    //   status: "anjungan",
    //   processStage: "loket",
    //   createdAt: new Date().toISOString(),
    //   registrationType: 'online',
    //   visitType: 'SEKARANG',
    //   visitDate: new Date().toISOString().substring(0, 10),
    //   namaDokter: "Dr. Citra Dewi, Sp.S",
    //   noRM: "RM-E003",
    //   penanggungJawab: "Dr. Citra Dewi",
    //   alasanFastTrack: "Pasien Eksekutif prioritas",
    // },
    // {
    //   no: 4,
    //   jamPanggil: "16:30",
    //   barcode: seedBarcodeE4,
    //   noAntrian: `EA004 | Online - ${seedBarcodeE4}`,
    //   shift: "Shift 2",
    //   klinik: "THT",
    //   kodeKlinik: "TH",
    //   fastTrack: "TIDAK",
    //   pembayaran: "VIP",
    //   status: "anjungan",
    //   processStage: "loket",
    //   createdAt: new Date().toISOString(),
    //   registrationType: 'online',
    //   visitType: 'SEKARANG',
    //   visitDate: new Date().toISOString().substring(0, 10),
    //   namaDokter: "Dr. Eka Putri, Sp.THT",
    //   noRM: "RM-E004",
    //   penanggungJawab: null,
    //   alasanFastTrack: null,
    // },
  ];



  const cloneSeed = () => seedPatients.map(p => ({ ...p }));

  // Initialize counters from seed data to ensure numbering continues correctly
  // Counter SHARED untuk semua payment group dan semua jenis pasien
  // Calculate max queue number from seeds or existing patients
  const syncCountersWithState = () => {
    if (typeof window === 'undefined') return;
    
    const today = new Date().toISOString().split('T')[0];
    const STORAGE_KEY_BARCODE = `barcode_counter_${today.replace(/-/g, '').substring(2)}`;
    
    // Determine the source of patients (prefer current state, fallback to seeds)
    const sourcePatients = allPatients.value.length > 0 ? allPatients.value : seedPatients;
    
    // Find max barcode counter
    let maxBarcodeCounter = 0;
    sourcePatients.forEach(patient => {
      const barcode = patient.barcode || '';
      if (barcode.length > 5) {
        const counterStr = barcode.substring(barcode.length - 5);
        const counter = parseInt(counterStr, 10);
        if (!isNaN(counter) && counter > maxBarcodeCounter) {
          maxBarcodeCounter = counter;
        }
      }
    });

    // Initialize barcode counter if not exists or smaller
    const existingBarcode = localStorage.getItem(STORAGE_KEY_BARCODE);
    if (!existingBarcode || parseInt(existingBarcode, 10) < maxBarcodeCounter) {
      localStorage.setItem(STORAGE_KEY_BARCODE, maxBarcodeCounter.toString());
    }

    // Existing queue counter logic...
    const counterKeyQueue = `queue_counter_loket_shared_${today}`;
    
    // Calculate max queue number from seeds dynamically
    const maxQueueCounter = sourcePatients.length > 0 
      ? Math.max(...sourcePatients.map(p => p.no)) 
      : 0;

    const existingQueue = localStorage.getItem(counterKeyQueue);
    // Always update if current max in memory is larger than stored
    if (!existingQueue || parseInt(existingQueue) < maxQueueCounter) {
      localStorage.setItem(counterKeyQueue, maxQueueCounter.toString()); 
    }
  };

  // Initial state - START EMPTY to avoid clashing with hydration
  const allPatients = ref([]);
  const quotaUsed = ref(5);
  // State - currentProcessingPatient is now an object mapping 'stage-id' to patient
  // For example: { 'loket-1': patient, 'loket-2': patient, 'klinik-3': patient }
  const currentProcessingPatient = ref({});

  // Daftar klinik untuk dropdown diambil 1 pintu dari clinicStore
  const kliniks = ref(clinicStore.clinics || []);

  // Penunjang data - reference dari penunjangStore
  const penunjangs = ref(penunjangStore.penunjangs || []);

  const RESET_HOUR = 2; // 2 AM reset threshold

  /**
   * Get logical reset threshold date object
   * If current time is before 2 AM, the threshold is yesterday at 2 AM.
   * If current time is after 2 AM, the threshold is today at 2 AM.
   */
  const getResetThreshold = () => {
    const now = new Date();
    const threshold = new Date(now);
    threshold.setHours(RESET_HOUR, 0, 0, 0);
    
    if (now.getHours() < RESET_HOUR) {
      threshold.setDate(threshold.getDate() - 1);
    }
    
    return threshold;
  };

  /**
   * Check if data needs to be reset (passed 2 AM of a new day)
   */
  const checkAndResetDaily = () => {
    const threshold = getResetThreshold();
    const thresholdTS = threshold.getTime();
    
    // Use localStorage to persist last reset time across sessions/tabs
    const lastResetStr = localStorage.getItem('queue_last_reset_time');
    const lastResetTS = lastResetStr ? parseInt(lastResetStr, 10) : 0;
    
    if (lastResetTS < thresholdTS) {
      console.log(`🕒 [queueStore] Daily reset triggered. Threshold: ${threshold.toLocaleString()}`);
      
      // Clear data
      allPatients.value = [];
      apiPatientsPerLoket.value = {};
      currentProcessingPatient.value = {};
      
      // Update reset timestamp
      localStorage.setItem('queue_last_reset_time', thresholdTS.toString());
      
      // Re-sync counters for the new day
      syncCountersWithState();
      
      return true;
    }
    return false;
  };

  /**
   * Filter strictly to only show today's patients (after 2 AM)
   */
  const isTodayPatient = (patient) => {
    if (!patient) return false;
    
    // Status processing overrides filter (always show if currently processing)
    const isProcessing = Object.values(currentProcessingPatient.value).some(p => p && p.no === patient.no);
    if (isProcessing) return true;

    const threshold = getResetThreshold();
    
    // Get YYYY-MM-DD for the logical "today" (based on 2 AM threshold)
    const year = threshold.getFullYear();
    const month = String(threshold.getMonth() + 1).padStart(2, '0');
    const day = String(threshold.getDate()).padStart(2, '0');
    const logicalTodayStr = `${year}-${month}-${day}`;
    
    // 1. If visitDate (YYYY-MM-DD) matches logical today's date, it's a "today" patient
    // This correctly includes API patients with midnight timestamps (00:00:00)
    if (patient.visitDate) {
      if (patient.visitDate === logicalTodayStr) return true;
      if (patient.visitDate < logicalTodayStr) return false;
    }
    
    // 2. Fallback: check createdAt timestamp (critical for seed/manual tickets)
    // Tickets created before today's 2 AM are stale
    const createdAt = patient.createdAt ? new Date(patient.createdAt) : null;
    if (createdAt && createdAt < threshold) {
      return false;
    }
    
    return true;
  };

  /**
   * Ensures initial data exists.
   * Only seeds if the store is empty (not hydrated from storage)
   */
  const ensureInitialData = () => {
    // 1. Check for daily reset first
    checkAndResetDaily();

    if (allPatients.value.length === 0) {
      console.log('🌱 Seeding queueStore with initial data...');
      allPatients.value = cloneSeed();
    }
    // ALWAYS sync counters with state (hydrated or seeded) to ensure next number is correct
    syncCountersWithState();
  };

  // Synchronization Guard: track if we are currently hydrating from another tab
  let isSyncing = false;

  // CROSS-TAB SYNC: Listen for storage events to update store across tabs
  if (typeof window !== 'undefined') {
    window.addEventListener('storage', (event) => {
      if (event.key === 'queue-store-state') {
        if (!event.newValue) return;

        try {
          const newState = JSON.parse(event.newValue);
          
          // BREAK THE LOOP: Only re-hydrate if the incoming data is strictly newer than ours
          // Defensive check: Handle cases where lastUpdated might be undefined or missing
          const incomingVersion = Number(newState?.lastUpdated || 0);
          const currentVersion = Number(lastUpdated.value || 0);
          
          if (incomingVersion === 0 || incomingVersion <= currentVersion) {
            // Already up to date, older, or corrupted data. Skip hydration.
            return; 
          }

          console.log(`🔄 Syncing state to version: ${incomingVersion}`);
          
          if (newState) {
            isSyncing = true; // Block local watch from updating timestamp
            
            try {
              if (newState.allPatients) allPatients.value = newState.allPatients;
              if (newState.quotaUsed !== undefined) quotaUsed.value = newState.quotaUsed;
              if (newState.currentProcessingPatient) currentProcessingPatient.value = newState.currentProcessingPatient;
              if (newState.apiPatientsPerLoket) apiPatientsPerLoket.value = newState.apiPatientsPerLoket;
              
              // Set local timestamp to match the source
              lastUpdated.value = incomingVersion;
              
              syncCountersWithState();
            } finally {
              // Ensure we release the lock
              setTimeout(() => { isSyncing = false; }, 50);
            }
          }
        } catch (e) {
          console.error('Error hydrating from storage event:', e);
          isSyncing = false;
        }
      }
    });
  }

  // Automatic timestamp update for local changes
  // This ensures lastUpdated changes whenever state changes LOCALLY
  // but skips updates coming from isSyncing = true
  watch([allPatients, quotaUsed, currentProcessingPatient, apiPatientsPerLoket], () => {
    if (!isSyncing) {
      lastUpdated.value = Date.now();
      // console.log('✨ Local state updated, version:', lastUpdated.value);
    }
  }, { deep: true });

  // Computed - Filter berdasarkan process stage dan status
  const getPatientsByStage = (stage) => {
    return computed(() => {
      // Filter by stage AND date (today only)
      // optimization: filter all once, then sub-filter
      const patients = allPatients.value.filter(p => p && p.processStage === stage && isTodayPatient(p));
      
      // Debug log (limited to avoid spam)
      if (patients.length > 0) {
        // console.log(`getPatientsByStage(${stage}):`, patients.length, 'patients (Today)');
      }
      
      return {
        all: patients,
        anjungan: patients.filter(p => p.status === 'anjungan'),
        menunggu: patients.filter(p => p.status === 'menunggu'),
        diLoket: patients.filter(p => p.status === 'di-loket'),
        terlambat: patients.filter(p => p.status === 'terlambat'),
        pending: patients.filter(p => p.status === 'pending'),
      };
    });
  };

  // Total pasien per stage - strictly today
  const getTotalPasienByStage = (stage) => {
    return computed(() => 
      allPatients.value.filter(p => p.processStage === stage && isTodayPatient(p)).length
    );
  };

  const totalPasien = computed(() => allPatients.value.length);

  const resetPatients = () => {
    allPatients.value = cloneSeed();
    quotaUsed.value = 5;
    currentProcessingPatient.value = { loket: null, klinik: null, penunjang: null };
    syncCountersWithState(); // Re-initialize counters after reset
  };

  // Action: Ambil Antrean Masuk dari Anjungan (Reservoir -> Waiting Room)
  // "fungsi ini juga sesuaikan dengan idloket dan klinik id"
  // "hanya memanggil tiket dari loket lain harus tiket menunggu yang sesuai id loket dan id kliniknya"
  const callNext = (adminType = 'loket', specificId = null) => {
    const stageMap = {
      'loket': 'loket',
      'klinik': 'klinik',
      'penunjang': 'penunjang'
    };
    
    const targetStage = stageMap[adminType];
    const targetId = specificId;
    
    // Filter list by stage AND relevance to this specific loket/clinic/penunjang
    const eligiblePatients = allPatients.value.filter(p => {
      // 1. Stage Check
      if (p.processStage !== targetStage) return false;
      
      // 2. Relevance Check based on adminType
      if (targetId) {
        if (adminType === 'loket') {
          const thisLoket = loketStore.getLoketById(parseInt(targetId));
          // Enforce clinic mapping (pelayanan)
          if (thisLoket && thisLoket.pelayanan && Array.isArray(thisLoket.pelayanan)) {
            if (!thisLoket.pelayanan.includes(p.kodeKlinik)) return false;
          }
          // Enforce assignment if present
          if (p.loketId && String(p.loketId) !== String(targetId)) return false;
        } 
        else if (adminType === 'klinik') {
          // Clinic ID match
          if (String(p.kodeKlinik) !== String(targetId) && String(p.klinik) !== String(targetId)) return false;
        }
        else if (adminType === 'penunjang') {
          // Penunjang match
          if (String(p.klinik) !== String(targetId) && String(p.kodeKlinik) !== String(targetId)) return false;
        }
      }
      
      return true;
    });

    // PRIORITAS: Hanya ambil pasien dengan status 'menunggu' (Antrean Baru dari Anjungan)
    // "bukan untuk memanggil pasien tapi tiket baru dari anjungan yang statusnya menunggu"
    const nextPatient = eligiblePatients.find(p => p.status === 'menunggu');

    if (!nextPatient) {
      return { success: false, message: `Tidak ada antrean baru yang sesuai untuk ${adminType} ${targetId || ''}` };
    }

    // Hitung kuota yang tersedia (khusus loket ini)
    const diLoketCount = allPatients.value.filter(p => 
      p.status === 'di-loket' && 
      p.processStage === targetStage && 
      (targetId && adminType === 'loket' ? String(p.loketId) === String(targetId) : true)
    ).length;
    const availableQuota = 150 - diLoketCount;

    if (availableQuota <= 0) {
      return { success: false, message: "Kuota sudah penuh" };
    }

    // Update status menjadi 'anjungan' (Masuk ke antrean aktif)
    const callTimestamp = new Date().toISOString();
    const index = allPatients.value.findIndex(p => p.no === nextPatient.no);
    if (index !== -1) {
      allPatients.value[index] = { 
        ...allPatients.value[index], 
        status: "anjungan",
        // Assign to this specific loket if it was unassigned
        loketId: (adminType === 'loket' && targetId) ? parseInt(targetId) : allPatients.value[index].loketId,
        lastCalledAt: callTimestamp
      };

      // SYNC to apiPatientsPerLoket if it's an API patient
      syncApiPatientStatus(allPatients.value[index], "anjungan");

      // POST to external API when patient is called
      try {
        fetch('http://10.10.150.131:8089/api/v1/tiket/update', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            barcode: nextPatient.barcode || "",
            statuspasien: "3",
            statuspasien2: "4",
            idklinikstatus: "1",
            idklinikstatus2: "1"
          })
        }).then(response => {
          if (response.ok) {
            console.log(`✅ Successfully posted status update for patient ${nextPatient.barcode}`);
          } else {
            console.error(`⚠️ Failed to post status update for patient ${nextPatient.barcode}:`, response.status);
          }
        }).catch(error => {
          console.error(`❌ Error posting status update for patient ${nextPatient.barcode}:`, error);
        });
      } catch (error) {
        console.error(`❌ Error initiating status update for patient ${nextPatient.barcode}:`, error);
      }
    }

    return {
      success: true,
      message: `Berhasil mengambil antrean ${nextPatient.noAntrian.split(" |")[0]} ke daftar tunggu`,
    };
  };

  const callMultiplePatients = (count, adminType = 'loket', specificId = null) => {
    const stageMap = { 'loket': 'loket', 'klinik': 'klinik', 'penunjang': 'penunjang' };
    const targetStage = stageMap[adminType];
    const targetId = specificId;

    const eligiblePatients = allPatients.value.filter(p => {
      if (p.processStage !== targetStage) return false;
      if (targetId) {
        if (adminType === 'loket') {
          const thisLoket = loketStore.getLoketById(parseInt(targetId));
          if (thisLoket && thisLoket.pelayanan && Array.isArray(thisLoket.pelayanan)) {
            if (!thisLoket.pelayanan.includes(p.kodeKlinik)) return false;
          }
          if (p.loketId && String(p.loketId) !== String(targetId)) return false;
        } else if (adminType === 'klinik' || adminType === 'penunjang') {
          if (String(p.kodeKlinik) !== String(targetId) && String(p.klinik) !== String(targetId)) return false;
        }
      }
      return true;
    });

    // Hanya ambil pasien status 'menunggu'
    const menungguList = eligiblePatients.filter(p => p.status === 'menunggu');

    if (menungguList.length === 0) {
      return { success: false, message: `Tidak ada antrean baru yang sesuai untuk ${adminType} ${targetId || ''}` };
    }

    // Hitung kuota yang tersedia
    const diLoketCount = allPatients.value.filter(p => 
      p.status === 'di-loket' && 
      p.processStage === targetStage &&
      (targetId && adminType === 'loket' ? String(p.loketId) === String(targetId) : true)
    ).length;
    const availableQuota = 150 - diLoketCount;

    const maxCallable = Math.min(count, menungguList.length, availableQuota);
    
    if (maxCallable <= 0) {
      if (availableQuota <= 0) return { success: false, message: "Kuota sudah penuh" };
      return { success: false, message: "Tidak ada antrean yang bisa diambil" };
    }

    const patientsToCall = menungguList.slice(0, maxCallable);
    const callTimestamp = new Date().toISOString();

    patientsToCall.forEach(async (patient) => {
      const index = allPatients.value.findIndex(p => p.no === patient.no);
      if (index !== -1) {
        const newStatus = "anjungan";
        const newLoketId = (adminType === 'loket' && targetId) ? targetId : allPatients.value[index].loketId;
        
        allPatients.value[index] = {
          ...allPatients.value[index],
          status: newStatus,
          loketId: newLoketId,
          lastCalledAt: callTimestamp
        };

        // SYNC to apiPatientsPerLoket if it's an API patient
        syncApiPatientStatus(allPatients.value[index], newStatus);

        // POST to external API when patient is called
        try {
          const response = await fetch('http://10.10.150.131:8089/api/v1/tiket/update', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              barcode: patient.barcode || "",
              statuspasien: "3",
              statuspasien2: "4",
              idklinikstatus: "1",
              idklinikstatus2: "1"
            })
          });

          if (response.ok) {
            console.log(`✅ Successfully posted status update for patient ${patient.barcode}`);
          } else {
            console.error(`⚠️ Failed to post status update for patient ${patient.barcode}:`, response.status);
          }
        } catch (error) {
          console.error(`❌ Error posting status update for patient ${patient.barcode}:`, error);
        }
      }
    });

    return {
      success: true,
      message: `Berhasil mengambil ${patientsToCall.length} antrean ke daftar tunggu`,
    };
  };

  const processPatient = (patient, action, adminType = 'loket', specificId = null) => {
    const storageKey = specificId ? `${adminType}-${specificId}` : adminType;
    const patientCode = patient.noAntrian.split(" |")[0];
    let message = "";
    
    // Find patient index for reactive update
    const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
    
    if (patientIndex === -1) {
      return { success: false, message: "Pasien tidak ditemukan" };
    }

    switch (action) {
      case "check-in":
        // Jika check-in di loket, pindahkan ke klinik dengan status di-loket
        if (adminType === 'loket') {
          allPatients.value[patientIndex] = {
            ...allPatients.value[patientIndex],
            status: "di-loket",
            processStage: "klinik",
            calledByAdmin: false // Reset flag saat pindah stage
          };
          syncApiPatientStatus(allPatients.value[patientIndex], "di-loket");
          message = `Pasien ${patientCode} berhasil check in dan masuk ke Tabel Loket Klinik`;
        } 
        // Jika check-in di klinik, selesai
        else if (adminType === 'klinik') {
          allPatients.value[patientIndex] = {
            ...allPatients.value[patientIndex],
            status: "processed"
          };
          syncApiPatientStatus(allPatients.value[patientIndex], "processed");
          message = `Pasien ${patientCode} berhasil check in di Klinik`;
        }
        // Jika check-in di penunjang, selesai
        else if (adminType === 'penunjang') {
          allPatients.value[patientIndex] = {
            ...allPatients.value[patientIndex],
            status: "processed"
          };
          syncApiPatientStatus(allPatients.value[patientIndex], "processed");
          message = `Pasien ${patientCode} berhasil check in di Penunjang`;
        }
        
        // Clear current processing di admin yang melakukan check-in
        if (currentProcessingPatient.value[storageKey]?.no === patient.no) {
          currentProcessingPatient.value[storageKey] = null;
        }
        break;

      case "terlambat":
        allPatients.value[patientIndex] = {
          ...allPatients.value[patientIndex],
          status: "terlambat",
          calledByAdmin: false // Reset flag
        };
        if (currentProcessingPatient.value[storageKey]?.no === patient.no) {
          currentProcessingPatient.value[storageKey] = null;
        }
        message = `Pasien ${patientCode} ditandai terlambat`;
        break;

      case "pending":
        allPatients.value[patientIndex] = {
          ...allPatients.value[patientIndex],
          status: "pending",
          calledByAdmin: false // Reset flag
        };
        if (currentProcessingPatient.value[storageKey]?.no === patient.no) {
          currentProcessingPatient.value[storageKey] = null;
        }
        message = `Pasien ${patientCode} di-pending`;
        break;

      case "aktifkan": {
        const currentStatus = allPatients.value[patientIndex].status;
        if (currentStatus === "terlambat" || currentStatus === "pending") {
          // PERBAIKAN: Update dengan cara yang Vue reactive
          allPatients.value[patientIndex] = {
            ...allPatients.value[patientIndex],
            status: "di-loket"
          };
          message = `Pasien ${patientCode} diaktifkan kembali dan masuk ke tabel Di Loket`;
        } else {
          message = `Pasien ${patientCode} tidak dapat diaktifkan (status: ${currentStatus})`;
        }
        break;
      }

      case "proses": {
        // Ambil data terbaru dari array
        const patient = allPatients.value[patientIndex];
        
        // Jika pasien memiliki status "pending" atau "terlambat", ubah menjadi "di-loket"
        // agar pasien masuk ke kategori diLoketPatients dan ditampilkan sebagai "diproses"
        const currentStatus = patient.status;
        const shouldUpdateStatus = currentStatus === "pending" || currentStatus === "terlambat";
        
        // Jika adminType adalah 'loket', pastikan ada loket assignment
        if (adminType === 'loket') {
          // Pastikan antrian yang diproses memiliki loket assignment
          const currentLoket = patient.loket || getDefaultLoket();
          const currentLoketId = patient.loketId || 1;
          
          // Update patient dengan loket assignment dan status (jika perlu)
          const updatedPatient = {
            ...patient,
            loket: patient.loket || currentLoket,
            loketId: patient.loketId || currentLoketId,
            // Ubah status menjadi "di-loket" jika sebelumnya "pending" atau "terlambat"
            ...(shouldUpdateStatus && { status: "di-loket" })
          };
          
          allPatients.value[patientIndex] = updatedPatient;
          // Set currentProcessingPatient with isolated key
          currentProcessingPatient.value[storageKey] = updatedPatient;
        } else {
          // Untuk adminType selain loket, update status jika perlu
          if (shouldUpdateStatus) {
            const updatedPatient = {
              ...patient,
              status: "di-loket"
            };
            allPatients.value[patientIndex] = updatedPatient;
            currentProcessingPatient.value[storageKey] = updatedPatient;
          } else {
            currentProcessingPatient.value[storageKey] = patient;
          }
        }
        message = `Memproses pasien ${patientCode}`;
        break;
      }
    }

    return { success: true, message };
  };



  const callProcessingPatient = (adminType = 'loket', specificId = null) => {
    // Panggil pasien yang sedang diproses untuk ditampilkan di layar anjungan
    const storageKey = specificId ? `${adminType}-${specificId}` : adminType;
    const processingPatient = currentProcessingPatient.value[storageKey];
    
    if (!processingPatient) {
      return { success: false, message: "Tidak ada pasien yang sedang diproses" };
    }

    // Update flag calledByAdmin
    const patientIndex = allPatients.value.findIndex(p => p.no === processingPatient.no);
    if (patientIndex !== -1) {
      allPatients.value[patientIndex] = {
        ...allPatients.value[patientIndex],
        calledByAdmin: true,
        lastCalledAt: new Date().toISOString()
      };
      
      // Update currentProcessingPatient with the new data
      currentProcessingPatient.value[storageKey] = allPatients.value[patientIndex];
      
      return {
        success: true,
        message: `Memanggil pasien ${processingPatient.noAntrian.split(" |")[0]}`
      };
    }

    return { success: false, message: "Gagal memanggil pasien" };
  };

  const createAntreanKlinik = (klinik, patient = null, adminType = 'loket') => {
    const newNo = allPatients.value.length + 1;
    const timestamp = new Date();
    const barcode = patient ? patient.barcode : generateBarcode([], allPatients);
    
    const newPatient = {
      no: newNo,
      jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
        timestamp.getMinutes()
      ).padStart(2, "0")}`,
      barcode: barcode,
      noAntrian: `KL${String(newNo).padStart(4, "0")} | Klinik - ${barcode}`,
      shift: "Shift 1",
      klinik: klinik.name,
      fastTrack: "TIDAK",
      pembayaran: patient ? patient.pembayaran : "UMUM",
      noRM: patient ? (patient.noRM || `RM-SCAN-${barcode.slice(-6)}`) : `RM-SCAN-${barcode.slice(-6)}`,
      kodeKlinik: klinik.kode || klinik.id, // Ensure kodeKlinik is saved
      status: "di-loket",
      processStage: "klinik",
      createdAt: timestamp.toISOString(),
      referencePatient: patient ? patient.noAntrian : null,
      loketId: null, // Initial check
    };

    // Auto-assign Loket ID based on Clinic Mapping
    // "menyesuaikan loketnya berdasar loket id tergantung dari create tiket itu di klinik"
    if (newPatient.kodeKlinik) {
       const allLokets = loketStore.lokets || [];
       const targetLoket = allLokets.find(l => 
         l.pelayanan && Array.isArray(l.pelayanan) && l.pelayanan.includes(newPatient.kodeKlinik)
       );
       
       if (targetLoket) {
         newPatient.loketId = targetLoket.id;
         newPatient.loket = targetLoket.namaLoket;
         console.log(`✅ Auto-assigned Ticket ${newPatient.noAntrian} to Loket ${targetLoket.id} (${targetLoket.namaLoket})`);
       } else {
         console.log(`⚠️ No specific Loket found for Clinic ${newPatient.kodeKlinik}, defaulting to general pool.`);
       }
    }

    allPatients.value.push(newPatient);
    
    // Increment counter setelah barcode digunakan
    if (!patient) {
      incrementBarcodeCounter();
    }

    return {
      success: true,
      message: `Antrean klinik ${klinik.name} berhasil dibuat dan masuk ke Tabel Loket Klinik`,
      patient: newPatient,
    };
  };

  const createAntreanPenunjang = (penunjang, patient = null, adminType = 'loket') => {
    const newNo = allPatients.value.length + 1;
    const timestamp = new Date();
    const barcode = patient ? patient.barcode : generateBarcode([], allPatients);

    const newPatient = {
      no: newNo,
      jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
        timestamp.getMinutes()
      ).padStart(2, "0")}`,
      barcode: barcode,
      noAntrian: `PN${String(newNo).padStart(4, "0")} | Penunjang - ${barcode}`,
      shift: "Shift 1",
      klinik: penunjang.name,
      fastTrack: "TIDAK",
      pembayaran: patient ? patient.pembayaran : "UMUM",
      noRM: patient ? patient.noRM : `RM-SCAN-${barcode.slice(-6)}`,
      status: "di-loket",
      processStage: "penunjang",
      createdAt: timestamp.toISOString(),
      referencePatient: patient ? patient.noAntrian : null,
    };

    allPatients.value.push(newPatient);
    
    // Increment counter setelah barcode digunakan
    if (!patient) {
      incrementBarcodeCounter();
    }

    return {
      success: true,
      message: `Antrean penunjang ${penunjang.name} berhasil dibuat dan masuk ke Tabel Loket Penunjang`,
      patient: newPatient,
    };
  };

  const createAntreanKlinikRuang = (klinikRuang, ruang, patient = null, adminType = 'klinik') => {
    const newNo = allPatients.value.length + 1;
    const timestamp = new Date();
    const barcode = patient ? patient.barcode : generateBarcode([], allPatients);

    // Generate nomor antrian baru dengan format: [huruf pertama poli + urutan abjad ruang + nomor antrian ruang]
    // Contoh: "Anak" ruang 1 = "AA001" (A dari Anak, A dari ruang 1, 001 nomor antrian)
    
    // 1. Ambil huruf pertama dari nama klinik/poli
    const firstLetter = klinikRuang.namaKlinik.charAt(0).toUpperCase();
    
    // 2. Konversi nomor ruang ke abjad (1 = A, 2 = B, 3 = C, dst)
    const ruangNumber = parseInt(ruang.nomorRuang) || 1;
    const ruangLetter = String.fromCharCode(64 + ruangNumber); // 64 = '@', 65 = 'A', 66 = 'B', dst
    
    // 3. Hitung nomor antrian ruang (dimulai dari 1, maksimal 3 digit)
    const roomQueues = allPatients.value.filter(p => 
      p.kodeKlinik === klinikRuang.kodeKlinik &&
      p.nomorRuang === ruang.nomorRuang &&
      p.processStage === 'klinik-ruang'
    );
    const queueNumber = roomQueues.length + 1;
    const queueNumberStr = String(queueNumber).padStart(3, "0");
    
    // 4. Format nomor antrian: AA001, AB002, dst
    const newNoAntrian = `${firstLetter}${ruangLetter}${queueNumberStr}`;

    const newPatient = {
      no: newNo,
      jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
        timestamp.getMinutes()
      ).padStart(2, "0")}`,
      barcode: barcode,
      noAntrian: `${newNoAntrian} | ${klinikRuang.namaKlinik} - ${ruang.namaRuang}`,
      noAntrianRuang: `${klinikRuang.namaKlinik} - ${ruang.namaRuang} | ${newNoAntrian}`,
      shift: patient ? (patient.shift || "Shift 1") : "Shift 1",
      klinik: klinikRuang.namaKlinik,
      ruang: ruang.namaRuang,
      kodeKlinik: klinikRuang.kodeKlinik,
      nomorRuang: ruang.nomorRuang,
      nomorScreen: ruang.nomorScreen,
      fastTrack: patient ? (patient.fastTrack || "TIDAK") : "TIDAK",
      pembayaran: patient ? patient.pembayaran : "UMUM",
      noRM: patient ? patient.noRM : null,
      status: "anjungan",
      processStage: "klinik-ruang", // Set ke klinik-ruang langsung
      createdAt: timestamp.toISOString(),
      referencePatient: patient ? patient.noAntrian : null,
      sourcePatientNo: patient ? patient.no : null,
      // Tracking panggilan
      calledPemeriksaanAwal: false,
      calledTindakan: false,
      lastCalledAt: null,
      lastCalledTipeLayanan: null,
      calledByAdmin: false, // Flag untuk tracking apakah sudah dipanggil oleh admin
    };

    allPatients.value.push(newPatient);
    
    // Increment counter setelah barcode digunakan
    if (!patient) {
      incrementBarcodeCounter();
    }

    return {
      success: true,
      message: `Antrean ${klinikRuang.namaKlinik} Ruang ${ruang.nomorRuang} berhasil dibuat: ${newNoAntrian}`,
      patient: newPatient,
    };
  };

  // Pindah pasien ke klinik ruang lain dengan nomor antrian tetap
  const pindahKlinikRuang = (patient, targetKlinikRuang, targetRuang) => {
    const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
    
    if (patientIndex === -1) {
      return { success: false, message: "Pasien tidak ditemukan" };
    }

    const currentPatient = allPatients.value[patientIndex];
    
    // Jika pasien sudah punya antrean klinik ruang, update antreannya
    if (currentPatient.processStage === 'klinik-ruang' && currentPatient.tipeLayanan) {
      const baseNoAntrian = currentPatient.noAntrian?.split(" |")[0] || currentPatient.barcode || '';
      
      // Update dengan klinik dan ruang baru, tapi nomor antrian tetap sama
      allPatients.value[patientIndex] = {
        ...currentPatient,
        klinik: targetKlinikRuang.namaKlinik,
        ruang: targetRuang.namaRuang,
        kodeKlinik: targetKlinikRuang.kodeKlinik,
        nomorRuang: targetRuang.nomorRuang,
        nomorScreen: targetRuang.nomorScreen,
        // Nomor antrian tetap sama
        noAntrian: `${baseNoAntrian} | ${targetKlinikRuang.namaKlinik} - ${targetRuang.namaRuang} - ${currentPatient.tipeLayanan}`,
        noAntrianRuang: `${targetKlinikRuang.namaKlinik} - ${targetRuang.namaRuang} | ${baseNoAntrian}`
      };
      
      // Clear current processing dari ruang lama jika ada
      const oldKey = `klinik-ruang-${currentPatient.kodeKlinik}-${currentPatient.nomorRuang}`;
      if (currentProcessingPatient.value[oldKey]?.no === currentPatient.no) {
        currentProcessingPatient.value[oldKey] = null;
      }
    } else {
      // Pasien belum digenerate tiket, hanya update ruang
      allPatients.value[patientIndex] = {
        ...currentPatient,
        klinik: targetKlinikRuang.namaKlinik,
        ruang: targetRuang.namaRuang,
        kodeKlinik: targetKlinikRuang.kodeKlinik,
        nomorRuang: targetRuang.nomorRuang,
        nomorScreen: targetRuang.nomorScreen
      };
    }

    return {
      success: true,
      message: `Pasien berhasil dipindah ke ${targetKlinikRuang.namaKlinik} Ruang ${targetRuang.nomorRuang}`,
      patient: allPatients.value[patientIndex]
    };
  };

  // Konsultasi: pindah pasien ke klinik ruang lain dengan nomor antrian baru (prefix K- atau KF-)
  const konsultasiKlinikRuang = (patient, targetKlinikRuang, targetRuang, tipeLayanan = 'Pemeriksaan Awal') => {
    const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
    
    if (patientIndex === -1) {
      return { success: false, message: "Pasien tidak ditemukan" };
    }

    const sourcePatient = allPatients.value[patientIndex];
    
    // Cek apakah sudah ada antrean konsultasi di ruang tujuan
    const existingKonsultasi = allPatients.value.find(p => 
      p.referencePatient === sourcePatient.noAntrian &&
      p.kodeKlinik === targetKlinikRuang.kodeKlinik &&
      p.nomorRuang === targetRuang.nomorRuang &&
      p.processStage === 'klinik-ruang' &&
      (p.noAntrian?.startsWith('K-') || p.noAntrian?.startsWith('KF-'))
    );

    if (existingKonsultasi) {
      return { 
        success: false, 
        message: `Pasien sudah memiliki antrean konsultasi di ${targetKlinikRuang.namaKlinik} Ruang ${targetRuang.nomorRuang}` 
      };
    }

    // Generate queue number untuk konsultasi
    const roomQueues = allPatients.value.filter(p => 
      p.kodeKlinik === targetKlinikRuang.kodeKlinik &&
      p.nomorRuang === targetRuang.nomorRuang &&
      p.tipeLayanan === tipeLayanan &&
      p.processStage === 'klinik-ruang' &&
      (p.noAntrian?.startsWith('K-') || p.noAntrian?.startsWith('KF-'))
    );
    
    const queueNumber = roomQueues.length + 1;
    const prefix = tipeLayanan === 'Pemeriksaan Awal' ? 'PA' : 'TD';
    
    // Tentukan prefix konsultasi: KF- untuk Fast Track, K- untuk normal
    const isFastTrack = sourcePatient.fastTrack === "YA";
    const konsultasiPrefix = isFastTrack ? 'KF-' : 'K-';
    const queueNumberStr = String(queueNumber).padStart(3, "0");
    const newNoAntrian = `${konsultasiPrefix}${prefix}${queueNumberStr}`;
    
    const newNo = allPatients.value.length + 1;
    const timestamp = new Date();

    const newPatient = {
      no: newNo,
      jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
        timestamp.getMinutes()
      ).padStart(2, "0")}`,
      barcode: sourcePatient.barcode,
      noAntrian: `${newNoAntrian} | ${targetKlinikRuang.namaKlinik} - ${targetRuang.namaRuang} - ${tipeLayanan}`,
      noAntrianRuang: `${targetKlinikRuang.namaKlinik} - ${targetRuang.namaRuang} | ${newNoAntrian}`,
      shift: sourcePatient.shift || "Shift 1",
      klinik: targetKlinikRuang.namaKlinik,
      ruang: targetRuang.namaRuang,
      kodeKlinik: targetKlinikRuang.kodeKlinik,
      nomorRuang: targetRuang.nomorRuang,
      nomorScreen: targetRuang.nomorScreen,
      tipeLayanan: tipeLayanan,
      fastTrack: sourcePatient.fastTrack || "TIDAK",
      pembayaran: sourcePatient.pembayaran || "UMUM",
      status: "anjungan",
      processStage: "klinik-ruang",
      createdAt: sourcePatient.createdAt || timestamp.toISOString(), // Gunakan createdAt dari pasien awal
      referencePatient: sourcePatient.noAntrian,
      sourcePatientNo: sourcePatient.no,
      isKonsultasi: true, // Flag untuk konsultasi
    };

    allPatients.value.push(newPatient);

    return {
      success: true,
      message: `Antrean konsultasi berhasil dibuat: ${newNoAntrian} untuk ${targetKlinikRuang.namaKlinik} Ruang ${targetRuang.nomorRuang}`,
      patient: newPatient,
    };
  };

  // Scan barcode dan generate antrean klinik ruang baru
  const scanAndCreateAntreanKlinikRuang = (barcodeInput, klinikRuang, ruang, tipeLayanan = 'Pemeriksaan Awal') => {
    // Clean input - remove whitespace and handle prefix letters
    const cleanInput = String(barcodeInput).trim().toUpperCase();
    // Remove leading letters if any (e.g., "J200730100005" -> "200730100005")
    const numericInput = cleanInput.replace(/^[A-Z]+/, '');
    
    // Find patient by barcode or noAntrian
    const sourcePatient = allPatients.value.find(p => {
      // Exact barcode match
      if (p.barcode === cleanInput || p.barcode === numericInput) return true;
      
      // Check if noAntrian includes the input
      const noAntrianUpper = (p.noAntrian || '').toUpperCase();
      if (noAntrianUpper.includes(cleanInput) || noAntrianUpper.includes(numericInput)) return true;
      
      // Try extracting number from noAntrian
      const noAntrianNumber = noAntrianUpper.match(/([A-Z]+)(\d+)/);
      if (noAntrianNumber) {
        const extractedNumber = noAntrianNumber[2];
        if (extractedNumber.includes(numericInput) || numericInput.includes(extractedNumber)) return true;
      }
      
      return false;
    });

    if (!sourcePatient) {
      return { success: false, message: "Pasien tidak ditemukan. Pastikan barcode/nomor antrian benar." };
    }

    // Check if patient already has antrean klinik ruang for this room
    const existingAntrean = allPatients.value.find(p => 
      p.referencePatient === sourcePatient.noAntrian &&
      p.kodeKlinik === klinikRuang.kodeKlinik &&
      p.nomorRuang === ruang.nomorRuang &&
      p.processStage === 'klinik-ruang'
    );

    if (existingAntrean) {
      return { 
        success: false, 
        message: `Pasien sudah memiliki antrean di ${klinikRuang.namaKlinik} Ruang ${ruang.nomorRuang}` 
      };
    }

    // Generate queue number for this specific room and tipeLayanan
    const roomQueues = allPatients.value.filter(p => 
      p.kodeKlinik === klinikRuang.kodeKlinik &&
      p.nomorRuang === ruang.nomorRuang &&
      p.tipeLayanan === tipeLayanan &&
      p.processStage === 'klinik-ruang' &&
      !p.noAntrian?.startsWith('K-') && // Exclude konsultasi
      !p.noAntrian?.startsWith('KF-') // Exclude konsultasi Fast Track
    );
    
    const queueNumber = roomQueues.length + 1;
    const prefix = tipeLayanan === 'Pemeriksaan Awal' ? 'PA' : 'TD';
    
    // Tentukan prefix untuk Fast Track: F- untuk Fast Track
    const isFastTrack = sourcePatient.fastTrack === "YA";
    const fastTrackPrefix = isFastTrack ? 'F-' : '';
    const queueNumberStr = String(queueNumber).padStart(3, "0");
    const newNoAntrian = `${fastTrackPrefix}${prefix}${queueNumberStr}`;
    
    const newNo = allPatients.value.length + 1;
    const timestamp = new Date();

    const newPatient = {
      no: newNo,
      jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
        timestamp.getMinutes()
      ).padStart(2, "0")}`,
      barcode: sourcePatient.barcode,
      noAntrian: `${newNoAntrian} | ${klinikRuang.namaKlinik} - ${ruang.namaRuang} - ${tipeLayanan}`,
      noAntrianRuang: `${klinikRuang.namaKlinik} - ${ruang.namaRuang} | ${newNoAntrian}`,
      shift: sourcePatient.shift || "Shift 1",
      klinik: klinikRuang.namaKlinik,
      ruang: ruang.namaRuang,
      kodeKlinik: klinikRuang.kodeKlinik,
      nomorRuang: ruang.nomorRuang,
      nomorScreen: ruang.nomorScreen,
      tipeLayanan: tipeLayanan,
      fastTrack: sourcePatient.fastTrack || "TIDAK",
      pembayaran: sourcePatient.pembayaran || "UMUM",
      status: "anjungan",
      processStage: "klinik-ruang",
      createdAt: sourcePatient.createdAt || timestamp.toISOString(), // Gunakan createdAt dari pasien awal
      referencePatient: sourcePatient.noAntrian,
      sourcePatientNo: sourcePatient.no,
    };

    allPatients.value.push(newPatient);

    return {
      success: true,
      message: `Antrean ${tipeLayanan} berhasil dibuat: ${newPatient.noAntrian.split(" |")[0]} untuk ${klinikRuang.namaKlinik} Ruang ${ruang.nomorRuang}`,
      patient: newPatient,
    };
  };

  // Get patients by klinik and ruang
  const getPatientsByKlinikRuang = (kodeKlinik, nomorRuang, tipeLayanan = null) => {
    return computed(() => {
      let patients = allPatients.value.filter(p => 
        p.kodeKlinik === kodeKlinik &&
        p.nomorRuang === nomorRuang &&
        p.processStage === 'klinik-ruang'
      );

      if (tipeLayanan) {
        patients = patients.filter(p => p.tipeLayanan === tipeLayanan);
      }

      return {
        all: patients,
        anjungan: patients.filter(p => p.status === 'anjungan'),
        diLoket: patients.filter(p => p.status === 'di-loket'),
        terlambat: patients.filter(p => p.status === 'terlambat'),
        pending: patients.filter(p => p.status === 'pending'),
      };
    });
  };

  // Call next patient for a specific room and tipeLayanan
  const callNextKlinikRuang = (kodeKlinik, nomorRuang, tipeLayanan, allowMultiple = false) => {
    const patients = allPatients.value.filter(p => 
      p.kodeKlinik === kodeKlinik &&
      p.nomorRuang === nomorRuang &&
      p.tipeLayanan === tipeLayanan &&
      p.processStage === 'klinik-ruang' &&
      (p.status === 'anjungan' || (allowMultiple && p.status === 'di-loket'))
    ).sort((a, b) => {
      // Sort by status priority first: anjungan=1, di-loket=2
      const statusPriority = { 'anjungan': 1, 'di-loket': 2 };
      const priorityDiff = (statusPriority[a.status] || 99) - (statusPriority[b.status] || 99);
      if (priorityDiff !== 0) return priorityDiff;
      
      const numA = parseInt(a.noAntrian?.match(/\d+/)?.[0] || '999');
      const numB = parseInt(b.noAntrian?.match(/\d+/)?.[0] || '999');
      return numA - numB;
    });

    if (patients.length === 0) {
      return { success: false, message: `Tidak ada antrian ${tipeLayanan} yang menunggu` };
    }

    const nextPatient = patients[0];
    const index = allPatients.value.findIndex(p => p.no === nextPatient.no);
    if (index !== -1) {
      allPatients.value[index] = {
        ...allPatients.value[index],
        status: "di-loket",
        lastCalledAt: new Date().toISOString()
      };
    }
    return { 
      success: true, 
      message: `Memanggil ${nextPatient.noAntrian.split(" |")[0]}`, 
      patient: allPatients.value[index] 
    };
  };

  // Process patient in klinik ruang (set as current processing)
  const processPatientKlinikRuang = (patient, action, kodeKlinik, nomorRuang) => {
    const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
    if (patientIndex === -1) return { success: false, message: "Pasien tidak ditemukan" };

    const specificId = `${kodeKlinik}-${nomorRuang}`;
    const storageKey = `klinik-ruang-${specificId}`;
    const pCode = patient.noAntrian.split(" |")[0];
    let message = "";

    switch (action) {
      case "proses":
        currentProcessingPatient.value[storageKey] = allPatients.value[patientIndex];
        message = `Memproses ${pCode}`;
        break;
      case "selesai":
        allPatients.value[patientIndex] = { ...allPatients.value[patientIndex], status: "processed" };
        currentProcessingPatient.value[storageKey] = null;
        message = `Pasien ${pCode} selesai diproses`;
        break;
      case "terlambat":
        allPatients.value[patientIndex] = { ...allPatients.value[patientIndex], status: "terlambat" };
        currentProcessingPatient.value[storageKey] = null;
        message = `Pasien ${pCode} ditandai terlambat`;
        break;
      case "pending":
        allPatients.value[patientIndex] = { ...allPatients.value[patientIndex], status: "pending" };
        currentProcessingPatient.value[storageKey] = null;
        message = `Pasien ${pCode} di-pending`;
        break;
    }
    return { success: true, message };
  };

  const changeKlinik = (patient, newKlinik, adminType = 'loket', specificId = null) => {
    const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
    if (patientIndex === -1) return { success: false, message: "Pasien tidak ditemukan" };

    allPatients.value[patientIndex] = { 
      ...allPatients.value[patientIndex], 
      klinik: newKlinik.name, 
      kodeKlinik: newKlinik.kode 
    };
    
    const key = specificId ? `${adminType}-${specificId}` : adminType;
    if (currentProcessingPatient.value[key]?.no === patient.no) {
      currentProcessingPatient.value[key] = { 
        ...currentProcessingPatient.value[key], 
        klinik: newKlinik.name, 
        kodeKlinik: newKlinik.kode 
      };
    }
    return { success: true, message: `Klinik berhasil diubah ke ${newKlinik.name}` };
  };

  const getCurrentProcessing = (adminType, id = null) => {
    const key = id ? `${adminType}-${id}` : adminType;
    return computed(() => currentProcessingPatient.value[key] || null);
  };

  const setCurrentProcessing = (patient, adminType, id = null) => {
    const key = id ? `${adminType}-${id}` : adminType;
    currentProcessingPatient.value[key] = patient;
  };

  const generateQueueNumber = (clinic, paymentType, isEksekutif = false) => {
    const serviceType = isEksekutif ? 'E' : 'R';
    const today = new Date().toISOString().split('T')[0];
    // FIXED: Use the same key as initializeCountersFromSeed
    const counterKey = `queue_counter_loket_shared_${today}`;
    
    let counter = 0;
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem(counterKey);
      counter = stored ? parseInt(stored, 10) : 0;
    }
    
    counter = counter + 1;
    const loketIndex = Math.floor((counter - 1) / 999);
    
    if (loketIndex > 13) {
      counter = 1;
      if (typeof window !== 'undefined') localStorage.setItem(counterKey, '1');
      return `${serviceType}A001`;
    }
    
    const loketLetter = String.fromCharCode(65 + loketIndex);
    const numberInLoket = ((counter - 1) % 999) + 1;
    const numberPart = String(numberInLoket).padStart(3, '0');
    
    if (typeof window !== 'undefined') localStorage.setItem(counterKey, counter.toString());
    
    return `${serviceType}${loketLetter}${numberPart}`;
  };

  // Register patient from Anjungan (onsite registration)
  const registerPatientFromAnjungan = (clinic, paymentType, visitType = 'SEKARANG', visitDate = null, shift = 'Shift 1', namaDokter = null, isFastTrack = false, fastTrackData = null, loketId = null, loket = null) => {
    // 1. Validasi keberadaan (prevent duplicates)
    // Gunakan date today untuk check-in sync
    const timestamp = new Date();
    
    // Generate barcode FIRST to check for existence
    const barcode = generateBarcode([], allPatients);
    
    // Check EXACT barcode match prevent duplicate submission
    const duplicate = allPatients.value.find(p => p.barcode === barcode);
    if (duplicate) {
        return {
            success: false,
            message: "Pasien dengan barcode ini sudah terdaftar untuk hari ini.",
            patient: duplicate
        };
    }

    const newNo = allPatients.value.length > 0 
      ? Math.max(...allPatients.value.map(p => p.no)) + 1 
      : 1;
    
    const visitDateTime = visitDate ? new Date(visitDate) : timestamp;
    const jamPanggil = visitDate 
      ? `${String(visitDateTime.getHours()).padStart(2, "0")}:${String(visitDateTime.getMinutes()).padStart(2, "0")}`
      : `${String(timestamp.getHours()).padStart(2, "0")}:${String(timestamp.getMinutes()).padStart(2, "0")}`;
    
    // Tentukan apakah pasien Eksekutif/Grand Pavilion (jika ada namaDokter, berarti Eksekutif)
    const isEksekutif = namaDokter !== null && namaDokter !== undefined && namaDokter !== '';
    
    // Generate nomor antrean dengan format baru: R/E + Loket (A-N) + 3 digit
    const queueNumber = generateQueueNumber(clinic, paymentType, isEksekutif);
    const finalQueueNumber = isFastTrack ? `F-${queueNumber}` : queueNumber;
    const noAntrian = `${finalQueueNumber} | Onsite - ${barcode}`;
    
    const status = 'menunggu';
    
    const newPatient = {
      no: newNo,
      jamPanggil: jamPanggil,
      barcode: barcode,
      noAntrian: noAntrian,
      shift: shift,
      klinik: clinic.name || clinic,
      kodeKlinik: clinic.kode || null, // Essential for filtering
      fastTrack: isFastTrack ? "YA" : "TIDAK",
      pembayaran: paymentType,
      noRM: `RM-${barcode.slice(-6)}`,
      status: status,
      processStage: "loket",
      createdAt: timestamp.toISOString(),
      registrationType: 'onsite',
      visitType: visitType,
      visitDate: visitDate || timestamp.toISOString().substring(0, 10),
      namaDokter: namaDokter || null,
      loketId: loketId, // Optional loketId
      loket: loket,     // Optional loket name
      calledByAdmin: false,
      penanggungJawab: (isFastTrack && fastTrackData) ? fastTrackData.penanggungJawab : null,
      alasanFastTrack: (isFastTrack && fastTrackData) ? fastTrackData.alasanFastTrack : null,
    };

    // Auto-assign Loket ID if not provided, based on Clinic Mapping
    // fulfill requirement: "adjust based on loket id depending on creation"
    if (!newPatient.loketId && newPatient.kodeKlinik) {
       const allLokets = loketStore.lokets || [];
       const targetLoket = allLokets.find(l => 
         l.pelayanan && Array.isArray(l.pelayanan) && l.pelayanan.includes(newPatient.kodeKlinik)
       );
       
       if (targetLoket) {
         newPatient.loketId = targetLoket.id;
         if (!newPatient.loket) newPatient.loket = targetLoket.namaLoket;
         console.log(`✅ Auto-assigned Onsite Ticket ${newPatient.noAntrian} to Loket ${targetLoket.id} (${targetLoket.namaLoket})`);
       }
    }

    allPatients.value.push(newPatient);
    incrementBarcodeCounter();

    return {
      success: true,
      message: `Pendaftaran ${clinic.name || clinic} berhasil diproses.`,
      patient: newPatient,
    };
  };

  /**
   * Register REGULER patient via API
   * POST to http://10.10.150.131:8089/api/v1/tiket/generate
   */
  const registerRegulerPatientViaApi = async (clinic, paymentType, visitType = 'SEKARANG', isFastTrack = false, fastTrackData = null) => {
    try {
      console.log('🔄 [queueStore] Generating ticket via API for REGULER patient...');
    console.log('📋 [queueStore] Payment Type:', paymentType, '| Clinic:', clinic.name, '| Clinic Code:', clinic.kode);
    
    // 1. Find appropriate idloket based on BOTH clinic code AND payment type
    const allLokets = loketStore.lokets || [];
    
    // Determine payment type for matching (normalize BPJS to JKN for API compatibility)
    const paymentTypeForMatching = paymentType === "BPJS" ? "JKN" : paymentType;
    
    // Find loket that handles BOTH the clinic AND the payment type
    const targetLoket = allLokets.find(l => {
      // Check if loket handles the clinic
      const handlesClinic = l.pelayanan && Array.isArray(l.pelayanan) && l.pelayanan.includes(clinic.kode);
      if (!handlesClinic) return false;
      
      // Check if loket accepts the payment type
      const acceptsPayment = l.pembayaran && Array.isArray(l.pembayaran) && 
        l.pembayaran.some(p => {
          // Handle case-insensitive matching and common variations
          const normalizedP = String(p).toUpperCase().trim();
          const normalizedPayment = String(paymentTypeForMatching).toUpperCase().trim();
          return normalizedP === normalizedPayment || 
                 (normalizedPayment === "JKN" && normalizedP === "BPJS") ||
                 (normalizedPayment === "BPJS" && normalizedP === "JKN");
        });
      
      return handlesClinic && acceptsPayment;
    });
    
    const idloket = targetLoket ? String(targetLoket.id) : "2"; // Default fallback to "2" if not found
    
    console.log('🎯 [queueStore] Target Loket:', targetLoket ? `${targetLoket.namaLoket} (ID: ${targetLoket.id})` : 'Not found (using fallback)', '| Accepts Payment:', targetLoket?.pembayaran);
    
    // 2. Determine idpembayaran based on paymentType
    // BPJS (JKN) = "2", UMUM and others = "1"
    const idpembayaran = paymentType === "BPJS" ? "2" : "1";
      
      // 3. Prepare API Body
      const body = {
        idloket: idloket,
        dokter: "",
        idklinik: String(clinic.id),
        namaklinik: clinic.name,
        idpembayaran: idpembayaran,
        statuspasien: "1",
        statuspasien2: "2",
        idklinikstatus: "1"
      };

      console.log('📤 [queueStore] API Body:', body);

      // 3. Call API
      const response = await fetch('http://10.10.150.131:8089/api/v1/tiket/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(body)
      });

      if (!response.ok) {
        throw new Error(`API error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('📥 [queueStore] API Response:', result);

      if (result.metadata && result.metadata.code !== 200) {
        return { success: false, message: result.message || 'Gagal generate barcode via API' };
      }

      const apiData = result.data;
      if (!apiData || !apiData.barcode) {
        return { success: false, message: 'Data barcode tidak valid dari API' };
      }

      // 4. Map API response to Store Format
      const timestamp = new Date();
      const newNo = allPatients.value.length > 0 
        ? Math.max(...allPatients.value.map(p => p.no)) + 1 
        : 1;

      // Gunakan waktu dari API jika tersedia
      const jamPanggil = apiData.waktutiket || 
        `${String(timestamp.getHours()).padStart(2, "0")}:${String(timestamp.getMinutes()).padStart(2, "0")}`;

      const barcode = apiData.barcode;
      // Penomoran tiket menggunakan "ticket" dari API
      const queueNumber = apiData.ticket || apiData.barcode;
      const finalQueueNumber = isFastTrack ? `F-${queueNumber}` : queueNumber;
      const noAntrian = `${finalQueueNumber} | Onsite - ${barcode}`;

      const newPatient = {
        no: newNo,
        jamPanggil: jamPanggil,
        barcode: barcode,
        noAntrian: noAntrian,
        shift: apiData.shift || 'Shift 1',
        klinik: clinic.name,
        kodeKlinik: clinic.kode,
        fastTrack: isFastTrack ? "YA" : "TIDAK",
        pembayaran: paymentType,
        noRM: `RM-${barcode.slice(-6)}`,
        status: 'menunggu',
        processStage: "loket",
        createdAt: apiData.tangaltiket ? `${apiData.tangaltiket}T${apiData.waktutiket || '00:00:00'}` : timestamp.toISOString(),
        registrationType: 'onsite',
        visitType: visitType,
        visitDate: apiData.tangaltiket || timestamp.toISOString().substring(0, 10),
        namaDokter: null,
        loketId: parseInt(idloket),
        loket: targetLoket ? targetLoket.namaLoket : null,
        calledByAdmin: false,
        penanggungJawab: (isFastTrack && fastTrackData) ? fastTrackData.penanggungJawab : null,
        alasanFastTrack: (isFastTrack && fastTrackData) ? fastTrackData.alasanFastTrack : null,
        // Additional API fields
        idvisit: 1, // Default menunggu
        idtiket: apiData.id
      };

      allPatients.value.push(newPatient);
      // NOTE: Kita tidak perlu incrementBarcodeCounter() di sini karena barcode berasal dari API
      
      console.log(`✅ [queueStore] Successfully registered REGULER patient via API: ${noAntrian}`);

      return {
        success: true,
        message: `Pendaftaran ${clinic.name} berhasil via API.`,
        patient: newPatient
      };

    } catch (error) {
      console.error('❌ [queueStore] Error generating ticket via API:', error);
      return {
        success: false,
        message: `Gagal pendaftaran API: ${error.message}`
      };
    }
  };


  /**
   * Check-in patient via API
   * POST to http://10.10.150.131:8089/api/v1/tiket/checkin
   */
  const checkInPatientViaApi = async (barcode) => {
    try {
      console.log(`🔄 [queueStore] Syncing check-in via API for barcode: ${barcode}...`);
      
      const body = {
        barcode: barcode,
        statuspasien: "5",
        statuspasien2: "6",
        idklinikstatus: "1",
        idklinikstatus2: "2"
      };

      console.log('📤 [queueStore] Check-in API Body:', body);

      const response = await fetch('http://10.10.150.131:8089/api/v1/tiket/checkin', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(body)
      });

      if (!response.ok) {
        throw new Error(`API error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('📥 [queueStore] Check-in API Response:', result);

      return {
        success: true,
        data: result
      };

    } catch (error) {
      console.error('❌ [queueStore] Error syncing check-in via API:', error);
      return {
        success: false,
        message: `Gagal sync check-in API: ${error.message}`
      };
    }
  };


  // Check-in patient (update status from anjungan to di-loket)
  // IMPORTANT: Hanya menggunakan EXACT barcode match untuk menghindari false positive
  // Format barcode: YYMMDD + 5 digit (contoh: 26011500001)
  // Jangan gunakan fallback ke noAntrian atau no karena bisa menyebabkan false positive
  const checkInPatient = async (patientIdOrBarcode) => {
    console.log('🔍 checkInPatient called with:', patientIdOrBarcode);
    console.log('📊 Total patients in store:', allPatients.value.length);
    
    // Clean input - remove whitespace and normalize
    const cleanInput = String(patientIdOrBarcode).trim();
    
    // PRIORITAS: Hanya cari dengan EXACT barcode match (case-insensitive, whitespace-insensitive)
    // Format barcode: YYMMDD + 5 digit (contoh: 26011500001)
    // Jangan gunakan fallback ke noAntrian atau no karena bisa menyebabkan false positive
    const patientIndex = allPatients.value.findIndex(p => {
      // Normalize barcode untuk comparison
      const patientBarcode = String(p.barcode || '').trim();
      
      // EXACT barcode match (case-insensitive, whitespace-insensitive)
      // Ini adalah satu-satunya cara yang aman untuk match pasien
      if (patientBarcode === cleanInput || 
          patientBarcode.toLowerCase() === cleanInput.toLowerCase()) {
        console.log('✅ Found by exact barcode match:', patientBarcode, '===', cleanInput);
        return true;
      }
      
      return false;
    });
    
    if (patientIndex === -1) {
      console.log('❌ Patient not found. Searched for barcode:', cleanInput);
      console.log('📋 Available barcodes (first 10):', allPatients.value.slice(0, 10).map(p => ({
        no: p.no,
        barcode: p.barcode,
        noAntrian: p.noAntrian?.split(' |')[0]
      })));
      return { success: false, message: `Pasien dengan barcode ${cleanInput} tidak ditemukan. Pastikan barcode benar (format: YYMMDD + 5 digit, contoh: 26011500001).` };
    }

    // IMPORTANT: Get fresh patient data from array to avoid stale data
    // Use the patientIndex we found earlier, but get fresh data from array
    const patient = allPatients.value[patientIndex];
    console.log('✅ Patient found (fresh):', {
      no: patient.no,
      barcode: patient.barcode,
      noAntrian: patient.noAntrian,
      status: patient.status,
      processStage: patient.processStage
    });
    
    // Only allow check-in if status is anjungan (sudah dipanggil) or pending
    // Pasien dengan status "menunggu" belum bisa check-in (belum dipanggil)
    if (patient.status === 'menunggu') {
      console.log('⚠️ Patient status is menunggu (belum dipanggil):', patient.status);
      return { 
        success: false, 
        message: `Pasien belum dipanggil oleh admin loket. Mohon menunggu hingga nomor antrean Anda dipanggil.` 
      };
    }
    
    // Check if already checked in
    if (patient.status === 'di-loket') {
      console.log('⚠️ Patient already checked in:', patient.status);
      return { 
        success: false, 
        message: `Pasien sudah melakukan check-in sebelumnya. Status saat ini: ${patient.status}` 
      };
    }
    
    if (patient.status !== 'anjungan' && patient.status !== 'pending') {
      console.log('⚠️ Patient status is not anjungan/pending:', patient.status);
      return { 
        success: false, 
        message: `Pasien tidak dapat check-in. Status saat ini: ${patient.status}` 
      };
    }

    // Update status to di-loket using the patientIndex
    allPatients.value[patientIndex] = {
      ...allPatients.value[patientIndex],
      status: "di-loket",
    };
    syncApiPatientStatus(allPatients.value[patientIndex], "di-loket");
    
    console.log('✅ Check-in successful locally, patient status updated to di-loket');

    // Sync to API
    const apiSyncResult = await checkInPatientViaApi(allPatients.value[patientIndex].barcode);
    if (!apiSyncResult.success) {
      console.warn('⚠️ Check-in API sync failed:', apiSyncResult.message);
      // We still return true because local state is updated, but we could also return failure if critical
    }

    return {
      success: true,
      message: `Check-in berhasil. Pasien ${patient.noAntrian.split(" |")[0]} siap diproses di loket.`,
      patient: allPatients.value[patientIndex],
    };
  };

  // FIX: Explicit implementation of processNextQueue to prevent cross-loket leakage
  const processNextQueueCorrected = (adminType = 'loket', specificId = null) => {
    // 1. Determine target stage and key
    const stageMap = { 'loket': 'loket', 'klinik': 'klinik', 'penunjang': 'penunjang' };
    const targetStage = stageMap[adminType];
    const key = specificId ? `${adminType}-${specificId}` : adminType;

    console.log(`🚀 [processNextQueue] Processing for ${key} (Stage: ${targetStage})`);

    // 2. Find next patient (Status: 'menunggu' -> 'anjungan')
    // Prioritaskan yang assigned ke loket ini (loketId) jika ada match
    let nextPatient = null;
    
    if (adminType === 'loket' && specificId) {
       // Cari yang spesifik untuk loket ini dulu
       nextPatient = allPatients.value.find(p => 
         p.status === 'menunggu' && 
         p.processStage === targetStage &&
         String(p.loketId) === String(specificId)
       );
    }
    
    // Jika tidak ada yang spesifik, cari yang umum (menunggu & loketId null/match)
    if (!nextPatient) {
       nextPatient = allPatients.value.find(p => 
         p.status === 'menunggu' && 
         p.processStage === targetStage &&
         (adminType !== 'loket' || !p.loketId || String(p.loketId) === String(specificId))
       );
    }
    
    // Fallback: Check 'anjungan' status if needed (though usually 'menunggu' is for calling)
    if (!nextPatient) {
        nextPatient = allPatients.value.find(p => 
         p.status === 'anjungan' && 
         p.processStage === targetStage &&
         (adminType !== 'loket' || String(p.loketId) === String(specificId))
       );
    }

    if (!nextPatient) {
      return { success: false, message: "Tidak ada antrean yang menunggu untuk diproses." };
    }

    // 3. Update Patient Status (di-loket)
    const index = allPatients.value.findIndex(p => p.no === nextPatient.no);
    if (index !== -1) {
      const updatedPatient = {
        ...allPatients.value[index],
        status: 'di-loket',
        loketId: specificId || allPatients.value[index].loketId, // Ensure loketId is set
        lastCalledAt: new Date().toISOString()
      };
      
      allPatients.value[index] = updatedPatient;
      syncApiPatientStatus(allPatients.value[index], 'di-loket');
      
      // 4. Set Current Processing ISOLATED by key
      currentProcessingPatient.value[key] = updatedPatient;
      
      return { 
        success: true, 
        message: `Memproses ${nextPatient.noAntrian.split(" |")[0]}`,
        patient: updatedPatient
      };
    }
    
    return { success: false, message: "Gagal memproses antrean." };
  };

  return {
    // State
    allPatients,
    resetPatients,
    ensureInitialData,
    quotaUsed,
    currentProcessingPatient,
    kliniks,
    penunjangs,

    // API Patient State
    apiPatientsPerLoket,
    isLoadingPatients,
    apiPatientsError,

    // Computed
    totalPasien,

    // Actions
    callNext,
    callMultiplePatients,
    processPatient,
    callProcessingPatient,
    createAntreanKlinik,
    createAntreanPenunjang,
    createAntreanKlinikRuang,
    scanAndCreateAntreanKlinikRuang,
    getPatientsByKlinikRuang,
    callNextKlinikRuang,
    processPatientKlinikRuang,
    changeKlinik,
    pindahKlinikRuang,
    konsultasiKlinikRuang,
    processNextQueue: processNextQueueCorrected,
    getPatientsByStage,
    getTotalPasienByStage,
    getCurrentProcessing,
    setCurrentProcessing,
    registerPatientFromAnjungan,
    checkInPatient,
    generateQueueNumber,
    generateBarcode,
    incrementBarcodeCounter,
    syncCountersWithState,

    // API Patient Actions
    fetchPatientsForLoket,
    getPatientsForLoket,
    mapStatusFromDeskripsi,
    mapApiPatientToStoreFormat,
    registerRegulerPatientViaApi,
    checkInPatientViaApi,
    checkAndResetDaily,
    isTodayPatient,
    getResetThreshold,
  };

}, {
  persist: {
    key: 'queue-store-state',
    storage: typeof window !== 'undefined' ? localStorage : undefined,
    paths: ['allPatients', 'quotaUsed', 'currentProcessingPatient', 'apiPatientsPerLoket', 'lastUpdated'],
    serializer: {
      deserialize: JSON.parse,
      serialize: JSON.stringify,
    },
    restore: (value) => {
      // Ensure allPatients is always an array
      if (value && value.allPatients && !Array.isArray(value.allPatients)) {
        value.allPatients = [];
      }
      return value;
    },
  },
});