<script setup lang="ts">
import { computed, 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();
type RendererWindowMode = "auto" | "login" | "main";

interface WindowModeBridge {
  setWindowMode?: (
    mode: "login" | "main",
    request?: { source?: "auth-state" | "login" | "logout"; animate?: boolean },
  ) => Promise<unknown>;
}

function resolveRendererWindowMode(): RendererWindowMode {
  const mode = new URLSearchParams(window.location.search).get("window");
  return mode === "login" || mode === "main" ? mode : "auto";
}

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", { source: "auth-state" });
}

const rendererWindowMode = resolveRendererWindowMode();
const usesAutomaticWindowMode = rendererWindowMode === "auto";
const showsMainSurface = computed(() =>
  rendererWindowMode === "main" || (rendererWindowMode === "auto" && isAuthenticated.value),
);

if (usesAutomaticWindowMode) {
  syncWindowMode(isAuthenticated.value);
  watch(isAuthenticated, (next) => syncWindowMode(next));
}

if (rendererWindowMode === "main") {
  if (!isAuthenticated.value) {
    syncWindowMode(false);
  }
  watch(isAuthenticated, (next) => {
    if (!next) {
      syncWindowMode(false);
    }
  });
}

onMounted(() => {
  if (rendererWindowMode !== "login") {
    void syncRuntimeSession();
  }
  if (usesAutomaticWindowMode) {
    syncWindowMode(isAuthenticated.value);
  }
});
</script>

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