<script setup lang="ts">
import { ref, onMounted, defineAsyncComponent } from "vue";
import { useAppStore } from "@/stores/app.store";
import UnlockLayout from "@/layouts/UnlockLayout.vue";

const MainLayout = defineAsyncComponent(
  () => import("@/layouts/MainLayout.vue")
);
const ToolWindow = defineAsyncComponent(
  () => import("@/components/tools/ToolWindow.vue")
);
const DetachedSession = defineAsyncComponent(
  () => import("@/components/session/DetachedSession.vue")
);

const app = useAppStore();

// Tool window mode — detected from URL hash: #/tool/network-scanner?sessionId=abc
const isToolMode = ref(false);
const isDetachedMode = ref(false);
const toolName = ref("");
const toolSessionId = ref("");

onMounted(async () => {
  const hash = window.location.hash;
  if (hash.startsWith("#/tool/")) {
    isToolMode.value = true;
    const rest = hash.substring(7); // after "#/tool/"
    const [name, query] = rest.split("?");
    toolName.value = name;
    toolSessionId.value = new URLSearchParams(query || "").get("sessionId") || "";
  } else if (hash.startsWith("#/detached-session")) {
    isDetachedMode.value = true;
  } else {
    await app.checkVaultState();
  }
});
</script>

<template>
  <!-- Detached session window mode -->
  <DetachedSession v-if="isDetachedMode" />
  <!-- Tool popup window mode -->
  <ToolWindow v-else-if="isToolMode" :tool="toolName" :session-id="toolSessionId" />
  <!-- Normal app mode -->
  <div v-else class="app-root">
    <UnlockLayout v-if="!app.isUnlocked" />
    <MainLayout v-else />
  </div>
</template>

<style scoped>
.app-root {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
