"use client";

import { createContext, useContext, type ReactNode } from "react";

// The z-index of the nearest stacking surface (a drawer panel, a modal) that a
// body-portaled popover is rendered from within. Popovers — ActionMenu, pickers,
// tooltips — portal to `document.body` at a fixed floating-layer z-index (90) so
// they escape a host's `overflow` clip. That flat z-index works everywhere the
// surface behind them sits below 90 — but a *nested* SessionDrawer stacks at
// `40 + depth * 100` (140 at depth 1, 240 at depth 2, …), which climbs over the
// popover layer. A menu opened inside such a drawer then renders BEHIND the
// panel and reads as "nothing happens on click".
//
// A surface that can outrank the popover layer wraps its content in
// `<SurfaceZIndexProvider value={panelZ}>`; a popover reads `useSurfaceZIndex()`
// and lifts its own z-index just above that surface, so it always sits over the
// drawer it was opened from — at any nesting depth. Default `0` means "no
// outranking surface", so any popover outside a provider keeps the plain
// floating-layer z-index.

const SurfaceZIndexContext = createContext<number>(0);

export function SurfaceZIndexProvider({
  value,
  children,
}: {
  value: number;
  children: ReactNode;
}) {
  return (
    <SurfaceZIndexContext.Provider value={value}>
      {children}
    </SurfaceZIndexContext.Provider>
  );
}

export function useSurfaceZIndex(): number {
  return useContext(SurfaceZIndexContext);
}

// The floating-layer z-index shared by body-portaled popovers (ActionMenu,
// pickers, tooltips). Exported so the popovers agree on one base.
export const POPOVER_Z_INDEX = 90;

/**
 * The default z-index of a centred modal dialog (`DialogShell`,
 * `ConfirmDialog`): above top-level drawers (z-50) and the floating popover
 * layer ({@link POPOVER_Z_INDEX}).
 */
export const DIALOG_Z_INDEX = 110;

/**
 * The z-index a body-portaled popover should use so it sits above both the
 * shared floating layer and any outranking surface it was opened from within.
 *
 * @param surfaceZ - the surrounding surface z-index from {@link useSurfaceZIndex}
 *   (`0` when there is none).
 * @returns `POPOVER_Z_INDEX` outside any outranking surface, else one above it.
 */
export function popoverZIndex(surfaceZ: number): number {
  return Math.max(POPOVER_Z_INDEX, surfaceZ + 1);
}
