<script setup lang="ts">
import { onBeforeUnmount, onMounted } from "vue";
import { ref } from "vue";
import { RefreshCw, WifiOff } from "@lucide/vue";
import { useAuthStore } from "./stores/auth";

const auth = useAuthStore();
const reconnecting = ref(false);
const retrySession = async () => {
  if (reconnecting.value || (typeof navigator !== "undefined" && !navigator.onLine)) return;
  reconnecting.value = true;
  try {
    await auth.loadSession(true);
  } finally {
    reconnecting.value = false;
  }
};
const handleOnline = () => void retrySession();

onMounted(() => window.addEventListener("online", handleOnline));
onBeforeUnmount(() => window.removeEventListener("online", handleOnline));
</script>

<template>
  <RouterView />
  <button
    v-if="auth.unavailable && auth.user"
    class="offline-status"
    role="status"
    aria-label="服务暂不可用，点击重连"
    title="服务暂不可用，点击重连"
    type="button"
    :disabled="reconnecting"
    @click="void retrySession()"
  >
    <WifiOff :size="16" />
    <span>{{ reconnecting ? "正在重连" : "服务暂不可用 · 点击重连" }}</span>
    <RefreshCw :size="14" :class="{ spinning: reconnecting }" />
  </button>
</template>
