type ModeId = 'agent' | 'plan'

interface UiState {
  ui: {
    mode: ModeId
  }
}

type UiAgent = Readonly<{
  getMode?: () => string
  setMode?: (modeId: ModeId) => void
}>

export function createUiState(
  opts: Readonly<{
    state: UiState
    agent: UiAgent
  }>,
): Readonly<{
  setMode: (modeId: ModeId) => void
  getMode: () => ModeId
}> {
  function setMode(modeId: ModeId): void {
    opts.state.ui.mode = modeId
    if (typeof opts.agent.setMode === 'function') opts.agent.setMode(modeId)
  }

  function getMode(): ModeId {
    if (typeof opts.agent.getMode === 'function')
      return (opts.agent.getMode() as ModeId) || 'agent'
    return opts.state.ui.mode ?? 'agent'
  }

  return {
    setMode,
    getMode,
  }
}
