const OPEN_SESSION_TERMINAL = 'overdeck:open-session-terminal'

/**
 * The terminal window lives in a persisted island outside the page's React tree, so the
 * session table reaches it through the document rather than through props.
 */
export function openSessionTerminal(sessionId: string): void {
  window.dispatchEvent(new CustomEvent<string>(OPEN_SESSION_TERMINAL, { detail: sessionId }))
}

export function subscribeToSessionTerminal(open: (sessionId: string) => void): () => void {
  const listener = (event: Event) => open((event as CustomEvent<string>).detail)
  window.addEventListener(OPEN_SESSION_TERMINAL, listener)
  return () => window.removeEventListener(OPEN_SESSION_TERMINAL, listener)
}
