<template>

  <div id="app" class="flex flex-col h-screen bg-gray-300">
    <!-- MenuBar всегда фиксирован сверху -->
    <MenuBar class="w-full sticky  hidden lg:block top-0 z-10"/>
    <ToolBar class=" fixed  visible lg:invisible bottom-0 z-10"/>

    <!-- Контентная часть заполняет оставшееся пространство -->
    <div class="flex-grow gap-4 ">
      <!--      {{  tg_id }}-->
      <Button label="Sub" :class="checkNotif ? 'flex' : '!hidden'" @click="checkSubscribe"/>
      <router-view/>
      <div class="bg-gray-100 h-12 block lg:hidden"></div>
    </div>

    <TransactionForm v-if="visible" :visible="visible"
                     :transaction-type="drawerStore.transactionType ? drawerStore.transactionType : 'INSTANT'"
                     :category-type="drawerStore.categoryType ? drawerStore.categoryType : 'EXPENSE'" @close-drawer="closeDrawer"/>

  </div>
</template>

<script setup lang="ts">
import MenuBar from "./components/MenuBar.vue";
import ToolBar from "@/components/ToolBar.vue";
import Button from "primevue/button";
import {computed, onMounted} from "vue";
import {subscribeUserToPush} from "@/services/pushManager";
import apiClient from '@/services/axiosSetup';
import {useUserStore} from "@/stores/userStore";
import {useDrawerStore} from '@/stores/drawerStore'
import TransactionForm from "@/components/TransactionForm.vue";


const drawerStore = useDrawerStore();
const visible = computed(() => drawerStore.visible);
const closeDrawer = () => {
  drawerStore.setVisible(false);
};

const checkNotif = computed(() => {

  return !tg_id.value && 'Notification' in window && Notification.permission === 'default'
})

const tg_id = computed(() => {
  if (window.Telegram?.WebApp) {
    const tg = window.Telegram.WebApp;
    tg.expand();  // Разворачиваем приложение на весь экран
    return tg.initDataUnsafe.user?.id ?? null;  // Если tg_id нет, возвращаем null
  }
  return null;
});

const checkSubscribe = async () => {
  if ("Notification" in window) {
    if (Notification.permission === 'default') {
      await Notification.requestPermission().then(sendSubscribe)
    } else if (Notification.permission === 'granted') {
      await sendSubscribe()
    } else {
      // Пользователь ранее отклонил запрос
    }
  } else {
    console.log("Notification API is not supported in this browser.");
    // You may want to use an alternative method, like alerts or modals
  }
}

const sendSubscribe = async () => {
  try {
    const subscription = await subscribeUserToPush();
    console.log("Push subscription:", subscription);

    // Отправка подписки на сервер для хранения
    await apiClient.post("/push/subscribe", subscription)
  } catch (error) {
    console.error("Failed to subscribe to push:", error);
  }
}

console.log('vyzyvaem app')
const userStore = useUserStore();
const user = computed(() => userStore.user);
console.log('vyzvali app')

onMounted(async () => {
  console.log("Загружаем данные при монтировании...");
  if (!userStore.user) {
    console.log('vyzyvaem app2')
    await userStore.fetchUserProfile();
    console.log('vyzvali app2')
  }
  await checkSubscribe();
});


// @Options({
//   components: {
//     TransactionEditDrawer, SpeedDial,
//     MenuBar,
//   },
// })
// export default class App extends Vue {}
</script>

<style scoped>
/* Пример настройки высоты для поддержки flexbox */
#app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}
</style>
