<script setup lang="ts">
import { onMounted, ref, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import Navbar from '@/components/layout/Navbar.vue'
import Footer from '@/components/layout/Footer.vue'
import LoginDialog from '@/components/auth/LoginDialog.vue'
import { Toaster } from '@/components/ui/sonner'
import 'vue-sonner/style.css'
import { auth } from '@/composables/useAuth'
import { useMarketPreloader } from '@/composables/useMarketPreloader'
import { nostrChat } from '@/composables/useNostrChat'
import { useRelayHub } from '@/composables/useRelayHub'
import { toast } from 'vue-sonner'

const route = useRoute()
const showLoginDialog = ref(false)

// Initialize preloader
const marketPreloader = useMarketPreloader()

// Initialize relay hub
const relayHub = useRelayHub()

// Hide navbar on login page
const showNavbar = computed(() => {
  return route.path !== '/login'
})

async function handleLoginSuccess() {
  showLoginDialog.value = false
  toast.success('Welcome back!')
  
  // Trigger preloading after successful login
  marketPreloader.preloadMarket()
  
  // Connect to chat
  if (!nostrChat.isConnected.value) {
    try {
      await nostrChat.connect()
      
      // Load peers and subscribe to all for notifications
      const peers = await nostrChat.loadPeers()
      await nostrChat.subscribeToAllPeersForNotifications(peers)
    } catch (error) {
      console.error('Failed to initialize chat:', error)
    }
  }
}

onMounted(async () => {
  // Initialize authentication
  try {
    await auth.initialize()
  } catch (error) {
    console.error('Failed to initialize authentication:', error)
  }

  // Initialize relay hub
  try {
    await relayHub.initialize()
    console.log('Relay hub initialized successfully')
  } catch (error) {
    console.error('Failed to initialize relay hub:', error)
  }
})

// Watch for authentication changes and trigger preloading
watch(() => auth.isAuthenticated.value, async (isAuthenticated) => {
  if (isAuthenticated) {
    if (!marketPreloader.isPreloaded.value) {
      console.log('User authenticated, triggering market preload...')
      marketPreloader.preloadMarket()
    }
    if (!nostrChat.isConnected.value) {
      console.log('User authenticated, connecting to chat...')
      try {
        await nostrChat.connect()
        
        // Load peers and subscribe to all for notifications
        const peers = await nostrChat.loadPeers()
        await nostrChat.subscribeToAllPeersForNotifications(peers)
      } catch (error) {
        console.error('Failed to initialize chat:', error)
      }
    }
  }
}, { immediate: true })
</script>

<template>
  <div class="min-h-screen bg-background font-sans antialiased">
    <div class="relative flex min-h-screen flex-col"
      style="padding-top: env(safe-area-inset-top); padding-bottom: env(safe-area-inset-bottom)">
      <header
        v-if="showNavbar"
        class="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
        <nav class="w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 xl:px-12 2xl:px-16 flex h-14 lg:h-16 xl:h-20 items-center justify-between">
          <Navbar />
        </nav>
      </header>

      <main class="flex-1">
        <router-view />
      </main>

      <Footer v-if="showNavbar" />
    </div>

    <!-- Toast notifications -->
    <Toaster />
    <!-- Login dialog -->
    <LoginDialog v-model:is-open="showLoginDialog" @success="handleLoginSuccess" />
  </div>
</template>
