<!-- pages/Anjungan/AntrianKlinikRuang/index.vue -->
<template>
  <div>
    <div class="selection-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="main-title">Pilih Klinik Ruang</h1>
        <p class="subtitle">RSUD dr. Saiful Anwar Provinsi Jawa Timur</p>
      </div>
    </div>

    <ClientOnly>
      <div class="klinik-selection-container">
        <div v-if="visibleKliniks.length > 0" class="kliniks-grid">
        <div
          v-for="klinik in visibleKliniks"
          :key="klinik.id"
          class="klinik-card"
          @click="navigateToKlinik(klinik)"
        >
          <div class="klinik-card-header">
            <v-icon size="32" color="primary">mdi-hospital-building</v-icon>
            <div class="klinik-info">
              <h3 class="klinik-name">{{ klinik.namaKlinik || 'Unknown Clinic' }}</h3>
              <div class="klinik-details">
                <v-chip 
                  size="x-small" 
                  :class="klinik.jenisLayanan === 'Reguler' ? 'chip-reguler' : 'chip-eksekutif'"
                >
                  {{ klinik.jenisLayanan || 'Reguler' }}
                </v-chip>
                <span class="kode-chip">{{ klinik.kodeKlinik }}</span>
              </div>
            </div>
          </div>
          
          <div class="klinik-ruang-preview">
            <div class="ruang-count">
              <v-icon size="18" color="primary">mdi-door</v-icon>
              <span>{{ (klinik.ruangList || []).length }} Ruang</span>
            </div>
            <div class="ruang-tags">
              <template v-if="klinik.ruangList && klinik.ruangList.length > 0">
                <v-chip
                  v-for="(ruang, idx) in klinik.ruangList.slice(0, 3)"
                  :key="`${klinik.id}-ruang-${idx}`"
                  size="small"
                  class="ma-1 chip-preview"
                >
                  {{ ruang.namaRuang }}
                </v-chip>
                <v-chip
                  v-if="klinik.ruangList.length > 3"
                  size="small"
                  class="ma-1 chip-more"
                >
                  +{{ klinik.ruangList.length - 3 }}
                </v-chip>
              </template>
              <div v-else class="text-caption text-grey">Tidak ada ruang terdaftar</div>
            </div>
          </div>

          <div class="klinik-card-footer">
            <v-btn
              color="primary"
              variant="flat"
              size="large"
              block
              class="btn-view"
            >
              <v-icon left>mdi-eye</v-icon>
              Tampilkan
            </v-btn>
          </div>
        </div>
        
        <!-- Sentinel for Infinite Scroll (placed inside the row but spanning full width) -->
        <div ref="targetRef" class="sentinel" style="height: 20px; width: 100%; grid-column: 1 / -1;"></div>
      </div>

        <div v-else class="empty-state">
          <v-icon size="64" color="grey-lighten-1">mdi-hospital-building-off</v-icon>
          <h3>Tidak Ada Klinik dengan Ruang Tersedia</h3>
          <p>Silakan tambah ruang klinik terlebih dahulu di halaman master</p>
          <v-btn
            color="primary"
            variant="flat"
            @click="navigateToSettings"
            class="mt-4"
          >
            <v-icon left>mdi-cog</v-icon>
            Ke Halaman Master
          </v-btn>
        </div>
      </div>
      <template #fallback>
        <div class="d-flex justify-center align-center" style="height: 400px;">
          <v-progress-circular indeterminate color="primary" size="64"></v-progress-circular>
        </div>
      </template>
    </ClientOnly>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useMasterStore } from '@/stores/masterStore';
import { useClinicStore } from '@/stores/clinicStore';
import { useRuangStore } from '@/stores/ruangStore';
import { useInfiniteScroll } from '@/composables/useInfiniteScroll';
import { useRoute } from '#app';

definePageMeta({
  layout: false,
});

const masterStore = useMasterStore();
const clinicStore = useClinicStore();
const ruangStore = useRuangStore();
const route = useRoute();

// Simplified computed to use masterStore.ruangData (which is already grouped/processed by ruangStore)
const kliniksWithRuang = computed(() => {
  const list = masterStore.ruangData || [];
  return [...list].sort((a, b) => a.namaKlinik.localeCompare(b.namaKlinik));
});

// Infinite Scroll
const { visibleItems: visibleKliniks, targetRef, hasMore } = useInfiniteScroll(kliniksWithRuang, 12);

// Deprecated: Pagination logic removed


const navigateToKlinik = (klinik) => {
  // Build URL with jenisLayanan query parameter to differentiate same clinic codes
  const url = `/anjungan/antrianklinikruang/${klinik.kodeKlinik}`;
  const query = klinik.jenisLayanan ? { jenisLayanan: klinik.jenisLayanan } : {};
  navigateTo({ path: url, query });
};

const navigateToSettings = () => {
  navigateTo('/setting/masterklinikruang');
};

// Load data on mount
onMounted(async () => {
  console.log('🚀 Anjungan/AntrianKlinikRuang/index mounted, loading data...');
  
  try {
    // 1. Fetch clinics from API (uses cache if available)
    await clinicStore.fetchRegulerClinics();
    
    // 2. Sync room definitions from API (centralized logic)
    await ruangStore.fetchRuangFromAPI();
    
    console.log('✅ Anjungan/index data sync completed');
  } catch (error) {
    console.error('❌ Error loading data:', error);
  }
});
</script>

<style scoped lang="scss">
.klinik-selection-container {
  background: var(--color-neutral-300);
  min-height: calc(100vh - 80px);
  padding: 16px;
  font-family: 'Inter', 'Roboto', sans-serif;
}

.kliniks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  gap: 20px;
  width: 100%;
  margin: 0;
}

@media (max-width: 1280px) {
  .kliniks-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 960px) {
  .kliniks-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

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

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

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

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

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

@media (max-width: 1440px) {
  /* Legacy grid styles removed */
}

.klinik-card {
  background: var(--color-neutral-100);
  border-radius: 20px;
  padding: clamp(16px, 2vw, 24px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 2px solid var(--color-neutral-400);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 280px; /* Ensure enough height for content */
  height: 100%;

  &:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 24px rgba(33, 150, 243, 0.2);
    border-color: var(--color-primary-600);
    z-index: 2;
  }
}

.klinik-card-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding-bottom: clamp(12px, 1.5vw, 16px);
  border-bottom: 2px solid var(--color-neutral-400);
  flex-shrink: 0;
}

.klinik-info {
  flex: 1;
}

.klinik-name {
  font-size: 20px;
  font-weight: 700;
  margin: 0;
  color: var(--color-neutral-900);
  line-height: 1.2;
}

.klinik-details {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
}

.chip-reguler {
  background-color: var(--color-primary-600) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 600;
  font-size: 11px;
}

.chip-eksekutif {
  background-color: var(--color-secondary-600) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 600;
  font-size: 11px;
}

.kode-chip {
  font-size: 12px;
  font-weight: 600;
  color: var(--color-neutral-700);
  background: var(--color-neutral-400);
  padding: 2px 8px;
  border-radius: 4px;
}

.klinik-code {
  font-size: 14px;
  color: var(--color-neutral-600);
  margin: 4px 0 0 0;
  font-weight: 500;
}

.klinik-ruang-preview {
  flex: 1;
}

.ruang-count {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: var(--color-primary-600);
  margin-bottom: 12px;
}

.ruang-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.chip-preview {
  background-color: var(--color-primary-600) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 500;
  font-size: 12px;
}

.chip-more {
  background-color: var(--color-neutral-600) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 600;
  font-size: 12px;
}

.klinik-card-footer {
  margin-top: auto;
}

.btn-view {
  font-weight: 600;
  text-transform: none;
  letter-spacing: 0.5px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: var(--color-neutral-700);

  h3 {
    font-size: 24px;
    font-weight: 700;
    margin: 24px 0 8px 0;
    color: var(--color-neutral-800);
  }

  p {
    font-size: 16px;
    color: var(--color-neutral-600);
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-top: 24px;
}

.page-info {
  font-weight: 600;
  color: var(--color-neutral-800);
}

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

  .selection-header {
    flex-direction: row;
    padding: 12px 16px;
    height: auto;
    min-height: 64px;
  }

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

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

  .main-title {
    font-size: 20px;
    line-height: 28px;
  }

  .subtitle {
    font-size: 13px;
    line-height: 18px;
  }
}
</style>

