<!-- @format -->
<script lang="ts">
  import { onMount } from "svelte";
  import {
    getSessionPassword,
    clearVaultSession,
    flushBeforeClose,
  } from "$lib/stores/session";
  import { persistAndClearVault } from "$lib/backend/auth";
  import { hydrateUiSettings } from "$lib/stores/settings";
  import { invoke, isTauriRuntime } from "$lib/runtime/invoke";

  let closeInProgress = false;

  async function persistSession(keepalive = false): Promise<void> {
    if (closeInProgress) return;
    closeInProgress = true;

    try {
      await flushBeforeClose();
    } catch {
      // best effort
    }

    const password = getSessionPassword();
    if (!password) {
      return;
    }

    try {
      await persistAndClearVault(password, { keepalive });
      clearVaultSession();
    } catch (error) {
      console.error("Vault persistence on exit failed:", error);
    }
  }

  onMount(() => {
    void hydrateUiSettings();

    if (isTauriRuntime()) {
      const unlistenPromise = (async () => {
        const tauriWindow = await import("@tauri-apps/api/window");
        const appWindow = tauriWindow.getCurrentWindow();
        return appWindow.onCloseRequested(async (event) => {
          if (closeInProgress) return;
          event.preventDefault();

          await persistSession();
          await invoke("shutdown");
        });
      })();

      return () => {
        void unlistenPromise.then((unlisten) => unlisten());
      };
    }

    const handlePageHide = () => {
      void persistSession(true);
    };

    const handleBeforeUnload = () => {
      void persistSession(true);
    };

    window.addEventListener("pagehide", handlePageHide);
    window.addEventListener("beforeunload", handleBeforeUnload);

    return () => {
      window.removeEventListener("pagehide", handlePageHide);
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  });
</script>

<slot />
