<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useAuthStore } from '../stores/auth'
import Card from 'primevue/card'
import ProgressSpinner from 'primevue/progressspinner'

const auth = useAuthStore()
const loading = ref(false)
const error = ref('')
const botUserName = import.meta.env.VITE_TELEGRAM_BOT_USERNAME

// Telegram Login Widget callback — must be global
;(window as any).onTelegramAuth = async (user: TelegramLoginData) => {
  loading.value = true
  error.value = ''
  try {
    await auth.loginWithTelegram(user)
  } catch (e: any) {
    error.value = e.response?.data?.detail || 'Authorization failed'
    loading.value = false
  }
}

onMounted(async () => {
  console.log(botUserName)
  // Check if running inside Telegram WebApp
  const webapp = window.Telegram?.WebApp
  if (webapp?.initData) {
    loading.value = true
    webapp.ready()
    webapp.expand()
    try {
      await auth.loginWithWebApp(webapp.initData)
    } catch (e: any) {
      error.value = e.response?.data?.detail || 'WebApp authorization failed'
      loading.value = false
    }
    return
  }

  // Render Telegram Login Widget for browser users
  const container = document.getElementById('telegram-login-container')
  if (container) {
    const script = document.createElement('script')
    script.src = 'https://telegram.org/js/telegram-widget.js?22'
    console.log()
    script.setAttribute('data-telegram-login', botUserName || '')
    script.setAttribute('data-size', 'large')
    script.setAttribute('data-radius', '8')
    script.setAttribute('data-onauth', 'onTelegramAuth(user)')
    script.setAttribute('data-request-access', 'write')
    script.async = true
    container.appendChild(script)
  }
})
</script>

<template>
  <div class="flex items-center justify-center min-h-[80vh]">
    <Card class="w-full max-w-md">
      <template #title>
        <div class="text-center">
          <span class="text-primary text-3xl font-bold">VeloBrain</span>
          <p class="text-surface-500 text-sm mt-2">AI-Powered Cycling Training Platform</p>
        </div>
      </template>
      <template #content>
        <div class="flex flex-col items-center gap-4">
          <div v-if="loading" class="flex flex-col items-center gap-3">
            <ProgressSpinner style="width: 50px; height: 50px" />
            <p class="text-surface-500 text-sm">Signing in via Telegram...</p>
          </div>
          <div v-else>
            <p v-if="error" class="text-red-500 text-sm mb-4 text-center">{{ error }}</p>
            <div id="telegram-login-container" class="flex justify-center"></div>
          </div>
        </div>
      </template>
    </Card>
  </div>
</template>
