<script setup lang="ts">
import { computed } from 'vue'
import { useAuthStore } from '@/stores'
import { Toaster } from 'vue-sonner'
import { CreateWalletFlow, LoginTab, OnboardingTab, RecoverWalletFlow } from './components'

const authStore = useAuthStore()
const router = useRouter()

// const neptuneWallet = useNeptuneWallet()

const currentState = computed(() => authStore.getCurrentState)

const handleGoToCreate = () => {
  authStore.goToCreate()
}

const handleGoToRecover = () => {
  authStore.goToRecover()
}

const handlePasswordSubmit = async (password: string) => {
  const loginRef = document.querySelector('login-tab') as any
  try {
    // TODO: Decrypt keystore with password
    // await neptuneWallet.decryptKeystore(password)
    // Mock success for now
    router.push({ name: 'home' })
  } catch (err) {
    if (loginRef) {
      loginRef.setError(true)
      loginRef.setLoading(false)
    }
    console.error('Failed to unlock wallet:', err)
  }
}

const handleAccessWallet = () => {
  router.push({ name: 'wallet' })
}

const handleCancel = () => {
  authStore.goBack()
}
</script>

<template>
  <div class="min-h-screen">
    <!-- Onboarding: Welcome screen -->
    <OnboardingTab
      v-if="currentState === 'onboarding'"
      @go-to-create="handleGoToCreate"
      @go-to-recover="handleGoToRecover"
    />

    <!-- Login: Unlock existing wallet -->
    <LoginTab
      v-else-if="currentState === 'login'"
      @go-to-create="handleGoToCreate"
      @submit="handlePasswordSubmit"
    />

    <!-- Create: New wallet creation flow -->
    <CreateWalletFlow
      v-else-if="currentState === 'create'"
      @navigate-to-recover="handleGoToRecover"
      @access-wallet="handleAccessWallet"
    />

    <!-- Recovery: Recover wallet from seed phrase -->
    <RecoverWalletFlow
      v-else-if="currentState === 'recovery'"
      @cancel="handleCancel"
      @access-wallet="handleAccessWallet"
    />

    <!-- Toast Notifications -->
    <Toaster position="top-center" :duration="3000" />
  </div>
</template>
