import { useEffect, useRef } from 'react';
import { useGlobal } from 'hooks/useGlobal';

// ── "A panel has taken the whole window" ──
//
// Read by the app shell, written by whichever `WorkspaceView` owns the maximized panel. It has to be a
// global rather than context or a prop, for two reasons that both point the same way:
//
// - `DashboardLayout` renders the nav Header *above* every screen, so it is an ancestor of the
//   `WorkspaceView` doing the maximizing. Nothing flows upward.
// - CSS cannot do it either. The content region is `absolute inset-0 z-2` and the Header is a `fixed
//   z-10` sibling, so the region is a stacking context the panel can never paint out of however high
//   its own z-index — which is exactly why plain maximize stops at `top-[56px]`. The panel does not
//   cover the header; the shell stands the header down.
//
// In memory only, deliberately: this is derived from the maximize state that IS persisted per tab, so a
// reload republishes it from `WorkspaceView` a frame later. Persisting it separately would be a second
// copy of one fact, and the failure mode of a stale copy is a screen with no header and nothing
// maximized to explain it.
const PANEL_FULLSCREEN = 'PANEL_FULLSCREEN';

/** Whether a panel is currently filling the window. For the shell — the chrome that has to get out of the way. */
export const usePanelFullscreen = () => useGlobal<boolean>(PANEL_FULLSCREEN, false)[0];

/**
 * Publish this workspace's fullscreen state, and stand it down when the workspace goes away.
 *
 * The cleanup is the load-bearing half: navigating off a screen with a fullscreen panel unmounts the
 * view without anything clicking Restore, and a flag left set is an app with no header and no way to
 * get one back short of a reload.
 */
export function usePublishPanelFullscreen(active: boolean) {
  const [, setActive] = useGlobal<boolean>(PANEL_FULLSCREEN, false);

  // Through a ref: `useGlobal` rebuilds its setter every render, so as a dependency it would re-run this
  // effect — and therefore the cleanup's `false` — on every render of the workspace.
  const setActiveRef = useRef(setActive);
  setActiveRef.current = setActive;

  useEffect(() => {
    setActiveRef.current(active);
    return () => setActiveRef.current(false);
  }, [active]);
}
