<script setup lang="ts">
import { useSystemStore } from '@/stores/systemStore'
import { startTimer, stopTimer } from 'libs/countdownTimer'
import { ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router'

const systemStore = useSystemStore()
const router = useRouter()
const timer = ref()
const websocketConnected = ref(true)

const countdownToReconnection = () => {
  startTimer(30 * 1000, (times: string) => {
    if (times === '0') {
      router.push('/login')
      return
    }
    timer.value = times
  })
}

watchEffect(() => {
  websocketConnected.value = systemStore.websocketConnected
  if (!systemStore.websocketConnected) {
    countdownToReconnection()
  }
  else {
    stopTimer()
  }
})
</script>

<template>
  <div v-if="!websocketConnected" class="reconnect-modal-overlay">
    <div class="reconnect-modal-container">
      <div class="reconnect-spinner" />
      <h2 class="reconnect-title">
        正在重连中 {{ timer }}
      </h2>
      <p class="reconnect-message">
        请稍候，系统正在尝试重新连接网络...
      </p>
    </div>
  </div>
</template>

<style scoped>
  .reconnect-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .reconnect-modal-container {
    background-color: white;
    border-radius: 12px;
    padding: 40px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
    text-align: center;
    animation: fadeIn 0.3s ease-out;
  }

  .reconnect-spinner {
    width: 64px;
    height: 64px;
    border: 6px solid #f3f3f3;
    border-radius: 50%;
    border-top: 6px solid #3b82f6;
    margin: 0 auto 24px;
    animation: spin 1s linear infinite;
  }

  .reconnect-title {
    font-size: 1.12rem;
    font-weight: bold;
    color: #1f2937;
    margin-bottom: 12px;
  }

  .reconnect-message {
  font-size: 16px;
  color: #4b5563;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  @keyframes fadeIn {
    from { opacity: 0; transform: scale(0.95); }
    to { opacity: 1; transform: scale(1); }
  }
</style>
