<template>
  <div v-if="isAuthenticated" class="app-layout">
    <RouterView v-slot="{ Component }">
      <keep-alive include="RealTimePremium">
        <component :is="Component" />
      </keep-alive>
    </RouterView>
  </div>
  <div v-else class="access-gate">
    <div class="access-card">
      <div class="lock-icon">🔒</div>
      <p class="access-tip">请输入访问口令</p>
      <el-input
        v-model="password"
        type="password"
        placeholder="请输入口令"
        size="large"
        @keyup.enter="verifyPassword"
      />
      <el-button
        type="primary"
        size="large"
        class="access-btn"
        @click="verifyPassword"
      >
        进入系统
      </el-button>
      <p v-if="error" class="error-msg">口令错误，请重试</p>
    </div>
  </div>
</template>

<script setup name="myApp">
import { ref } from 'vue'

const ACCESS_PASSWORD = '88'
const STORAGE_KEY = 'lof_access_granted'
const EXPIRY_HOURS = 24

const password = ref('')
const error = ref(false)

function isAuthValid() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return false
    const data = JSON.parse(raw)
    if (!data || !data.granted) return false
    const elapsed = Date.now() - data.time
    return elapsed < EXPIRY_HOURS * 3600 * 1000
  } catch {
    return false
  }
}

const isAuthenticated = ref(isAuthValid())

function verifyPassword() {
  if (password.value === ACCESS_PASSWORD) {
    isAuthenticated.value = true
    error.value = false
    localStorage.setItem(STORAGE_KEY, JSON.stringify({
      granted: true,
      time: Date.now()
    }))
  } else {
    error.value = true
    password.value = ''
  }
}
</script>

<style scoped>
.app-layout {
  min-height: 100vh;
  background: var(--bg-primary);
}
.access-gate {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: var(--bg-primary);
  padding: 16px;
}
.access-card {
  background: var(--bg-secondary);
  border-radius: 16px;
  padding: 48px 40px;
  width: 400px;
  max-width: 100%;
  border: 1px solid var(--border-color);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
  text-align: center;
}
.lock-icon {
  font-size: 56px;
  margin-bottom: 8px;
}
.access-tip {
  margin: 0 0 24px;
  color: var(--text-secondary);
  font-size: 14px;
}
.access-btn {
  margin-top: 16px;
  width: 100%;
}
.error-msg {
  color: var(--danger) !important;
  margin-top: 12px !important;
  margin-bottom: 0 !important;
  font-size: 13px !important;
}

@media (max-width: 480px) {
  .access-card {
    padding: 32px 24px;
  }
  .lock-icon {
    font-size: 40px;
  }
}
</style>
