import { useCallback } from 'react';
import { useWorkspace } from '../../components/Workspace';
import { useGlobal } from 'hooks/useGlobal';
import type { TerminalConnectionState } from './Terminal';
import { TerminalView } from './Terminal';
import { terminalStateKey } from './state-key';
import { useTerminalSession } from './use-terminal-session';

// This one kept the unmount cleanup the other two wrappers had already removed, so every layout or route
// change dropped its `panelId → sessionId` entry, minted a new uuid on the way back, and left the previous
// host shell running with nothing pointing at it. It now forgets the session where the others do: when the
// panel is actually closed.
export const HostTerminalWrapper = ({ panelId }: { panelId: string }) => {
  const { workspace, cwd } = useWorkspace();
  const sessionId = useTerminalSession(panelId, terminalStateKey('host-terminals', workspace));

  const [, setConnState] = useGlobal<TerminalConnectionState>(`terminal-conn-${panelId}`, 'disconnected');
  const onConnectionChange = useCallback((state: TerminalConnectionState) => setConnState(state), [setConnState]);

  if (!sessionId) return null;

  return (
    <TerminalView
      className="h-full w-full p-2"
      sessionId={sessionId}
      cwd={cwd}
      onConnectionChange={onConnectionChange}
    />
  );
};
