"use client";

import { useEffect } from "react";

const ROOT_STATE_KEY = "zimphonyWorkspaceRoot";
const GUARD_STATE_KEY = "zimphonyWorkspaceExitGuard";

type HistoryState = Record<string, unknown>;

function currentState(): HistoryState {
  const state = window.history.state;
  return state && typeof state === "object" ? { ...state } : {};
}

function isStandaloneDisplay() {
  return window.matchMedia("(display-mode: standalone)").matches || Boolean((navigator as Navigator & { standalone?: boolean }).standalone);
}

export function BrowserExitGuard() {
  useEffect(() => {
    if (isStandaloneDisplay()) return;

    const rootState = { ...currentState(), [ROOT_STATE_KEY]: true };
    const guardState = { ...rootState, [GUARD_STATE_KEY]: true };
    window.history.replaceState(rootState, "", window.location.href);
    window.history.pushState(guardState, "", window.location.href);

    const restoreWorkspace = (event: PopStateEvent) => {
      const state = event.state as HistoryState | null;
      if (state?.[GUARD_STATE_KEY]) return;

      // Keep a browser Back gesture inside the authenticated workspace instead
      // of leaving for the site visited before webmail.
      window.history.pushState(guardState, "", window.location.href);
    };

    window.addEventListener("popstate", restoreWorkspace);
    return () => window.removeEventListener("popstate", restoreWorkspace);
  }, []);

  return null;
}
