<script setup lang="ts">
import {onMounted, ref} from "vue"
import {useRouter} from "vue-router";
import {Button, InputText, Password} from "primevue";
import {useUserStore} from "@/stores/userStore";

const router = useRouter()

// необязательно делать реактивным, но удобно для шаблона
const tgApp = (window as any)?.Telegram?.WebApp;
const tgData = ref()
const errors = ref({username: '', password: ''})
const loading = ref(false)

const username = ref<string>('')
const password = ref<string>('')

const userStore = useUserStore()

const telegramBtn = ref(null)

async function onTelegramAuth(user) {
  console.log('TG login success', user)
  // alert(`Logged in as ${user.first_name} (@${user.username})`)
  // 👉 здесь отправляешь user.auth_data на бэк для проверки Telegram-sign
  await userStore.tgLogin(user.id, user.first_name, user.last_name, user.username, user.photo_url, user.auth_date, user.hash)
}

onMounted(async () => {

  // передаём функцию глобально чтобы виджет её увидел
  window.onTelegramAuth = onTelegramAuth

  const script = document.createElement("script")
  script.src = "https://telegram.org/js/telegram-widget.js?22"
  script.setAttribute("data-telegram-login", "luminicspacebot") // ← твой bot
  script.setAttribute("data-size", "medium")
  script.setAttribute("data-onauth", "onTelegramAuth(user)")
  script.setAttribute("data-request-access", "write")
  script.async = true

  telegramBtn.value.appendChild(script)

  // сообщаем Telegram WebApp, что UI готов
  console.log(tgApp.initData)
  if (tgApp.initData) {
    tgData.value = tgApp.initDataUnsafe
    console.log(tgApp.initData)
    if (tgData.value.user?.id != null) {
      let user = tgData.value.user
      await userStore.tgLoginData(tgApp.initData, tgData.value.hash)
    }
  } else {

  }
  // router.push('/')
})
</script>

<template>
  <div class="login">
    {{tgApp.initData}}
    <div ref="telegramBtn"></div>
  </div>
  <div class="flex !w-full items-center justify-center h-100">
    <div class="card !w-fit">
      <div class="login">
        <div ref="telegramBtn"></div>
      </div>
    </div>
  </div>
<!--      <h1 class="text-2xl font-bold text-center">Вход</h1>-->


<!--      <form @submit.prevent="userStore.login(username, password)" class="flex  flex-col !gap-6 !w-fit !p-10">-->
<!--        <div class="!w-full">-->
<!--          <label for="username" class="block text-sm font-semibold text-gray-700">Логин</label>-->
<!--          <InputText id="username" v-model.trim="username" class="w-full" :class="{'p-invalid': errors.username}"/>-->
<!--          <small v-if="errors.username" class="text-red-500">{{ errors.username }}</small>-->
<!--        </div>-->

<!--        <div class="mb-6">-->
<!--          <label for="password" class="block text-sm font-semibold text-gray-700">Пароль</label>-->
<!--          <Password id="password" v-model="password" class="w-full" :feedback="false" toggleMask/>-->
<!--          <small v-if="errors.password" class="text-red-500">{{ errors.password }}</small>-->
<!--        </div>-->

<!--        <Button label="Войти" type="submit" class="w-full mt-2 !bg-blue-300 hover:!bg-blue-400 !border-blue-300"-->
<!--                :disabled="loading" :loading="loading"/>-->
<!--      </form>-->


<!--      <p class="mt-4 text-sm text-center text-gray-600">-->
<!--        Нет аккаунта?-->
<!--        <RouterLink to="/register" class="text-blue-500 hover:underline">Регистрация</RouterLink>-->
<!--      </p>-->


<!--    </div>-->
<!--  </div>-->
</template>

<style scoped>
</style>