<script setup lang="ts">
import { defineAsyncComponent, onMounted, watch } from "vue";
import { useDesktopSession } from "./composables/useDesktopSession";

const DesktopShell = defineAsyncComponent(() => import("./components/DesktopShell.vue"));
const LoginView = defineAsyncComponent(() => import("./views/LoginView.vue"));

const { isAuthenticated, syncRuntimeSession } = useDesktopSession();

interface WindowModeBridge {
  setWindowMode?: (mode: "login" | "main") => Promise<unknown>;
}

function getModeBridge(): WindowModeBridge | undefined {
  return (globalThis as unknown as {
    desktopBridge?: { app?: WindowModeBridge };
  }).desktopBridge?.app;
}

function syncWindowMode(authenticated: boolean): void {
  void getModeBridge()?.setWindowMode?.(authenticated ? "main" : "login");
}

// Fire immediately during setup so the main process can size + reveal the
// window before the user sees any "wrong-sized" frame.
syncWindowMode(isAuthenticated.value);
watch(isAuthenticated, (next) => syncWindowMode(next));

onMounted(() => {
  void syncRuntimeSession();
  syncWindowMode(isAuthenticated.value);
});
</script>

<template>
  <DesktopShell v-if="isAuthenticated" />
  <LoginView v-else />
</template>
