import { useEffect, useRef } from 'react';

import { useWorkspace } from './WorkspaceContext';

/**
 * Say what to do when this panel is deliberately closed — removed from the workspace, or handed to a
 * different app. Use it to release whatever the panel owns on the server: a pty, a lock, a job.
 *
 * **This is not an unmount hook, and it is deliberately not one.** A panel unmounts when it is dragged
 * to a new position, when the mobile view switches panels, when a parent re-renders it under a new key
 * — all of which look identical to a close from inside the component. `movePanel` even mints a new panel
 * id on the way (see `layout-utils.test.ts`), so the layout cannot be asked either. Only the two call
 * sites that carry the intent can answer, so only they fire this. The cost of getting it wrong is a
 * killed terminal or a dropped session, which is why the framework refuses to guess.
 *
 * Consequences worth knowing before you use it:
 *
 * - The handler runs *while the panel is being torn down*, so it must not set React state. Call an API,
 *   close a socket, drop a map entry — nothing that expects a render afterwards.
 * - Registration is never undone. A component that unmounts leaves its handler in place, because
 *   "unmounted" is exactly the signal we are refusing to trust; re-registering for the same panel id
 *   replaces it. Handlers are scoped to the workspace they were registered on, and one only ever fires
 *   for the panel id it was registered under.
 * - `handler` does not need to be memoised — the latest one always runs.
 * - Nothing fires in a locked or inert workspace, where no panel can be closed in the first place.
 *
 * A panel that is a *pointer* to server-side state rather than the owner of it should not use this at
 * all. Closing a chat panel must not delete the session it points at.
 */
export function usePanelClose(panelId: string, handler: () => void): void {
  const { registerPanelClose } = useWorkspace();
  const latest = useRef(handler);
  latest.current = handler;

  useEffect(() => {
    registerPanelClose(panelId, () => latest.current());
  }, [panelId, registerPanelClose]);
}
