<script setup>
import { onMounted, ref } from 'vue';

const nuxtApp = useNuxtApp();
const loading = ref(false);

nuxtApp.hook('page:start', () => {
  loading.value = true;
});
nuxtApp.hook('page:finish', () => {
  loading.value = false;
});

// Naikkan versi ini setiap kali ada perubahan struktur state (schema migration).
// Saat versi tidak cocok, semua cache Pinia akan dibersihkan otomatis.
const STORE_SCHEMA_VERSION = 3;
const VERSION_KEY = 'app-store-version';

// Daftar semua localStorage key yang dikelola oleh Pinia stores
const PINIA_STORE_KEYS = [
  'queue-store-state',
  'clinic-store-state',
  'doctor-store',
  'loket-store-state',
  'ruang-store-state',
  'klinikruang-store-state',
  'antrean-masuk-screen-store',
  'anjungan-store',
  'screen-store',
  'penunjang-store',
];

onMounted(() => {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return;

    const savedVersion = parseInt(localStorage.getItem(VERSION_KEY) || '0', 10);

    if (savedVersion < STORE_SCHEMA_VERSION) {
      // Versi lama terdeteksi → hapus semua cache Pinia sekaligus
      console.log(`[Migration] Store schema v${savedVersion} → v${STORE_SCHEMA_VERSION}. Clearing all caches...`);
      PINIA_STORE_KEYS.forEach(key => localStorage.removeItem(key));
      localStorage.setItem(VERSION_KEY, String(STORE_SCHEMA_VERSION));
      console.log('[Migration] Done. App will fetch fresh data from API.');
    }
  } catch (e) {
    // Ignore storage errors (e.g., private browsing mode)
  }
});
</script>

<template>
  <v-app>
    <v-overlay
      :model-value="loading"
      class="align-center justify-center"
      persistent
      z-index="9999"
    >
      <v-progress-circular
        color="primary"
        indeterminate
        size="64"
        width="6"
      ></v-progress-circular>
    </v-overlay>

    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </v-app>
</template>