<script setup lang="ts">
import SpaceList from "@/components/space-list/SpaceList.vue";
import { useSpaceStore } from "@/stores/spaceStore";
import { computed, onMounted, onBeforeUnmount, ref } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { useToolbarStore } from "@/stores/toolbar-store";
import router from "@/router";
import {useRoute} from "vue-router"; // если у тебя index.ts экспортирует по умолчанию, можно без /index.js

const spaceStore = useSpaceStore();
const toolbarStore = useToolbarStore();
const route = useRoute();

// true/false, есть ли Telegram WebApp
const isTelegram = computed(() => !!(window as any)?.Telegram?.WebApp);

const isSpaceSelectorVisible = ref(false);
const isSpaceSelected = computed(
    () => spaceStore.selectedSpaceId === undefined || isSpaceSelectorVisible.value
);

const menu = [
  { name: "Dashboard",    icon: "pi pi-chart-bar", link: "/" },
  { name: "Transactions", icon: "pi pi-cog",       link: "/transactions" },
  { name: "Settings",     icon: "pi pi-list",      link: "/settings" },
];

function spaceSelected() {
  router.push("/");
  isSpaceSelectorVisible.value = false;
}

onMounted(() => {
  toolbarStore.registerHandler("openSpacePicker", () => {
    isSpaceSelectorVisible.value = true;
  });

  const tgApp = (window as any)?.Telegram?.WebApp;
  if (tgApp) {
    try {

      tgApp.expand?.();          // более мягкий вариант, чем requestFullscreen()
      tgApp.requestFullscreen?.();
      tgApp.lockOrientation?.();
      if (route.path != '/') {
        tgApp.BackButton.show()
        // при нажатии — возвращаемся назад
        const handleBack = () => {
          // например, переход на предыдущий маршрут
          if (window.history.length > 1) {
            router.back();
          } else {
            tg.BackButton.hide();
          }
        };

        tg.BackButton.onClick(handleBack);
      }
      tgApp.ready();
    } catch {
      /* ignore */
    }
  }
});

onBeforeUnmount(() => {
  toolbarStore.unregisterHandler("openSpacePicker");
});
</script>

<template>
  <div class="flex flex-col tg">
    <SpaceList v-if="isSpaceSelected" @space-selected="spaceSelected" />

    <div v-else class="flex flex-col w-full gap-4">
      <div class="w-full flex flex-row items-end justify-end pt-4 pe-4">
        <Toolbar />
      </div>

      <div class="flex flex-col w-full h-full items-end px-4 gap-4">
        <router-view class="w-full" />
      </div>

      <nav class="fixed inset-x-0 bottom-0 z-50 h-16 bg-white px-10">
        <div class="flex h-full items-center justify-between">
          <router-link
              v-for="item in menu"
              :key="item.link"
              :to="item.link"
              class="flex w-fit flex-col items-center gap-2"
          >
            <i class="!text-lg" :class="item.icon" />
            <span class=" font-medium text-gray-900">{{ item.name }}</span>
          </router-link>
        </div>
      </nav>

      <!-- отступ под нижний navbar, чтобы контент не перекрывался -->
      <div class="h-16" />
    </div>
  </div>
</template>

<style scoped>
/* Порядок отступов: top right bottom left */
.tg {
  width: 100% !important;
  padding:
      var(--tg-content-safe-area-inset-top)
      var(--tg-content-safe-area-inset-right)
      var(--tg-content-safe-area-inset-bottom)
      var(--tg-content-safe-area-inset-left) !important;
}
</style>