<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import LockScreen from '@/components/LockScreen.vue'

const authStore = useAuthStore()
const isLocked = ref(false)
const lastActiveTime = ref(Date.now())
const LOCK_TIMEOUT = 30000 // 30 seconds of inactivity

// Check if lock is enabled
const lockEnabled = computed(() => {
  return localStorage.getItem('lockMethod') && 
         localStorage.getItem('lockMethod') !== 'none' &&
         authStore.isAuthenticated
})

onMounted(async () => {
  if (authStore.hasStoredToken) {
    await authStore.fetchCurrentUser()
  }
  
  // Check if we should show lock screen on app start
  if (lockEnabled.value) {
    const lastUnlock = localStorage.getItem('lastUnlockTime')
    const now = Date.now()
    
    // Lock if no previous unlock or more than 30 seconds ago
    if (!lastUnlock || (now - parseInt(lastUnlock)) > LOCK_TIMEOUT) {
      isLocked.value = true
    }
  }
  
  // Listen for visibility changes (app goes to background/foreground)
  document.addEventListener('visibilitychange', handleVisibilityChange)
  
  // Track user activity
  document.addEventListener('touchstart', updateLastActive)
  document.addEventListener('click', updateLastActive)
  document.addEventListener('keydown', updateLastActive)
})

onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  document.removeEventListener('touchstart', updateLastActive)
  document.removeEventListener('click', updateLastActive)
  document.removeEventListener('keydown', updateLastActive)
})

function updateLastActive() {
  lastActiveTime.value = Date.now()
}

function handleVisibilityChange() {
  if (document.visibilityState === 'hidden') {
    // App went to background - record time
    localStorage.setItem('backgroundTime', String(Date.now()))
  } else if (document.visibilityState === 'visible') {
    // App came back to foreground
    if (lockEnabled.value) {
      const backgroundTime = localStorage.getItem('backgroundTime')
      const now = Date.now()
      
      // Lock if was in background for more than 30 seconds
      if (backgroundTime && (now - parseInt(backgroundTime)) > LOCK_TIMEOUT) {
        isLocked.value = true
      }
    }
  }
}

function handleUnlock() {
  isLocked.value = false
  localStorage.setItem('lastUnlockTime', String(Date.now()))
}
</script>

<template>
  <!-- Lock Screen Overlay -->
  <LockScreen 
    v-if="isLocked && lockEnabled" 
    @unlocked="handleUnlock" 
  />
  
  <!-- Main App -->
  <router-view v-show="!isLocked || !lockEnabled" />
</template>
